From 78f4dd8be6add8634f5332c42f59022de3c0f67f Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 23 Feb 2023 14:51:26 +0800 Subject: [PATCH] [native] Merge some optimizations from new serialization task (#14338) * [native] Merge some optimizations from new serialization task - Optimize the loading time of loading scene which has plenty of nodes. --- cocos/scene-graph/node.jsb.ts | 84 +++---- cocos/scene-graph/scene.jsb.ts | 11 +- native/CMakeLists.txt | 1 + native/cocos/base/HasMemberFunction.h | 97 ++++++++ native/cocos/base/std/variant.h | 12 +- native/cocos/bindings/auto/jsb_scene_auto.cpp | 64 ------ .../cocos/bindings/jswrapper/PrivateObject.h | 12 +- native/cocos/bindings/jswrapper/v8/Class.cpp | 56 +++-- native/cocos/bindings/jswrapper/v8/Class.h | 124 +++++----- .../bindings/jswrapper/v8/HelperMacros.cpp | 19 +- .../bindings/jswrapper/v8/HelperMacros.h | 5 +- native/cocos/bindings/jswrapper/v8/Object.h | 12 +- native/cocos/bindings/jswrapper/v8/Utils.cpp | 62 +++-- .../cocos/bindings/manual/jsb_conversions.h | 55 ++++- native/cocos/bindings/manual/jsb_global.h | 8 +- .../bindings/manual/jsb_scene_manual.cpp | 214 +++++++++--------- native/cocos/bindings/sebind/class_v8.h | 2 +- native/cocos/core/TypedArray.h | 6 +- native/cocos/core/data/Object.h | 31 ++- native/cocos/core/scene-graph/Node.cpp | 4 +- native/cocos/core/scene-graph/Node.h | 11 +- .../src/base_has_member_function_test.cpp | 159 +++++++++++++ native/tools/swig-config/cocos.i | 3 + native/tools/swig-config/scene.i | 1 + 24 files changed, 673 insertions(+), 380 deletions(-) create mode 100644 native/cocos/base/HasMemberFunction.h create mode 100644 native/tests/unit-test/src/base_has_member_function_test.cpp diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index 7edbc71670..4aa7e12241 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -238,10 +238,8 @@ const REGISTERED_EVENT_MASK_TRANSFORM_CHANGED = (1 << 0); const REGISTERED_EVENT_MASK_PARENT_CHANGED = (1 << 1); const REGISTERED_EVENT_MASK_MOBILITY_CHANGED = (1 << 2); const REGISTERED_EVENT_MASK_LAYER_CHANGED = (1 << 3); -const REGISTERED_EVENT_MASK_CHILD_REMOVED_CHANGED = (1 << 4); -const REGISTERED_EVENT_MASK_CHILD_ADDED_CHANGED = (1 << 5); -const REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED_CHANGED = (1 << 6); -const REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED = (1 << 7); +const REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED = (1 << 4); +const REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED = (1 << 5); nodeProto.on = function (type, callback, target, useCapture: any = false) { switch (type) { @@ -270,22 +268,10 @@ nodeProto.on = function (type, callback, target, useCapture: any = false) { this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_LAYER_CHANGED; } break; - case NodeEventType.CHILD_REMOVED: - if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_CHILD_REMOVED_CHANGED)) { - this._registerOnChildRemoved(); - this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_CHILD_REMOVED_CHANGED; - } - break; - case NodeEventType.CHILD_ADDED: - if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_CHILD_ADDED_CHANGED)) { - this._registerOnChildAdded(); - this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_CHILD_ADDED_CHANGED; - } - break; case NodeEventType.SIBLING_ORDER_CHANGED: - if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED_CHANGED)) { + if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED)) { this._registerOnSiblingOrderChanged(); - this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED_CHANGED; + this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED; } break; case NodeEventType.LIGHT_PROBE_BAKING_CHANGED: @@ -438,23 +424,20 @@ nodeProto._onLayerChanged = function (layer) { }; nodeProto._onChildRemoved = function (child) { + const removeAt = this._children.indexOf(child); + if (removeAt < 0) { + errorID(1633); + return; + } + this._children.splice(removeAt, 1); this.emit(NodeEventType.CHILD_REMOVED, child); }; nodeProto._onChildAdded = function (child) { + this._children.push(child); this.emit(NodeEventType.CHILD_ADDED, child); }; -nodeProto._onNodeDestroyed = function () { - this.emit(NodeEventType.NODE_DESTROYED, this); - // destroy children - const children = this._children; - for (let i = 0; i < children.length; ++i) { - // destroy immediate so its _onPreDestroy can be called - children[i]._destroyImmediate(); - } -}; - const oldPreDestroy = nodeProto._onPreDestroy; nodeProto._onPreDestroy = function _onPreDestroy () { const ret = oldPreDestroy.call(this); @@ -1304,6 +1287,20 @@ nodeProto._instantiate = function (cloned: Node, isSyncedNode: boolean) { return cloned; }; +nodeProto._onSiblingIndexChanged = function (index) { + const siblings = this._parent._children; + index = index !== -1 ? index : siblings.length - 1; + const oldIndex = siblings.indexOf(this); + if (index !== oldIndex) { + siblings.splice(oldIndex, 1); + if (index < siblings.length) { + siblings.splice(index, 0, this); + } else { + siblings.push(this); + } + } +} + // nodeProto._ctor = function (name?: string) { this.__nativeRefs = {}; @@ -1316,7 +1313,7 @@ nodeProto._ctor = function (name?: string) { this._eventProcessor = new legacyCC.NodeEventProcessor(this); this._uiProps = new NodeUIProperties(this); - const sharedArrayBuffer = this._getSharedArrayBufferObject(); + const sharedArrayBuffer = this._initAndReturnSharedBuffer(); // Uint32Array with 3 elements: eventMask, layer, dirtyFlags this._sharedUint32Arr = new Uint32Array(sharedArrayBuffer, 0, 3); // Int32Array with 1 element: siblingIndex @@ -1331,8 +1328,6 @@ nodeProto._ctor = function (name?: string) { // record scene's id when set this node as persist node this._originalSceneId = ''; - this._registerListeners(); - this._children = []; // this._isChildrenRedefined = false; @@ -1342,33 +1337,6 @@ nodeProto._ctor = function (name?: string) { this._euler = new Vec3(); this._registeredNodeEventTypeMask = 0; - - this.on(NodeEventType.CHILD_ADDED, (child) => { - this._children.push(child); - }); - - this.on(NodeEventType.CHILD_REMOVED, (child) => { - const removeAt = this._children.indexOf(child); - if (removeAt < 0) { - errorID(1633); - return; - } - this._children.splice(removeAt, 1); - }); - - this._onSiblingIndexChanged = function (index) { - const siblings = this._parent._children; - index = index !== -1 ? index : siblings.length - 1; - const oldIndex = siblings.indexOf(this); - if (index !== oldIndex) { - siblings.splice(oldIndex, 1); - if (index < siblings.length) { - siblings.splice(index, 0, this); - } else { - siblings.push(this); - } - } - } }; // handle meta data, it is generated automatically diff --git a/cocos/scene-graph/scene.jsb.ts b/cocos/scene-graph/scene.jsb.ts index e4a379132d..1c69e73eca 100644 --- a/cocos/scene-graph/scene.jsb.ts +++ b/cocos/scene-graph/scene.jsb.ts @@ -86,16 +86,17 @@ sceneProto._ctor = function () { }; sceneProto._onBatchCreated = function (dontSyncChildPrefab: boolean) { - // Don't invoke Node.prototype._onBatchCreated because we refactor Node&BaseNode, BaseNode is empty just for - // instanceof check in ts engine. After ts engine removes BaseNode, we could remove BaseNode.h/.cpp too. if (this._parent) { this._siblingIndex = this._parent.children.indexOf(this); } // - const len = this._children.length; + const children = this._children; + const len = children.length; + let child; for (let i = 0; i < len; ++i) { - this.children[i]._siblingIndex = i; - this._children[i]._onBatchCreated(dontSyncChildPrefab); + child = children[i]; + child._siblingIndex = i; + child._onBatchCreated(dontSyncChildPrefab); } }; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 719bbcd727..9b03cfa0b0 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -426,6 +426,7 @@ cocos_source_files( cocos/base/etc1.h cocos/base/etc2.cpp cocos/base/etc2.h + cocos/base/HasMemberFunction.h cocos/base/IndexHandle.h cocos/base/Locked.h cocos/base/Macros.h diff --git a/native/cocos/base/HasMemberFunction.h b/native/cocos/base/HasMemberFunction.h new file mode 100644 index 0000000000..3e0900a842 --- /dev/null +++ b/native/cocos/base/HasMemberFunction.h @@ -0,0 +1,97 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +/* This macro is used for checking whether a member function exists in a class in compiling time. +Usage: + If we have a class called `MyClass` as follows: + + ```c++ + class MyClass { + public: + int myMethod(bool a, float b) { return 100; } + }; +``` + +Test code: +```c++ + #include "base/HasMemberFunction.h" + + CC_DEFINE_HAS_MEMBER_FUNC(myMethod) + + template + void myTest(T* arg0) { + if constexpr (has_myMethod::value) { + // <1>: DO SOMETHING if T owns `myMethod` function. + // ... + } else { + // <2>: DO SOMETHING if T doesn't own `myMethod` function. + // ... + } + } + + static int myTestEntry() { + MyClass a; + myTest(&a); // --> Go to <1> + int b; + myTest(&b; // --> Go to <2> + } + +``` +*/ + +#define CC_DEFINE_HAS_MEMBER_FUNC(memFunc) \ + template \ + struct has_##memFunc { \ + static_assert( \ + std::integral_constant::value, \ + "Second template parameter needs to be of function type."); \ + }; \ + \ + template \ + struct has_##memFunc { \ + private: \ + template \ + static constexpr auto check(T*) \ + -> typename std::is_same< \ + decltype(std::declval().memFunc(std::declval()...)), \ + Ret>::type; \ + \ + template \ + static constexpr std::false_type check(...); \ + typedef decltype(check(0)) type; \ + \ + public: \ + static constexpr bool value = type::value; \ + }; + +namespace cc { + +CC_DEFINE_HAS_MEMBER_FUNC(setScriptObject) +CC_DEFINE_HAS_MEMBER_FUNC(getScriptObject) + +} // namespace cc diff --git a/native/cocos/base/std/variant.h b/native/cocos/base/std/variant.h index f457b25a1e..ef28fbf006 100644 --- a/native/cocos/base/std/variant.h +++ b/native/cocos/base/std/variant.h @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. - + http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -36,6 +36,10 @@ using std::holds_alternative; using std::in_place_index; using std::monostate; using std::variant; +using std::variant_alternative; +using std::variant_alternative_t; +using std::variant_size; +using std::variant_size_v; using std::visit; }; // namespace ccstd @@ -52,6 +56,10 @@ using boost::variant2::holds_alternative; using boost::variant2::in_place_index; using boost::variant2::monostate; using boost::variant2::variant; +using boost::variant2::variant_alternative; +using boost::variant2::variant_alternative_t; +using boost::variant2::variant_size; +using boost::variant2::variant_size_v; using boost::variant2::visit; }; // namespace ccstd diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index 3e9e29d6b9..6951c8b5ab 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -3579,31 +3579,6 @@ static bool js_cc_Node__setChildren(se::State& s) } SE_BIND_FUNC(js_cc_Node__setChildren) -static bool js_cc_Node__getSharedArrayBufferObject(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Node *arg1 = (cc::Node *) NULL ; - se::Object *result = 0 ; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = (se::Object *)((cc::Node const *)arg1)->_getSharedArrayBufferObject(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - - return true; -} -SE_BIND_FUNC(js_cc_Node__getSharedArrayBufferObject) - static bool js_cc_Node__onPreDestroy(se::State& s) { CC_UNUSED bool ok = true; @@ -3650,43 +3625,6 @@ static bool js_cc_Node__onPreDestroyBase(se::State& s) } SE_BIND_FUNC(js_cc_Node__onPreDestroyBase) -static bool js_cc_Node_onSiblingIndexChanged_set(se::State& s) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Node *arg1 = (cc::Node *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg1->onSiblingIndexChanged, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - - - return true; -} -SE_BIND_PROP_SET(js_cc_Node_onSiblingIndexChanged_set) - -static bool js_cc_Node_onSiblingIndexChanged_get(se::State& s) -{ - CC_UNUSED bool ok = true; - cc::Node *arg1 = (cc::Node *) NULL ; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->onSiblingIndexChanged, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(arg1->onSiblingIndexChanged, s.thisObject(), s.rval()); - - - - return true; -} -SE_BIND_PROP_GET(js_cc_Node_onSiblingIndexChanged_get) - static bool js_cc_Node__id_set(se::State& s) { CC_UNUSED bool ok = true; @@ -3995,7 +3933,6 @@ bool js_register_cc_Node(se::Object* obj) { auto* cls = se::Class::create("Node", obj, __jsb_cc_CCObject_proto, _SE(js_new_Node)); cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("onSiblingIndexChanged", _SE(js_cc_Node_onSiblingIndexChanged_get), _SE(js_cc_Node_onSiblingIndexChanged_set)); cls->defineProperty("_id", _SE(js_cc_Node__id_get), _SE(js_cc_Node__id_set)); cls->defineProperty("_parentInternal", _SE(js_cc_Node__parentInternal_get), _SE(js_cc_Node__parentInternal_set)); cls->defineProperty("_mobility", _SE(js_cc_Node__mobility_get), _SE(js_cc_Node__mobility_set)); @@ -4054,7 +3991,6 @@ bool js_register_cc_Node(se::Object* obj) { cls->defineFunction("setLayer", _SE(js_cc_Node_setLayer)); cls->defineFunction("getLayer", _SE(js_cc_Node_getLayer)); cls->defineFunction("_setChildren", _SE(js_cc_Node__setChildren)); - cls->defineFunction("_getSharedArrayBufferObject", _SE(js_cc_Node__getSharedArrayBufferObject)); cls->defineFunction("_onPreDestroy", _SE(js_cc_Node__onPreDestroy)); cls->defineFunction("_onPreDestroyBase", _SE(js_cc_Node__onPreDestroyBase)); diff --git a/native/cocos/bindings/jswrapper/PrivateObject.h b/native/cocos/bindings/jswrapper/PrivateObject.h index 27319d996d..0698a52898 100644 --- a/native/cocos/bindings/jswrapper/PrivateObject.h +++ b/native/cocos/bindings/jswrapper/PrivateObject.h @@ -196,7 +196,7 @@ inline void inHeap(void *ptr) { #endif template -inline PrivateObjectBase *make_shared_private_object(T *cobj) { // NOLINT +inline auto *make_shared_private_object(T *cobj) { // NOLINT static_assert(!std::is_same::value, "void * is not allowed"); // static_assert(!std::is_pointer_v && !std::is_null_pointer_v, "bad pointer"); #if CC_DEBUG @@ -209,19 +209,19 @@ inline PrivateObjectBase *make_shared_private_object(T *cobj) { // NOLINT } } template -inline PrivateObjectBase *shared_ptr_private_object(std::shared_ptr &&ptr) { // NOLINT +inline auto *shared_ptr_private_object(std::shared_ptr &&ptr) { // NOLINT static_assert(!std::is_base_of::value, "cc::RefCounted is not acceptable for shared_ptr"); return ccnew SharedPtrPrivateObject(std::forward>(ptr)); } template -inline PrivateObjectBase *shared_ptr_private_object(const std::shared_ptr &ptr) { // NOLINT +inline auto *shared_ptr_private_object(const std::shared_ptr &ptr) { // NOLINT static_assert(!std::is_base_of::value, "cc::RefCounted is not acceptable for shared_ptr"); return ccnew SharedPtrPrivateObject(ptr); } template -inline PrivateObjectBase *rawref_private_object(T *ptr) { // NOLINT +inline auto *rawref_private_object(T *ptr) { // NOLINT // static_assert(false, "always fail"); // static_assert(!std::is_base_of::value, "cc::RefCounted is not acceptable for shared_ptr"); #if CC_DEBUG @@ -231,12 +231,12 @@ inline PrivateObjectBase *rawref_private_object(T *ptr) { // NOLINT } template -inline PrivateObjectBase *ccintrusive_ptr_private_object(const cc::IntrusivePtr &ptr) { // NOLINT +inline auto *ccintrusive_ptr_private_object(const cc::IntrusivePtr &ptr) { // NOLINT static_assert(std::is_base_of::value, "cc::RefCounted expected!"); return ccnew CCIntrusivePtrPrivateObject(ptr); } template -inline PrivateObjectBase *ccintrusive_ptr_private_object(T *cobj) { // NOLINT +inline auto *ccintrusive_ptr_private_object(T *cobj) { // NOLINT static_assert(std::is_base_of::value, "cc::RefCounted expected!"); return ccnew CCIntrusivePtrPrivateObject(cc::IntrusivePtr(cobj)); } diff --git a/native/cocos/bindings/jswrapper/v8/Class.cpp b/native/cocos/bindings/jswrapper/v8/Class.cpp index ff2432e8d9..3eee7d0d09 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.cpp +++ b/native/cocos/bindings/jswrapper/v8/Class.cpp @@ -61,13 +61,7 @@ void invalidConstructor(const v8::FunctionCallbackInfo &args) { } // namespace -Class::Class() -: _parent(nullptr), - _parentProto(nullptr), - _proto(nullptr), - _ctor(nullptr), - _finalizeFunc(nullptr), - _createProto(true) { +Class::Class() { __allClasses.push_back(this); } @@ -107,27 +101,43 @@ bool Class::init(const ccstd::string &clsName, Object *parent, Object *parentPro _parentProto->incRef(); } - _ctor = ctor; + _constructor = ctor; - v8::FunctionCallback ctorToSet = _ctor != nullptr ? _ctor : invalidConstructor; + v8::FunctionCallback ctorToSet = _constructor != nullptr ? _constructor : invalidConstructor; - _ctorTemplate.Reset(__isolate, v8::FunctionTemplate::New(__isolate, ctorToSet, createExternal(__isolate, data))); + _constructorTemplate.Reset(__isolate, v8::FunctionTemplate::New(__isolate, ctorToSet, createExternal(__isolate, data))); v8::MaybeLocal jsNameVal = v8::String::NewFromUtf8(__isolate, _name.c_str(), v8::NewStringType::kNormal); if (jsNameVal.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->SetClassName(jsNameVal.ToLocalChecked()); - _ctorTemplate.Get(__isolate)->InstanceTemplate()->SetInternalFieldCount(1); + _constructorTemplate.Get(__isolate)->SetClassName(jsNameVal.ToLocalChecked()); + _constructorTemplate.Get(__isolate)->InstanceTemplate()->SetInternalFieldCount(1); return true; } +void Class::_setCtor(Object *obj) { + assert(!_ctor.has_value()); + _ctor = obj; + if (obj != nullptr) { + obj->root(); + obj->incRef(); + } +} + void Class::destroy() { SAFE_DEC_REF(_parent); SAFE_DEC_REF(_proto); SAFE_DEC_REF(_parentProto); - _ctorTemplate.Reset(); + if (_ctor.has_value()) { + if (_ctor.value() != nullptr) { + _ctor.value()->unroot(); + _ctor.value()->decRef(); + } + _ctor.reset(); + } + _constructorTemplate.Reset(); } void Class::cleanup() { @@ -153,11 +163,11 @@ bool Class::install() { // __clsMap.emplace(_name, this); if (_parentProto != nullptr) { - _ctorTemplate.Get(__isolate)->Inherit(_parentProto->_getClass()->_ctorTemplate.Get(__isolate)); + _constructorTemplate.Get(__isolate)->Inherit(_parentProto->_getClass()->_constructorTemplate.Get(__isolate)); } v8::Local context = __isolate->GetCurrentContext(); - v8::MaybeLocal ctor = _ctorTemplate.Get(__isolate)->GetFunction(context); + v8::MaybeLocal ctor = _constructorTemplate.Get(__isolate)->GetFunction(context); if (ctor.IsEmpty()) { return false; } @@ -196,7 +206,7 @@ bool Class::defineFunction(const char *name, v8::FunctionCallback func, void *da if (jsName.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->PrototypeTemplate()->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func, createExternal(__isolate, data))); + _constructorTemplate.Get(__isolate)->PrototypeTemplate()->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func, createExternal(__isolate, data))); return true; } @@ -206,7 +216,7 @@ bool Class::defineProperty(const char *name, v8::FunctionCallback getter, v8::Fu return false; } - auto prototypeTemplate = _ctorTemplate.Get(__isolate)->PrototypeTemplate(); + auto prototypeTemplate = _constructorTemplate.Get(__isolate)->PrototypeTemplate(); auto externalData = createExternal(__isolate, data); prototypeTemplate->SetAccessorProperty(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, getter, externalData), v8::FunctionTemplate::New(__isolate, setter, externalData)); return true; @@ -225,7 +235,7 @@ bool Class::defineStaticFunction(const char *name, v8::FunctionCallback func, vo if (jsName.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func, createExternal(__isolate, data))); + _constructorTemplate.Get(__isolate)->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func, createExternal(__isolate, data))); return true; } @@ -236,7 +246,7 @@ bool Class::defineStaticProperty(const char *name, v8::FunctionCallback getter, } auto externalData = createExternal(__isolate, data); - _ctorTemplate.Get(__isolate)->SetAccessorProperty(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, getter, externalData), v8::FunctionTemplate::New(__isolate, setter, externalData)); + _constructorTemplate.Get(__isolate)->SetAccessorProperty(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, getter, externalData), v8::FunctionTemplate::New(__isolate, setter, externalData)); return true; } @@ -248,7 +258,7 @@ bool Class::defineStaticProperty(const char *name, const Value &value, PropertyA v8::Local v8Val; internal::seToJsValue(__isolate, value, &v8Val); - _ctorTemplate.Get(__isolate)->Set(jsName.ToLocalChecked(), v8Val, static_cast(attribute)); + _constructorTemplate.Get(__isolate)->Set(jsName.ToLocalChecked(), v8Val, static_cast(attribute)); return true; } @@ -271,8 +281,8 @@ bool Class::defineFinalizeFunction(V8FinalizeFunc finalizeFunc) { // return _createJSObjectWithClass(iter->second); // } -v8::Local Class::_createJSObjectWithClass(Class *cls) { //NOLINT - v8::MaybeLocal ret = cls->_ctorTemplate.Get(__isolate)->InstanceTemplate()->NewInstance(__isolate->GetCurrentContext()); +v8::Local Class::_createJSObjectWithClass(Class *cls) { // NOLINT + v8::MaybeLocal ret = cls->_constructorTemplate.Get(__isolate)->InstanceTemplate()->NewInstance(__isolate->GetCurrentContext()); CC_ASSERT(!ret.IsEmpty()); return ret.ToLocalChecked(); } @@ -281,7 +291,7 @@ Object *Class::getProto() const { return _proto; } -V8FinalizeFunc Class::_getFinalizeFunction() const { //NOLINT +V8FinalizeFunc Class::_getFinalizeFunction() const { // NOLINT return _finalizeFunc; } diff --git a/native/cocos/bindings/jswrapper/v8/Class.h b/native/cocos/bindings/jswrapper/v8/Class.h index 988487c011..96e714ebcc 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.h +++ b/native/cocos/bindings/jswrapper/v8/Class.h @@ -32,68 +32,69 @@ #include "../Define.h" #include "../Value.h" #include "Base.h" + #include "base/std/optional.h" namespace se { class Object; /** - * se::Class represents a definition of how to create a native binding object. - */ + * se::Class represents a definition of how to create a native binding object. + */ class Class final { public: /** - * @brief Creates a class used for creating relevant native binding objects. - * @param[in] className A null-terminated UTF8 string containing the class's name. - * @param[in] obj The object that current class proto object attaches to. Should not be nullptr. - * @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent. - * @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor. - * @param[in] data A data pointer attach to the function callback. - * @return A class instance used for creating relevant native binding objects. - * @note Don't need to delete the pointer return by this method, it's managed internally. - */ + * @brief Creates a class used for creating relevant native binding objects. + * @param[in] className A null-terminated UTF8 string containing the class's name. + * @param[in] obj The object that current class proto object attaches to. Should not be nullptr. + * @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent. + * @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor. + * @param[in] data A data pointer attach to the function callback. + * @return A class instance used for creating relevant native binding objects. + * @note Don't need to delete the pointer return by this method, it's managed internally. + */ static Class *create(const ccstd::string &clsName, Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data = nullptr); static Class *create(const std::initializer_list &classPath, Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data = nullptr); /** - * @brief Defines a member function with a callback. Each objects created by class will have this function property. - * @param[in] name A null-terminated UTF8 string containing the function name. - * @param[in] func A callback to invoke when the property is called as a function. - * @param[in] data A data pointer attach to the function callback. - * @return true if succeed, otherwise false. - */ + * @brief Defines a member function with a callback. Each objects created by class will have this function property. + * @param[in] name A null-terminated UTF8 string containing the function name. + * @param[in] func A callback to invoke when the property is called as a function. + * @param[in] data A data pointer attach to the function callback. + * @return true if succeed, otherwise false. + */ bool defineFunction(const char *name, v8::FunctionCallback func, void *data = nullptr); /** - * @brief Defines a property with accessor callbacks. Each objects created by class will have this property. - * @param[in] name A null-terminated UTF8 string containing the property name. - * @param[in] getter A callback to invoke when the property is read. - * @param[in] setter A callback to invoke when the property is set. - * @param[in] data A data pointer attach to the property's callback - * @return true if succeed, otherwise false. - */ + * @brief Defines a property with accessor callbacks. Each objects created by class will have this property. + * @param[in] name A null-terminated UTF8 string containing the property name. + * @param[in] getter A callback to invoke when the property is read. + * @param[in] setter A callback to invoke when the property is set. + * @param[in] data A data pointer attach to the property's callback + * @return true if succeed, otherwise false. + */ bool defineProperty(const char *name, v8::FunctionCallback getter, v8::FunctionCallback setter, void *data = nullptr); bool defineProperty(const std::initializer_list &names, v8::FunctionCallback getter, v8::FunctionCallback setter, void *data = nullptr); /** - * @brief Defines a static function with a callback. Only JavaScript constructor object will have this function. - * @param[in] name A null-terminated UTF8 string containing the function name. - * @param[in] func A callback to invoke when the constructor's property is called as a function. - * @param[in] data A data pointer attach to static function callback - * @return true if succeed, otherwise false. - */ + * @brief Defines a static function with a callback. Only JavaScript constructor object will have this function. + * @param[in] name A null-terminated UTF8 string containing the function name. + * @param[in] func A callback to invoke when the constructor's property is called as a function. + * @param[in] data A data pointer attach to static function callback + * @return true if succeed, otherwise false. + */ bool defineStaticFunction(const char *name, v8::FunctionCallback func, void *data = nullptr); /** - * @brief Defines a static property with accessor callbacks. Only JavaScript constructor object will have this property. - * @param[in] name A null-terminated UTF8 string containing the property name. - * @param[in] getter A callback to invoke when the constructor's property is read. - * @param[in] setter A callback to invoke when the constructor's property is set. - * @param[in] data A data pointer attach to static property callback - * @return true if succeed, otherwise false. - */ + * @brief Defines a static property with accessor callbacks. Only JavaScript constructor object will have this property. + * @param[in] name A null-terminated UTF8 string containing the property name. + * @param[in] getter A callback to invoke when the constructor's property is read. + * @param[in] setter A callback to invoke when the constructor's property is set. + * @param[in] data A data pointer attach to static property callback + * @return true if succeed, otherwise false. + */ bool defineStaticProperty(const char *name, v8::FunctionCallback getter, v8::FunctionCallback setter, void *data = nullptr); /** @@ -106,34 +107,36 @@ public: bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE); /** - * @brief Defines the finalize function with a callback. - * @param[in] func The callback to invoke when a JavaScript object is garbage collected. - * @return true if succeed, otherwise false. - */ + * @brief Defines the finalize function with a callback. + * @param[in] func The callback to invoke when a JavaScript object is garbage collected. + * @return true if succeed, otherwise false. + */ bool defineFinalizeFunction(V8FinalizeFunc func); /** - * @brief Installs class to JavaScript VM. - * @return true if succeed, otherwise false. - * @note After this method, an object could be created by `var foo = new Foo();`. - */ + * @brief Installs class to JavaScript VM. + * @return true if succeed, otherwise false. + * @note After this method, an object could be created by `var foo = new Foo();`. + */ bool install(); /** - * @brief Gets the proto object of this class. - * @return The proto object of this class. - * @note Don't need to be released in user code. - */ + * @brief Gets the proto object of this class. + * @return The proto object of this class. + * @note Don't need to be released in user code. + */ Object *getProto() const; /** - * @brief Gets the class name. - * @return The class name. - */ + * @brief Gets the class name. + * @return The class name. + */ const char *getName() const { return _name.c_str(); } // Private API used in wrapper - V8FinalizeFunc _getFinalizeFunction() const; // NOLINT(readability-identifier-naming) + V8FinalizeFunc _getFinalizeFunction() const; // NOLINT(readability-identifier-naming) + void _setCtor(Object *obj); // NOLINT(readability-identifier-naming) + inline const ccstd::optional &_getCtor() const { return _ctor; } // NOLINT(readability-identifier-naming) private: Class(); @@ -150,14 +153,15 @@ private: static void setIsolate(v8::Isolate *isolate); ccstd::string _name; - Object *_parent; - Object *_parentProto; - Object *_proto; + Object *_parent{nullptr}; + Object *_parentProto{nullptr}; + Object *_proto{nullptr}; + ccstd::optional _ctor; - v8::FunctionCallback _ctor; - v8::UniquePersistent _ctorTemplate; - V8FinalizeFunc _finalizeFunc; - bool _createProto; + v8::FunctionCallback _constructor{nullptr}; + v8::UniquePersistent _constructorTemplate; + V8FinalizeFunc _finalizeFunc{nullptr}; + bool _createProto{true}; friend class ScriptEngine; friend class Object; diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp b/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp index 03e7abbeac..69287edf2a 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp @@ -25,6 +25,7 @@ #include "HelperMacros.h" #include "../State.h" #include "../ValueArrayPool.h" +#include "Class.h" #include "Object.h" #include "ScriptEngine.h" #include "Utils.h" @@ -128,7 +129,23 @@ SE_HOT void jsbConstructorWrapper(const v8::FunctionCallbackInfo &v8a SE_LOGE("[ERROR] Failed to invoke %s\n", funcName); } se::Value property; - if (thisObject->getProperty("_ctor", &property)) { + bool foundCtor = false; + if (!cls->_getCtor().has_value()) { + foundCtor = thisObject->getProperty("_ctor", &property, true); + if (foundCtor) { + cls->_setCtor(property.toObject()); + } else { + cls->_setCtor(nullptr); + } + } else { + auto *ctorObj = cls->_getCtor().value(); + if (ctorObj != nullptr) { + property.setObject(ctorObj); + foundCtor = true; + } + } + + if (foundCtor) { property.toObject()->call(args, thisObject); } } diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.h b/native/cocos/bindings/jswrapper/v8/HelperMacros.h index 213855e6d2..7491fee285 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.h @@ -37,7 +37,7 @@ #include "base/Macros.h" #include "base/std/container/string.h" -//#define RECORD_JSB_INVOKING +// #define RECORD_JSB_INVOKING #ifndef CC_DEBUG #undef RECORD_JSB_INVOKING @@ -141,6 +141,7 @@ void jsbSetterWrapper(const v8::FunctionCallbackInfo &, #define SE_BIND_FUNC_FAST(funcName) \ void funcName##Registry(const v8::FunctionCallbackInfo &_v8args) { \ + JsbInvokeScope(#funcName); \ auto *thisObject = static_cast(_v8args.This()->GetAlignedPointerFromInternalField(0)); \ auto *nativeObject = thisObject != nullptr ? thisObject->getPrivateData() : nullptr; \ funcName(nativeObject); \ @@ -188,7 +189,7 @@ void jsbSetterWrapper(const v8::FunctionCallbackInfo &, #define SE_QUOTEME(x) SE_QUOTEME_(x) // IDEA: implement this macro - //#define SE_REPORT_ERROR(fmt, ...) SE_LOGE(SE_STR_CONCAT3("[ERROR] ( %s, %d): ", fmt, "\n"), __FILE__, __LINE__, ##__VA_ARGS__) + // #define SE_REPORT_ERROR(fmt, ...) SE_LOGE(SE_STR_CONCAT3("[ERROR] ( %s, %d): ", fmt, "\n"), __FILE__, __LINE__, ##__VA_ARGS__) #define SE_REPORT_ERROR(fmt, ...) selogMessage(cc::LogLevel::ERR, "[SE_ERROR]", (" (%s, %d): " fmt), __FILE__, __LINE__, ##__VA_ARGS__) #if CC_DEBUG > 0 diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index 80a834f0f2..a35d70525b 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -34,6 +34,7 @@ #include "../Value.h" #include "Base.h" #include "ObjectWrap.h" + #include "base/HasMemberFunction.h" #include @@ -325,7 +326,7 @@ public: * @return true if object is a proxy object, otherwise false. */ bool isProxy() const; - + /** * @brief Gets the type of a typed array object. * @return The type of a typed array object. @@ -443,6 +444,15 @@ public: ValueArray getAllElementsInSet() const; void setPrivateObject(PrivateObjectBase *data); + + template + inline void setPrivateObject(TypedPrivateObject *data) { + setPrivateObject(static_cast(data)); + if constexpr (cc::has_setScriptObject::value) { + data->template get()->setScriptObject(this); + } + } + PrivateObjectBase *getPrivateObject() const; /* diff --git a/native/cocos/bindings/jswrapper/v8/Utils.cpp b/native/cocos/bindings/jswrapper/v8/Utils.cpp index 3bb6d09e94..6e5334253f 100644 --- a/native/cocos/bindings/jswrapper/v8/Utils.cpp +++ b/native/cocos/bindings/jswrapper/v8/Utils.cpp @@ -115,7 +115,8 @@ void jsToSeValue(v8::Isolate *isolate, v8::Local jsval, Value *v) { } } else if (jsval->IsString()) { v8::String::Utf8Value utf8(isolate, jsval); - v->setString(ccstd::string(*utf8)); + const char *utf8Str = *utf8; + v->setString(utf8Str); } else if (jsval->IsBoolean()) { v8::MaybeLocal jsBoolean = jsval->ToBoolean(isolate); if (!jsBoolean.IsEmpty()) { @@ -155,29 +156,44 @@ static void warnWithinTimesInReleaseMode(const char *msg) { template void setReturnValueTemplate(const Value &data, const T &argv) { - if (data.getType() == Value::Type::Undefined) { - argv.GetReturnValue().Set(v8::Undefined(argv.GetIsolate())); - } else if (data.getType() == Value::Type::Null) { - argv.GetReturnValue().Set(v8::Null(argv.GetIsolate())); - } else if (data.getType() == Value::Type::Number) { - argv.GetReturnValue().Set(v8::Number::New(argv.GetIsolate(), data.toDouble())); - } else if (data.getType() == Value::Type::BigInt) { - constexpr int64_t maxSafeInt = 9007199254740991LL; // value refer to JS Number.MAX_SAFE_INTEGER - constexpr int64_t minSafeInt = -9007199254740991LL; // value refer to JS Number.MIN_SAFE_INTEGER - if (data.toInt64() > maxSafeInt || data.toInt64() < minSafeInt) { - // NOTICE: Precision loss will happend here. - warnWithinTimesInReleaseMode<100>("int64 value is out of range for double"); - CC_ABORT(); // should be fixed in debug mode. + switch (data.getType()) { + case Value::Type::Undefined: { + argv.GetReturnValue().Set(v8::Undefined(argv.GetIsolate())); + break; + } + case Value::Type::Null: { + argv.GetReturnValue().Set(v8::Null(argv.GetIsolate())); + break; + } + case Value::Type::Number: { + argv.GetReturnValue().Set(v8::Number::New(argv.GetIsolate(), data.toDouble())); + break; + } + case Value::Type::BigInt: { + constexpr int64_t maxSafeInt = 9007199254740991LL; // value refer to JS Number.MAX_SAFE_INTEGER + constexpr int64_t minSafeInt = -9007199254740991LL; // value refer to JS Number.MIN_SAFE_INTEGER + if (data.toInt64() > maxSafeInt || data.toInt64() < minSafeInt) { + // NOTICE: Precision loss will happend here. + warnWithinTimesInReleaseMode<100>("int64 value is out of range for double"); + CC_ABORT(); // should be fixed in debug mode. + } + argv.GetReturnValue().Set(v8::Number::New(argv.GetIsolate(), static_cast(data.toInt64()))); + break; + } + case Value::Type::String: { + v8::MaybeLocal value = v8::String::NewFromUtf8(argv.GetIsolate(), data.toString().c_str(), v8::NewStringType::kNormal); + CC_ASSERT(!value.IsEmpty()); + argv.GetReturnValue().Set(value.ToLocalChecked()); + break; + } + case Value::Type::Boolean: { + argv.GetReturnValue().Set(v8::Boolean::New(argv.GetIsolate(), data.toBoolean())); + break; + } + case Value::Type::Object: { + argv.GetReturnValue().Set(data.toObject()->_getJSObject()); + break; } - argv.GetReturnValue().Set(v8::Number::New(argv.GetIsolate(), static_cast(data.toInt64()))); - } else if (data.getType() == Value::Type::String) { - v8::MaybeLocal value = v8::String::NewFromUtf8(argv.GetIsolate(), data.toString().c_str(), v8::NewStringType::kNormal); - CC_ASSERT(!value.IsEmpty()); - argv.GetReturnValue().Set(value.ToLocalChecked()); - } else if (data.getType() == Value::Type::Boolean) { - argv.GetReturnValue().Set(v8::Boolean::New(argv.GetIsolate(), data.toBoolean())); - } else if (data.getType() == Value::Type::Object) { - argv.GetReturnValue().Set(data.toObject()->_getJSObject()); } } diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 5a54fff33e..7faf48d499 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -51,6 +51,8 @@ #include "math/Math.h" #include "renderer/gfx-base/states/GFXSampler.h" +#include "base/HasMemberFunction.h" + #define SE_PRECONDITION2_VOID(condition, ...) \ do { \ if (!(condition)) { \ @@ -196,7 +198,7 @@ seval_to_type(const se::Value &v, bool &ok) { // NOLINT(readability-identifier-n } inline se::HandleObject unwrapProxyObject(se::Object *obj) { - if(obj->isProxy()) { + if (obj->isProxy()) { return se::HandleObject(se::Object::createProxyTarget(obj)); } obj->incRef(); @@ -344,7 +346,23 @@ native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullpt cc_tmp_set_private_data(obj, v); se::Value property; - if (obj->getProperty("_ctor", &property)) { + bool foundCtor = false; + if (!cls->_getCtor().has_value()) { + foundCtor = obj->getProperty("_ctor", &property, true); + if (foundCtor) { + cls->_setCtor(property.toObject()); + } else { + cls->_setCtor(nullptr); + } + } else { + auto *ctorObj = cls->_getCtor().value(); + if (ctorObj != nullptr) { + property.setObject(ctorObj); + foundCtor = true; + } + } + + if (foundCtor) { property.toObject()->call(se::EmptyValueArray, obj); } @@ -366,6 +384,16 @@ bool native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCa return true; } + if constexpr (cc::has_getScriptObject::value) { + if (v->getScriptObject() != nullptr) { + if (isReturnCachedValue != nullptr) { + *isReturnCachedValue = true; + } + ret->setObject(v->getScriptObject()); + return true; + } + } + se::NativePtrToObjectMap::filter(v, cls) .forEach( [&](se::Object *foundObj) { @@ -383,7 +411,23 @@ bool native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCa cc_tmp_set_private_data(obj, v); se::Value property; - if (obj->getProperty("_ctor", &property)) { + bool foundCtor = false; + if (!cls->_getCtor().has_value()) { + foundCtor = obj->getProperty("_ctor", &property, true); + if (foundCtor) { + cls->_setCtor(property.toObject()); + } else { + cls->_setCtor(nullptr); + } + } else { + auto *ctorObj = cls->_getCtor().value(); + if (ctorObj != nullptr) { + property.setObject(ctorObj); + foundCtor = true; + } + } + + if (foundCtor) { property.toObject()->call(se::EmptyValueArray, obj); } @@ -718,7 +762,7 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * CC_ASSERT(from.toObject()); se::HandleObject array(unwrapProxyObject(from.toObject())); - + if (array->isArray()) { uint32_t len = 0; array->getArrayLength(&len); @@ -1032,6 +1076,7 @@ bool sevalue_to_native(const se::Value &from, ccstd::optional *to, se::Object } return ret; } + ////////////////////// shoter form template inline bool sevalue_to_native(const se::Value &from, T &&to) { // NOLINT(readability-identifier-naming) @@ -1106,7 +1151,7 @@ nativevalue_to_se(const T &from, se::Value &to, se::Object * /*ctx*/) { // NOLIN return true; } -//#endif // HAS_CONSTEXPR +// #endif // HAS_CONSTEXPR //////////////////////////////// forward declaration: nativevalue_to_se //////////////////////////////// diff --git a/native/cocos/bindings/manual/jsb_global.h b/native/cocos/bindings/manual/jsb_global.h index 64248a0c73..ca16a2e7b0 100644 --- a/native/cocos/bindings/manual/jsb_global.h +++ b/native/cocos/bindings/manual/jsb_global.h @@ -49,14 +49,14 @@ se::PrivateObjectBase *jsb_make_private_object(ARGS &&...args) { // NOLINT(reada } template -typename std::enable_if::value, se::PrivateObjectBase *>::type -jsb_make_private_object_with_instance(T *instance) { //NOLINT(readability-identifier-naming) +typename std::enable_if::value, se::TypedPrivateObject *>::type +jsb_make_private_object_with_instance(T *instance) { // NOLINT(readability-identifier-naming) return se::ccintrusive_ptr_private_object(instance); } template -typename std::enable_if::value, se::PrivateObjectBase *>::type -jsb_make_private_object_with_instance(T *instance) { //NOLINT(readability-identifier-naming) +typename std::enable_if::value, se::TypedPrivateObject *>::type +jsb_make_private_object_with_instance(T *instance) { // NOLINT(readability-identifier-naming) return se::shared_ptr_private_object(std::shared_ptr(instance)); } diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index 8459ca9899..bd5370b0c1 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -37,6 +37,13 @@ #define JSB_FREE(ptr) delete ptr #endif +#define DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emmiter) \ + se::Object *jsObject = emitter->getScriptObject(); \ + if (jsObject == nullptr) { \ + jsObject = se::NativePtrToObjectMap::findFirst(emitter); \ + emmiter->setScriptObject(jsObject); \ + } + namespace { class TempFloatArray final { @@ -128,9 +135,11 @@ static bool js_root_registerListeners(se::State &s) // NOLINT(readability-identi } SE_BIND_FUNC(js_root_registerListeners) // NOLINT(readability-identifier-naming) -static void registerOnTransformChanged(cc::Node *node, se::Object *jsObject) { +static void registerOnTransformChanged(cc::Node *node) { node->on( - [jsObject](cc::Node * /* emitter*/, cc::TransformBit transformBit) { + +[](cc::Node *emitter, cc::TransformBit transformBit) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(transformBit, arg0); @@ -138,9 +147,11 @@ static void registerOnTransformChanged(cc::Node *node, se::Object *jsObject) { }); } -static void registerOnParentChanged(cc::Node *node, se::Object *jsObject) { +static void registerOnParentChanged(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/, cc::Node *oldParent) { + +[](cc::Node *emitter, cc::Node *oldParent) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(oldParent, arg0); @@ -148,17 +159,21 @@ static void registerOnParentChanged(cc::Node *node, se::Object *jsObject) { }); } -static void registerOnMobilityChanged(cc::Node *node, se::Object *jsObject) { +static void registerOnMobilityChanged(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/) { + +[](cc::Node *emitter) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::ScriptEngine::getInstance()->callFunction(jsObject, "_onMobilityChanged", 0, nullptr); }); } -static void registerOnLayerChanged(cc::Node *node, se::Object *jsObject) { +static void registerOnLayerChanged(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/, uint32_t layer) { + +[](cc::Node *emitter, uint32_t layer) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(layer, arg0); @@ -166,9 +181,11 @@ static void registerOnLayerChanged(cc::Node *node, se::Object *jsObject) { }); } -static void registerOnChildRemoved(cc::Node *node, se::Object *jsObject) { +static void registerOnChildRemoved(cc::Node *node) { node->on( - [jsObject](cc::Node * /* emitter*/, cc::Node *child) { + +[](cc::Node *emitter, cc::Node *child) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(child, arg0); @@ -176,9 +193,11 @@ static void registerOnChildRemoved(cc::Node *node, se::Object *jsObject) { }); } -static void registerOnChildAdded(cc::Node *node, se::Object *jsObject) { +static void registerOnChildAdded(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/, cc::Node *child) { + +[](cc::Node *emitter, cc::Node *child) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(child, arg0); @@ -186,17 +205,21 @@ static void registerOnChildAdded(cc::Node *node, se::Object *jsObject) { }); } -static void registerOnSiblingOrderChanged(cc::Node *node, se::Object *jsObject) { +static void registerOnSiblingOrderChanged(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/) { + +[](cc::Node *emitter) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope scope; se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSiblingOrderChanged", 0, nullptr); }); } -static void registerOnActiveNode(cc::Node *node, se::Object *jsObject) { +static void registerOnActiveNode(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/, bool shouldActiveNow) { + +[](cc::Node *emitter, bool shouldActiveNow) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(shouldActiveNow, arg0); @@ -204,9 +227,11 @@ static void registerOnActiveNode(cc::Node *node, se::Object *jsObject) { }); } -static void registerOnBatchCreated(cc::Node *node, se::Object *jsObject) { +static void registerOnBatchCreated(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/, bool dontChildPrefab) { + +[](cc::Node *emitter, bool dontChildPrefab) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(dontChildPrefab, arg0); @@ -214,9 +239,11 @@ static void registerOnBatchCreated(cc::Node *node, se::Object *jsObject) { }); } -static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object *jsObject) { +static void registerLocalPositionRotationScaleUpdated(cc::Node *node) { node->on( - [jsObject](cc::Node * /*emitter*/, float x, float y, float z) { + +[](cc::Node *emitter, float x, float y, float z) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(x, args[0]); @@ -225,27 +252,35 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalPositionUpdated", static_cast(args.size()), args.data()); }); - node->on([jsObject](cc::Node * /*emiiter*/, float x, float y, float z, float w) { - se::AutoHandleScope hs; - ccstd::array args; - nativevalue_to_se(x, args[0]); - nativevalue_to_se(y, args[1]); - nativevalue_to_se(z, args[2]); - nativevalue_to_se(w, args[3]); - se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalRotationUpdated", static_cast(args.size()), args.data()); - }); + node->on( + +[](cc::Node *emitter, float x, float y, float z, float w) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) - node->on([jsObject](cc::Node * /*emitter*/, float x, float y, float z) { - se::AutoHandleScope hs; - ccstd::array args; - nativevalue_to_se(x, args[0]); - nativevalue_to_se(y, args[1]); - nativevalue_to_se(z, args[2]); - se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalScaleUpdated", static_cast(args.size()), args.data()); - }); + se::AutoHandleScope hs; + ccstd::array args; + nativevalue_to_se(x, args[0]); + nativevalue_to_se(y, args[1]); + nativevalue_to_se(z, args[2]); + nativevalue_to_se(w, args[3]); + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalRotationUpdated", static_cast(args.size()), args.data()); + }); + + node->on( + +[](cc::Node *emitter, float x, float y, float z) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + + se::AutoHandleScope hs; + ccstd::array args; + nativevalue_to_se(x, args[0]); + nativevalue_to_se(y, args[1]); + nativevalue_to_se(z, args[2]); + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalScaleUpdated", static_cast(args.size()), args.data()); + }); node->on( - [jsObject](cc::Node * /*emitter*/, float px, float py, float pz, float rx, float ry, float rz, float rw, float sx, float sy, float sz) { + +[](cc::Node *emitter, float px, float py, float pz, float rx, float ry, float rz, float rw, float sx, float sy, float sz) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(px, args[0]); @@ -273,71 +308,79 @@ static void registerOnLightProbeBakingChanged(cc::Node *node, se::Object *jsObje }); } -static bool js_scene_Node_registerListeners(se::State &s) // NOLINT(readability-identifier-naming) +static bool js_scene_Node_registerListeners(cc::Node *cobj) // NOLINT(readability-identifier-naming) { - auto *cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - - auto *jsObject = s.thisObject(); #define NODE_DISPATCH_EVENT_TO_JS(eventType, jsFuncName) \ cobj->on( \ - [jsObject](cc::Node * /*emitter*/) { \ + +[](cc::Node *emitter) { \ + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) \ se::AutoHandleScope scope; \ se::ScriptEngine::getInstance()->callFunction(jsObject, #jsFuncName, 0, nullptr); \ }); - registerOnActiveNode(cobj, jsObject); - registerOnBatchCreated(cobj, jsObject); + registerOnActiveNode(cobj); + // NOTE: Node.prototype._onBatchCreated was implemented in TS and invoked in scene.jsb.ts (Scene.prototype._load), + // so don't need to register the listener here. + // registerOnBatchCreated(cobj); + registerOnChildAdded(cobj); + registerOnChildRemoved(cobj); NODE_DISPATCH_EVENT_TO_JS(cc::Node::Reattach, _onReAttach); NODE_DISPATCH_EVENT_TO_JS(cc::Node::RemovePersistRootNode, _onRemovePersistRootNode); - NODE_DISPATCH_EVENT_TO_JS(cc::Node::DestroyComponents, _onDestroyComponents); - cobj->on( - [](cc::Node *emitter) { - se::AutoHandleScope scope; - se::Value nodeVal; - nativevalue_to_se(emitter, nodeVal); - se::ScriptEngine::getInstance()->callFunction(nodeVal.toObject(), "_onNodeDestroyed", 1, &nodeVal); - }); + cobj->on(+[](cc::Node *emitter, index_t newIndex) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) - cobj->onSiblingIndexChanged = [jsObject](index_t newIndex) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(newIndex, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSiblingIndexChanged", 1, &arg0); - }; + }); cobj->on( - [jsObject](cc::Node * /*emitter*/, cc::Scene *scene) { + +[](cc::Node *emitter, cc::Scene *scene) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(scene, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSceneUpdated", 1, &arg0); }); +#if CC_EDITOR cobj->on( - [jsObject](cc::Node * /*emitter*/, bool attached) { + +[](cc::Node *emitter, bool attached) { + DEFINE_JS_OBJECT_IN_EVENT_CALLBACK(emitter) + se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(attached, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onEditorAttached", 1, &arg0); }); +#endif - registerLocalPositionRotationScaleUpdated(cobj, jsObject); + registerLocalPositionRotationScaleUpdated(cobj); return true; } -SE_BIND_FUNC(js_scene_Node_registerListeners) // NOLINT(readability-identifier-naming) + +static bool js_cc_Node_initAndReturnSharedBuffer(se::State &s) // NOLINT(readability-identifier-naming) +{ + auto *cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + + auto *result = cobj->_getSharedArrayBufferObject(); + js_scene_Node_registerListeners(cobj); + s.rval().setObject(result); + return true; +} +SE_BIND_FUNC(js_cc_Node_initAndReturnSharedBuffer) // NOLINT(readability-identifier-naming) static bool js_scene_Node_registerOnTransformChanged(se::State &s) // NOLINT(readability-identifier-naming) { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - - auto *jsObject = s.thisObject(); - - registerOnTransformChanged(cobj, jsObject); + registerOnTransformChanged(cobj); return true; } SE_BIND_FUNC(js_scene_Node_registerOnTransformChanged) // NOLINT(readability-identifier-naming) @@ -347,9 +390,7 @@ static bool js_scene_Node_registerOnParentChanged(se::State &s) // NOLINT(readab auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - auto *jsObject = s.thisObject(); - - registerOnParentChanged(cobj, jsObject); + registerOnParentChanged(cobj); return true; } SE_BIND_FUNC(js_scene_Node_registerOnParentChanged) // NOLINT(readability-identifier-naming) @@ -359,9 +400,7 @@ static bool js_scene_Node_registerOnMobilityChanged(se::State &s) // NOLINT(read auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - auto *jsObject = s.thisObject(); - - registerOnMobilityChanged(cobj, jsObject); + registerOnMobilityChanged(cobj); return true; } SE_BIND_FUNC(js_scene_Node_registerOnMobilityChanged) // NOLINT(readability-identifier-naming) @@ -371,44 +410,17 @@ static bool js_scene_Node_registerOnLayerChanged(se::State &s) // NOLINT(readabi auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - auto *jsObject = s.thisObject(); - - registerOnLayerChanged(cobj, jsObject); + registerOnLayerChanged(cobj); return true; } SE_BIND_FUNC(js_scene_Node_registerOnLayerChanged) // NOLINT(readability-identifier-naming) -static bool js_scene_Node_registerOnChildRemoved(se::State &s) // NOLINT(readability-identifier-naming) -{ - auto *cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - - auto *jsObject = s.thisObject(); - - registerOnChildRemoved(cobj, jsObject); - return true; -} -SE_BIND_FUNC(js_scene_Node_registerOnChildRemoved) // NOLINT(readability-identifier-naming) - -static bool js_scene_Node_registerOnChildAdded(se::State &s) // NOLINT(readability-identifier-naming) -{ - auto *cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - - auto *jsObject = s.thisObject(); - - registerOnChildAdded(cobj, jsObject); - return true; -} -SE_BIND_FUNC(js_scene_Node_registerOnChildAdded) // NOLINT(readability-identifier-naming) - static bool js_scene_Node_registerOnSiblingOrderChanged(se::State &s) // NOLINT(readability-identifier-naming) { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - auto *jsObject = s.thisObject(); - registerOnSiblingOrderChanged(cobj, jsObject); + registerOnSiblingOrderChanged(cobj); return true; } SE_BIND_FUNC(js_scene_Node_registerOnSiblingOrderChanged) // NOLINT(readability-identifier-naming) @@ -839,14 +851,12 @@ bool register_all_scene_manual(se::Object *obj) // NOLINT(readability-identifier __jsb_cc_scene_Camera_proto->defineFunction("getMatViewProjInv", _SE(js_scene_Camera_getMatViewProjInv)); // Node TS wrapper will invoke this function to let native object listen some events. - __jsb_cc_Node_proto->defineFunction("_registerListeners", _SE(js_scene_Node_registerListeners)); + __jsb_cc_Node_proto->defineFunction("_initAndReturnSharedBuffer", _SE(js_cc_Node_initAndReturnSharedBuffer)); __jsb_cc_Node_proto->defineFunction("_registerOnTransformChanged", _SE(js_scene_Node_registerOnTransformChanged)); __jsb_cc_Node_proto->defineFunction("_registerOnParentChanged", _SE(js_scene_Node_registerOnParentChanged)); __jsb_cc_Node_proto->defineFunction("_registerOnMobilityChanged", _SE(js_scene_Node_registerOnMobilityChanged)); __jsb_cc_Node_proto->defineFunction("_registerOnLayerChanged", _SE(js_scene_Node_registerOnLayerChanged)); - __jsb_cc_Node_proto->defineFunction("_registerOnChildRemoved", _SE(js_scene_Node_registerOnChildRemoved)); - __jsb_cc_Node_proto->defineFunction("_registerOnChildAdded", _SE(js_scene_Node_registerOnChildAdded)); __jsb_cc_Node_proto->defineFunction("_registerOnSiblingOrderChanged", _SE(js_scene_Node_registerOnSiblingOrderChanged)); __jsb_cc_Node_proto->defineFunction("_registerOnLightProbeBakingChanged", _SE(js_scene_Node_registerOnLightProbeBakingChanged)); diff --git a/native/cocos/bindings/sebind/class_v8.h b/native/cocos/bindings/sebind/class_v8.h index b759dfec2a..50ade1ba93 100644 --- a/native/cocos/bindings/sebind/class_v8.h +++ b/native/cocos/bindings/sebind/class_v8.h @@ -90,7 +90,7 @@ void genericConstructor(const v8::FunctionCallbackInfo &v8args) { } se::Value propertyVal; - if (thisObject->getProperty("_ctor", &propertyVal)) { + if (thisObject->getProperty("_ctor", &propertyVal, true)) { propertyVal.toObject()->call(args, thisObject); } } diff --git a/native/cocos/core/TypedArray.h b/native/cocos/core/TypedArray.h index 77be0e7e37..64b5302630 100644 --- a/native/cocos/core/TypedArray.h +++ b/native/cocos/core/TypedArray.h @@ -255,18 +255,18 @@ public: _jsTypedArray->incRef(); se::Value tmpVal; - _jsTypedArray->getProperty("buffer", &tmpVal); + _jsTypedArray->getProperty("buffer", &tmpVal, true); CC_ASSERT(tmpVal.isObject()); CC_ASSERT(tmpVal.toObject()->isArrayBuffer()); _buffer = ccnew ArrayBuffer(); _buffer->setJSArrayBuffer(tmpVal.toObject()); - _jsTypedArray->getProperty("byteOffset", &tmpVal); + _jsTypedArray->getProperty("byteOffset", &tmpVal, true); CC_ASSERT(tmpVal.isNumber()); _byteOffset = tmpVal.toUint32(); - _jsTypedArray->getProperty("byteLength", &tmpVal); + _jsTypedArray->getProperty("byteLength", &tmpVal, true); CC_ASSERT(tmpVal.isNumber()); _byteLength = tmpVal.toUint32(); diff --git a/native/cocos/core/data/Object.h b/native/cocos/core/data/Object.h index 9f2e1f3bf5..32e15358bb 100644 --- a/native/cocos/core/data/Object.h +++ b/native/cocos/core/data/Object.h @@ -30,6 +30,10 @@ #include "base/RefCounted.h" #include "base/TypeDef.h" +namespace se { +class Object; +} + namespace cc { /** @@ -78,9 +82,9 @@ public: */ LOCKED_IN_EDITOR = 1 << 9, /** - * @en Hide the object in editor. - * @zh 在编辑器中隐藏该对象。 - */ + * @en Hide the object in editor. + * @zh 在编辑器中隐藏该对象。 + */ HIDE_IN_HIERARCHY = 1 << 10, IS_ON_ENABLE_CALLED = 1 << 11, @@ -107,16 +111,16 @@ public: // all the hideFlags /** - * @en The object will not be saved and hide the object in editor,and lock node, when the node is locked, - * cannot be clicked in the scene,and The object will not be saved when building a player. - * @zh 该对象将不会被保存,构建项目时,该对象将不会被保存, 锁定节点,锁定后场景内不能点击, 在编辑器中隐藏该对象。 - */ + * @en The object will not be saved and hide the object in editor,and lock node, when the node is locked, + * cannot be clicked in the scene,and The object will not be saved when building a player. + * @zh 该对象将不会被保存,构建项目时,该对象将不会被保存, 锁定节点,锁定后场景内不能点击, 在编辑器中隐藏该对象。 + */ ALL_HIDE_MASKS = DONT_SAVE | EDITOR_ONLY | LOCKED_IN_EDITOR | HIDE_IN_HIERARCHY, }; static void deferredDestroy(); - //cjh public declare [editorExtrasTag]: unknown; + // cjh public declare [editorExtrasTag]: unknown; Flags _objFlags{Flags::ZERO}; ccstd::string _name; @@ -135,8 +139,8 @@ public: * obj.name = "New Obj"; * ``` */ - inline const ccstd::string &getName() const { return _name; } - inline void setName(const ccstd::string &value) { _name = value; } + inline const ccstd::string& getName() const { return _name; } + inline void setName(const ccstd::string& value) { _name = value; } /** * @en After inheriting CCObject objects, control whether you need to hide, lock, serialize, and other functions. @@ -222,11 +226,16 @@ public: virtual ccstd::string toString() const { return ""; }; + inline void setScriptObject(se::Object* seObj) { _scriptObject = seObj; } + inline se::Object* getScriptObject() const { return _scriptObject; } + protected: virtual bool onPreDestroy() { // FIXME: need reture value return true; } + + se::Object* _scriptObject{nullptr}; // weak reference }; CC_ENUM_BITWISE_OPERATORS(CCObject::Flags); @@ -285,6 +294,6 @@ inline bool CCObject::isReplicated() const { * log(isValid(node)); // false, destroyed in the end of last frame * ``` */ -bool isObjectValid(CCObject *value, bool strictMode = false); +bool isObjectValid(CCObject* value, bool strictMode = false); } // namespace cc diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index 3ad11361c3..0baae2a95d 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -365,9 +365,7 @@ void Node::setSiblingIndex(index_t index) { siblings.emplace_back(this); } _parent->updateSiblingIndex(); - if (onSiblingIndexChanged != nullptr) { - onSiblingIndexChanged(index); - } + emit(index); } } diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index 32aa151901..b69b0f0ef7 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -27,8 +27,8 @@ #include "base/Ptr.h" #include "base/std/any.h" #include "bindings/utils/BindingUtils.h" -//#include "core/components/Component.h" -//#include "core/event/Event.h" +// #include "core/components/Component.h" +// #include "core/event/Event.h" #include "core/data/Object.h" #include "core/event/EventTarget.h" #include "core/scene-graph/Layers.h" @@ -74,14 +74,13 @@ class Node : public CCObject { TARGET_EVENT_ARG1(ChildAdded, Node *) TARGET_EVENT_ARG1(ChildRemoved, Node *) TARGET_EVENT_ARG1(ParentChanged, Node *) - TARGET_EVENT_ARG0(NodeDestroyed) TARGET_EVENT_ARG0(MobilityChanged) TARGET_EVENT_ARG1(LayerChanged, uint32_t) TARGET_EVENT_ARG0(SiblingOrderChanged) + TARGET_EVENT_ARG1(SiblingIndexChanged, index_t) TARGET_EVENT_ARG0(ActiveInHierarchyChanged) TARGET_EVENT_ARG0(Reattach) TARGET_EVENT_ARG0(RemovePersistRootNode) - TARGET_EVENT_ARG0(DestroyComponents) TARGET_EVENT_ARG0(UITransformDirty) TARGET_EVENT_ARG1(ActiveNode, bool) TARGET_EVENT_ARG1(BatchCreated, bool) @@ -581,7 +580,6 @@ public: bool onPreDestroy() override; bool onPreDestroyBase(); - std::function onSiblingIndexChanged{nullptr}; // For deserialization ccstd::string _id; Node *_parent{nullptr}; @@ -640,10 +638,11 @@ private: Vec3 _localPosition{Vec3::ZERO}; Vec3 _localScale{Vec3::ONE}; Quaternion _localRotation{Quaternion::identity()}; + Vec3 _euler{0, 0, 0}; + // world transform Vec3 _worldPosition{Vec3::ZERO}; Vec3 _worldScale{Vec3::ONE}; - Vec3 _euler{0, 0, 0}; Quaternion _worldRotation{Quaternion::identity()}; Mat4 _worldMatrix{Mat4::IDENTITY}; diff --git a/native/tests/unit-test/src/base_has_member_function_test.cpp b/native/tests/unit-test/src/base_has_member_function_test.cpp new file mode 100644 index 0000000000..16c4acaf2d --- /dev/null +++ b/native/tests/unit-test/src/base_has_member_function_test.cpp @@ -0,0 +1,159 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "base/HasMemberFunction.h" +#include "core/scene-graph/Node.h" +#include "gtest/gtest.h" + +using namespace cc; + +namespace { + +class BaseWithoutGetScriptObject {}; + +class BaseWithGetScriptObjectButDifferentSignature { +public: + int getScriptObject(bool) const { return false; } + float getScriptObject(int) const { return 1.F; } + inline Node* getScriptObject() { return _node; } + inline const Node* getScriptObject() const { return _node; } + +private: + Node* _node{nullptr}; +}; + +class BaseWithCorrectGetScriptObjectSignature { +public: + se::Object* getScriptObject() const { return nullptr; } + se::Object* getScriptObject() { return nullptr; } +}; + +static const unsigned long fakeAddr = 100; + +class Base0 { +public: + Base0() { + _seObj = reinterpret_cast(reinterpret_cast(&fakeAddr)); + } + + se::Object* getScriptObject() const { return _seObj; } + se::Object* getScriptObject() { return _seObj; } + +private: + se::Object* _seObj{nullptr}; +}; + +class Base1 { +public: +}; + +class Sub0 : public Base0 { +}; + +class Sub1 : public Base0, public Base1 { +}; + +class Sub2 : public Base1, public Base0 { +}; + +class BaseVirtual { +public: + virtual ~BaseVirtual() = default; + virtual se::Object* getScriptObject() const = 0; + virtual se::Object* getScriptObject() = 0; +}; + +class BaseVirtualOverride : public BaseVirtual { +public: + se::Object* getScriptObject() const override { return nullptr; } + se::Object* getScriptObject() override { return nullptr; } +}; + +class SubVirtualOverride : public BaseVirtualOverride { +public: + SubVirtualOverride() { + _seObj = reinterpret_cast(reinterpret_cast(&fakeAddr)); + } + se::Object* getScriptObject() const override { return _seObj; } + se::Object* getScriptObject() override { return _seObj; } + int getScriptObject(int) { return 100; } + float getScriptObject(float) { return 200.F; } + +private: + se::Object* _seObj{nullptr}; +}; + +} // namespace + +TEST(HasMemberFunction, test01) { + static_assert(!cc::has_getScriptObject::value); + static_assert(!cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); + static_assert(cc::has_getScriptObject::value); +} + +TEST(HasMemberFunction, test02) { + if constexpr (cc::has_getScriptObject::value) { + Sub0 a; + Base0* b = &a; + EXPECT_EQ(b->getScriptObject(), reinterpret_cast(reinterpret_cast(&fakeAddr))); + } +} + +TEST(HasMemberFunction, test03) { + if constexpr (cc::has_getScriptObject::value) { + Sub1 a; + Base0* b = &a; + EXPECT_EQ(b->getScriptObject(), reinterpret_cast(reinterpret_cast(&fakeAddr))); + } +} + +TEST(HasMemberFunction, test04) { + if constexpr (cc::has_getScriptObject::value) { + Sub2 a; + Base0* b = &a; + EXPECT_EQ(b->getScriptObject(), reinterpret_cast(reinterpret_cast(&fakeAddr))); + } +} + +TEST(HasMemberFunction, test05) { + if constexpr (cc::has_getScriptObject::value) { + BaseVirtualOverride a; + BaseVirtual* b = &a; + EXPECT_EQ(b->getScriptObject(), nullptr); + } +} + +TEST(HasMemberFunction, test06) { + if constexpr (cc::has_getScriptObject::value) { + SubVirtualOverride a; + BaseVirtual* b = &a; + EXPECT_EQ(b->getScriptObject(), reinterpret_cast(reinterpret_cast(&fakeAddr))); + } +} diff --git a/native/tools/swig-config/cocos.i b/native/tools/swig-config/cocos.i index 63ed4c9504..4f55955031 100644 --- a/native/tools/swig-config/cocos.i +++ b/native/tools/swig-config/cocos.i @@ -100,6 +100,9 @@ namespace cc { %ignore JSBNativeDataHolder::getData; %ignore JSBNativeDataHolder::setData; +%ignore CCObject::setScriptObject; +%ignore CCObject::getScriptObject; + } diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 3e3fd93d21..a86fc8960d 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -138,6 +138,7 @@ using namespace cc; %ignore cc::Node::getWorldMatrix; %ignore cc::Node::getWorldRS; %ignore cc::Node::getWorldRT; +%ignore cc::Node::_getSharedArrayBufferObject; %ignore cc::scene::Camera::screenPointToRay; %ignore cc::scene::Camera::screenToWorld;