From 952bf07ff516c8053f122803a0807fd0be635333 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 25 May 2022 11:17:36 +0800 Subject: [PATCH] 3.6 sebind impl (#11125) --- .github/workflows/native-unit-test.yml | 86 +- native/CMakeLists.txt | 19 + native/cmake/predefine.cmake | 1 + .../cocos/bindings/jswrapper/PrivateObject.h | 2 + native/cocos/bindings/jswrapper/v8/Class.cpp | 42 +- native/cocos/bindings/jswrapper/v8/Class.h | 21 +- .../cocos/bindings/manual/jsb_conversions.h | 10 +- native/cocos/bindings/sebind/class.inl | 414 +++++++ native/cocos/bindings/sebind/class_v8.cpp | 48 + native/cocos/bindings/sebind/class_v8.h | 194 ++++ native/cocos/bindings/sebind/intl/common.cpp | 50 + native/cocos/bindings/sebind/intl/common.h | 1005 +++++++++++++++++ native/cocos/bindings/sebind/sebind.h | 28 + .../cocos/renderer/gfx-base/GFXDef-common.h | 6 + .../renderer/gfx-gles2/GLES2GPUObjects.h | 3 +- native/tests/sebind-tests/.gitignore | 5 + native/tests/sebind-tests/cfg.cmake | 18 + .../tests/sebind-tests/common/CMakeLists.txt | 51 + .../sebind-tests/common/Classes/Game.cpp | 77 ++ .../tests/sebind-tests/common/Classes/Game.h | 42 + .../common/Classes/demo/Coconut.cpp | 19 + .../common/Classes/demo/Coconut.h | 39 + .../common/Classes/demo/Fruit.cpp | 18 + .../sebind-tests/common/Classes/demo/Fruit.h | 29 + .../common/Classes/demo/sebind_fruits.cpp | 120 ++ .../common/Classes/demo/sebind_fruits.h | 12 + .../data/jsb-adapter/jsb-builtin.js | 2 + native/tests/sebind-tests/data/main.js | 119 ++ native/tests/sebind-tests/run-windows.sh | 21 + 29 files changed, 2469 insertions(+), 32 deletions(-) create mode 100644 native/cocos/bindings/sebind/class.inl create mode 100644 native/cocos/bindings/sebind/class_v8.cpp create mode 100644 native/cocos/bindings/sebind/class_v8.h create mode 100644 native/cocos/bindings/sebind/intl/common.cpp create mode 100644 native/cocos/bindings/sebind/intl/common.h create mode 100644 native/cocos/bindings/sebind/sebind.h create mode 100644 native/tests/sebind-tests/.gitignore create mode 100644 native/tests/sebind-tests/cfg.cmake create mode 100644 native/tests/sebind-tests/common/CMakeLists.txt create mode 100644 native/tests/sebind-tests/common/Classes/Game.cpp create mode 100644 native/tests/sebind-tests/common/Classes/Game.h create mode 100644 native/tests/sebind-tests/common/Classes/demo/Coconut.cpp create mode 100644 native/tests/sebind-tests/common/Classes/demo/Coconut.h create mode 100644 native/tests/sebind-tests/common/Classes/demo/Fruit.cpp create mode 100644 native/tests/sebind-tests/common/Classes/demo/Fruit.h create mode 100644 native/tests/sebind-tests/common/Classes/demo/sebind_fruits.cpp create mode 100644 native/tests/sebind-tests/common/Classes/demo/sebind_fruits.h create mode 100644 native/tests/sebind-tests/data/jsb-adapter/jsb-builtin.js create mode 100644 native/tests/sebind-tests/data/main.js create mode 100644 native/tests/sebind-tests/run-windows.sh diff --git a/.github/workflows/native-unit-test.yml b/.github/workflows/native-unit-test.yml index c10b87c359..79da371a0a 100644 --- a/.github/workflows/native-unit-test.yml +++ b/.github/workflows/native-unit-test.yml @@ -33,10 +33,94 @@ jobs: cmake -B tests/unit-test/build -S tests/unit-test cmake --build tests/unit-test/build --config Release ./tests/unit-test/build/src/Release/CocosTest.exe - + #### TODO(PatriceJiang): model split # - name: Run Module Tests # shell: bash # run: | # cd tests/module-tests # bash run-test-windows.sh + sebind-with-windows: + name: "sebind tests" + runs-on: windows-latest + defaults: + run: + working-directory: ${{github.workspace}}/native + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: "3.x" + + - name: Downlad external libraties + run: | + npm install + npm install gulp -g + node ./utils/download-deps.js + + - name: Generate bindings + shell: bash + run: | + python -m pip install PyYAML==5.4.1 Cheetah3 + python ./tools/tojs/genbindings.py + + - name: Run Sebind Tests + shell: bash + run: | + cd ${GITHUB_WORKSPACE}/native + cp -r ../templates/windows tests/sebind-tests/win64 + cd tests/sebind-tests + mkdir -p proj + cp cfg.cmake proj/ + GW="${GITHUB_WORKSPACE//\\/\/}" + cmake -B proj -S win64 -DRES_DIR="${GW}/native/tests/sebind-tests" -DCOCOS_X_PATH="${GW}/native" -DAPP_NAME=sebind + cmake --build proj + # cd proj/Debug + ## can not boot on this machine + # ./sebind.exe || true + # if [[ -f "result.txt" ]]; + # then + # echo "success!" + # else + # echo "Run sebind-tests fail!" + # exit 1 + # fi + + # sebind-run-on-linux: + # name: "Test sebind on Ubuntu" + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@v2 + # - name: Download external libraries + # shell: bash + # run: | + # EXT_VERSION=`node ./.github/workflows/get-native-external-version.js` + # git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos-creator/engine-native-external native/external + # - name: Generate bindings + # run: | + # python3 -m pip install PyYAML==5.4.1 Cheetah3 + # python3 ./native/tools/tojs/genbindings.py + # rm ./native/tools/tojs/userconf.ini + # - name: Install dependencies + # run: | + # sudo apt install libx11-dev -y + # sudo apt install libsndio-dev -y + # sudo apt install ninja-build -y + # - name: Run Sebind Tests + # shell: bash + # run: | + # cd ${GITHUB_WORKSPACE}/native + # cp -r ../templates/linux tests/sebind-tests/linux + # cd tests/sebind-tests + # mkdir -p proj + # cp cfg.cmake proj + # cmake -G Ninja -B proj -S linux -DRES_DIR=${GITHUB_WORKSPACE}/native/tests/sebind-tests/ -DCOCOS_X_PATH=${GITHUB_WORKSPACE}/native -DAPP_NAME=sebind + # cmake --build proj + # cd proj + # ./sebind || true + # if [[ -f "result.txt" ]]; + # then + # echo "success!" + # else + # echo "Run sebind-tests fail!" > /dev/stderr + # fi diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 28bccb19d6..5de6460ecc 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -27,6 +27,7 @@ cc_set_if_undefined(USE_JOB_SYSTEM_TBB OFF) cc_set_if_undefined(USE_PHYSICS_PHYSX OFF) cc_set_if_undefined(USE_MODULES OFF) cc_set_if_undefined(USE_SERVER_MODE OFF) +cc_set_if_undefined(USE_CCACHE OFF) add_definitions() @@ -99,6 +100,13 @@ if(USE_JOB_SYSTEM_TASKFLOW) endif() endif() +if(ANDROID) + if(CCACHE_EXECUTABLE AND USE_CCACHE) + set(CMAKE_C_COMPILER_LAUNCHER "${CCACHE_EXECUTABLE}") + set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_EXECUTABLE}") + endif() +endif() + ################################# list all option values ############################## cc_inspect_values( @@ -123,6 +131,8 @@ cc_inspect_values( USE_JOB_SYSTEM_TBB USE_JOB_SYSTEM_TASKFLOW USE_SERVER_MODE + USE_CCACHE + CCACHE_EXECUTABLE ) ################################# external source code ################################ @@ -2347,8 +2357,17 @@ elseif(LINUX) endif() ############# module bindings +cocos_source_files(MODULE ccbindings + cocos/bindings/sebind/intl/common.h + cocos/bindings/sebind/intl/common.cpp + cocos/bindings/sebind/class.inl + cocos/bindings/sebind/sebind.h +) + if(USE_SE_V8) cocos_source_files(MODULE ccbindings + cocos/bindings/sebind/class_v8.h + cocos/bindings/sebind/class_v8.cpp cocos/bindings/jswrapper/v8/Base.h cocos/bindings/jswrapper/v8/Class.cpp cocos/bindings/jswrapper/v8/Class.h diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index d0d5c42d7f..89d458e488 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -216,6 +216,7 @@ endfunction() find_program(NODE_EXECUTABLE NAMES node) find_program(TSC_EXECUTABLE NAMES tsc) +find_program(CCACHE_EXECUTABLE NAMES ccache) ## predefined configurations for game applications include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/common.cmake) diff --git a/native/cocos/bindings/jswrapper/PrivateObject.h b/native/cocos/bindings/jswrapper/PrivateObject.h index 45a11ca3a4..79311e9a7c 100644 --- a/native/cocos/bindings/jswrapper/PrivateObject.h +++ b/native/cocos/bindings/jswrapper/PrivateObject.h @@ -67,6 +67,8 @@ public: friend se::Object; friend se::State; friend se::ScriptEngine; + + void *finalizerData{nullptr}; }; template diff --git a/native/cocos/bindings/jswrapper/v8/Class.cpp b/native/cocos/bindings/jswrapper/v8/Class.cpp index 8436d8ea46..2bb2a7867d 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.cpp +++ b/native/cocos/bindings/jswrapper/v8/Class.cpp @@ -36,6 +36,15 @@ #include "ScriptEngine.h" #include "Utils.h" +namespace { +inline v8::Local createExternal(v8::Isolate *isolate, void *data) { + if (data) { + return v8::External::New(isolate, data); + } + return {}; +} +} // namespace + namespace se { // ------------------------------------------------------- Object @@ -66,16 +75,16 @@ Class::Class() Class::~Class() = default; /* static */ -Class *Class::create(const ccstd::string &clsName, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor) { +Class *Class::create(const ccstd::string &clsName, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data) { auto *cls = ccnew Class(); - if (cls != nullptr && !cls->init(clsName, parent, parentProto, ctor)) { + if (cls != nullptr && !cls->init(clsName, parent, parentProto, ctor, data)) { delete cls; cls = nullptr; } return cls; } -Class *Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor) { +Class *Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data) { se::AutoHandleScope scope; se::Object *currentParent = parent; se::Value tmp; @@ -84,12 +93,11 @@ Class *Class::create(const std::initializer_list &classPath, se::O CC_ASSERT(ok); // class or namespace in path is not defined currentParent = tmp.toObject(); } - return create(*(classPath.end() - 1), currentParent, parentProto, ctor); + return create(*(classPath.end() - 1), currentParent, parentProto, ctor, data); } -bool Class::init(const ccstd::string &clsName, Object *parent, Object *parentProto, v8::FunctionCallback ctor) { +bool Class::init(const ccstd::string &clsName, Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data) { _name = clsName; - _parent = parent; if (_parent != nullptr) { _parent->incRef(); @@ -104,7 +112,7 @@ bool Class::init(const ccstd::string &clsName, Object *parent, Object *parentPro v8::FunctionCallback ctorToSet = _ctor != nullptr ? _ctor : invalidConstructor; - _ctorTemplate.Reset(__isolate, v8::FunctionTemplate::New(__isolate, ctorToSet)); + _ctorTemplate.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; @@ -184,47 +192,47 @@ bool Class::install() { return true; } -bool Class::defineFunction(const char *name, v8::FunctionCallback func) { +bool Class::defineFunction(const char *name, v8::FunctionCallback func, void *data) { v8::MaybeLocal jsName = v8::String::NewFromUtf8(__isolate, name, v8::NewStringType::kNormal); if (jsName.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->PrototypeTemplate()->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func)); + _ctorTemplate.Get(__isolate)->PrototypeTemplate()->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func, createExternal(__isolate, data))); return true; } -bool Class::defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter) { +bool Class::defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter, void *data) { v8::MaybeLocal jsName = v8::String::NewFromUtf8(__isolate, name, v8::NewStringType::kNormal); if (jsName.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->PrototypeTemplate()->SetAccessor(jsName.ToLocalChecked(), getter, setter); + _ctorTemplate.Get(__isolate)->PrototypeTemplate()->SetAccessor(jsName.ToLocalChecked(), getter, setter, createExternal(__isolate, data)); return true; } -bool Class::defineProperty(const std::initializer_list &names, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter) { +bool Class::defineProperty(const std::initializer_list &names, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter, void *data) { bool ret = true; for (const auto *name : names) { - ret &= defineProperty(name, getter, setter); + ret &= defineProperty(name, getter, setter, data); } return ret; } -bool Class::defineStaticFunction(const char *name, v8::FunctionCallback func) { +bool Class::defineStaticFunction(const char *name, v8::FunctionCallback func, void *data) { v8::MaybeLocal jsName = v8::String::NewFromUtf8(__isolate, name, v8::NewStringType::kNormal); if (jsName.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func)); + _ctorTemplate.Get(__isolate)->Set(jsName.ToLocalChecked(), v8::FunctionTemplate::New(__isolate, func, createExternal(__isolate, data))); return true; } -bool Class::defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter) { +bool Class::defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter, void *data) { v8::MaybeLocal jsName = v8::String::NewFromUtf8(__isolate, name, v8::NewStringType::kNormal); if (jsName.IsEmpty()) { return false; } - _ctorTemplate.Get(__isolate)->SetNativeDataProperty(jsName.ToLocalChecked(), getter, setter); + _ctorTemplate.Get(__isolate)->SetNativeDataProperty(jsName.ToLocalChecked(), getter, setter, createExternal(__isolate, data)); return true; } diff --git a/native/cocos/bindings/jswrapper/v8/Class.h b/native/cocos/bindings/jswrapper/v8/Class.h index bac410c9f6..50ff1c10db 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.h +++ b/native/cocos/bindings/jswrapper/v8/Class.h @@ -47,48 +47,53 @@ public: * @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, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor); + static Class *create(const ccstd::string &clsName, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data = nullptr); - static Class *create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor); + static Class *create(const std::initializer_list &classPath, se::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. */ - bool defineFunction(const char *name, v8::FunctionCallback func); + 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. */ - bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); + bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter, void *data = nullptr); - bool defineProperty(const std::initializer_list &names, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); + bool defineProperty(const std::initializer_list &names, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback 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. */ - bool defineStaticFunction(const char *name, v8::FunctionCallback func); + 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. */ - bool defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); + bool defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter, void *data = nullptr); /** * @brief Defines the finalize function with a callback. @@ -126,7 +131,7 @@ private: void setCreateProto(bool createProto); - bool init(const ccstd::string &clsName, Object *parent, Object *parentProto, v8::FunctionCallback ctor); + bool init(const ccstd::string &clsName, Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data = nullptr); void destroy(); static void cleanup(); diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 02b10c02e7..7bbb928a1e 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -535,7 +535,7 @@ holder_convert_to(In &input) { // NOLINT(readability-identifier-naming) template struct HolderType { - using type = typename std::remove_const::type; + using type = typename std::remove_const::type>::type; using local_type = typename std::conditional_t, std::add_pointer_t, type>; local_type data; type *ptr = nullptr; @@ -550,7 +550,7 @@ struct HolderType { ~HolderType() { //delete ptr; if (ptr) { - ptr->~T(); + ptr->~type(); } } }; @@ -635,9 +635,9 @@ struct is_variant> : std::true_type {}; // NOLINT template inline typename std::enable_if_t::value && !std::is_pointer::value && !is_jsb_object_v, bool> sevalue_to_native(const se::Value & /*from*/, T * /*to*/, se::Object * /*unused*/) { // NOLINT(readability-identifier-naming) - SE_LOGE("Can not convert type ???\n - [[ %s ]]\n", typeid(T).name()); - CC_STATIC_ASSERT(!is_variant::value, "should not match ccstd::variant"); - CC_STATIC_ASSERT((std::is_same::value), "sevalue_to_native not implemented for T"); + SE_LOGE("Missing conversion impl `sevalue_to_native` for type [[%s]]\n", typeid(T).name()); + CC_STATIC_ASSERT(!is_variant::value, "should not match cc::variant"); + CC_STATIC_ASSERT((std::is_same::value), "Type incorrect or implementation not found!"); return false; } diff --git a/native/cocos/bindings/sebind/class.inl b/native/cocos/bindings/sebind/class.inl new file mode 100644 index 0000000000..916b0eff60 --- /dev/null +++ b/native/cocos/bindings/sebind/class.inl @@ -0,0 +1,414 @@ +/**************************************************************************** + Copyright (c) 2022 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 +#include "base/memory/Memory.h" +#include "bindings/jswrapper/SeApi.h" +#include "bindings/jswrapper/Value.h" + + +#include "bindings/manual/jsb_conversions.h" +#include "bindings/manual/jsb_global.h" +#include "intl/common.h" + +namespace sebind { + +/** + * @brief Remove all cached data. Should be invoked before restart. + * + */ +inline void reset() { + intl::ContextDB::reset(); +} + +/** + * @brief Export C++ Class/Funtions to JS + * + * @tparam T C++ type + */ +template +class class_ final { //NOLINT +public: + using class_type = T; + using Context = intl::ContextDB::Context; + + explicit class_(Context *ctx) : _ctx(ctx) {} + + /** + * @brief Construct a new class_ object + * + * @param name specify the class name in JS + */ + explicit class_(const char *name); + + /** + * @brief Construct a new class_ object + * + * @param name Specify the class name in JS + * @param parentProto The prototype object of the parent class + */ + explicit class_(const char *name, se::Object *parentProto); + + ~class_() { + assert(_installed); // procedure `class_::install` has not been invoked? + } + + /** + * @brief Attach the function object to the namespace object, + * then the exported class can be accessed through the namespace object in JS. + * And the namespace object is a global object in most cases. + * + * @param nsObject the namespace object + * @return true + */ + bool install(se::Object *nsObject); + + /** + * @brief Define a constructor by argument type list + * + * The parameter list must match a specific constructor. + * + * @tparam ARGS parameter types for a constructor of class T + * @return class_& + */ + template + class_ &constructor(); + + /** + * @brief Define a constructor by a function + * + * The signature of the function pointer can be + * - `bool(*)(se::State&)` + * or + * - `T*(*)(ARGS...)` + * + * @tparam F + * @param callback The function pointer + * @return class_& + */ + template + class_ &constructor(F callback); + + /** + * @brief Register a callback when GC occurs + * @param callback GC callback + * @return class_& + */ + class_ &finalizer(void (*callback)(T *)); + + /** + * @brief Define a member function for js class + * + * @tparam Method + * @param name The method name + * @param method Member function pointer of class `T`, or normal function which the first argument is `T*`. + * @return class_& + */ + template + class_ &function(const char *name, Method method); + + /** + * @brief Define a property for js class + * + * @tparam Field + * @param name Field name + * @param field Member data pointer of class `T` + * @return class_& + */ + template + class_ &property(const char *name, Field field); + + /** + * @brief Define a property for JS class + * + * The getter and setter can not be both null. + * @tparam Getter Member function pointer or normal function pointer which first parameter is `T*`. + * @tparam Setter Member function pointer or normal function pointer which first parameter is `T*`. + * @param name Property name + * @param getter Getter function pointer + * @param setter Setter function pointer + * @return class_& + */ + template + class_ &property(const char *name, Getter getter, Setter setter); + + /** + * @brief Define a static property for JS class + * + * @tparam Method static function pointer or normal function pointer. + * @param name property name + * @param method function pointer + * @return class_& + */ + template + class_ &staticFunction(const char *name, Method method); + + /** + * @brief Define a static property for JS class + * + * The getter and setter can not be both null. + * + * @tparam Getter Static function pointer or normal function pointer. + * @tparam Setter Static function pointer or normal function pointer. + * @param name property name + * @param getter function pointer + * @param setter function pointer + * @return class_& + */ + template + class_ &staticProperty(const char *name, Getter getter, Setter setter); + + /** + * @brief Define a constructor with verbose callback. + * + * @param callback function pointer + * @return class_& + */ + class_ &constructor(SeCallbackFnPtr callback); + + /** + * @brief Define a function with verbose callback. + * + * @param name function name + * @param callback function pointer + * @return class_& + */ + class_ &function(const char *name, SeCallbackFnPtr callback); + + /** + * @brief Define a property with verbose callback. + * getter and setter can not be both null + * @param name property name + * @param getter function pointer + * @param setter function pointer + * @return class_& + */ + class_ &property(const char *name, SeCallbackFnPtr getter, SeCallbackFnPtr setter); + + /** + * @brief Define static function with verbose callback + * + * @param name static function name + * @param callback + * @return class_& + */ + class_ &staticFunction(const char *name, SeCallbackFnPtr callback); + + /** + * @brief Define a property with verbose callback. + * getter and setter can not be both null + * @param name property name + * @param getter function pointer + * @param setter function pointer + * @return class_& + */ + class_ &staticProperty(const char *name, SeCallbackFnPtr getter, SeCallbackFnPtr setter); + + /** + * @brief Prototype of JS class, only valid after invoke install. + * + * @return se::Object* + */ + se::Object *prototype() { + return _ctx->kls->getProto(); + } + +private: + bool _installed{false}; + Context *_ctx{nullptr}; + template + friend void genericConstructor(const v8::FunctionCallbackInfo &); +}; + +// implements + +template +class_::class_(const char *name) { + _ctx = intl::ContextDB::instance()[name]; + _ctx->className = name; +} + +template +class_::class_(const char *name, se::Object *parentProto) { + _ctx = intl::ContextDB::instance()[name]; + _ctx->className = name; + _ctx->parentProto = parentProto; +} + +template +template +class_ &class_::constructor() { + using CTYPE = intl::Constructor>; + using MTYPE = intl::TypeMapping>; + static_assert(intl::IsConstructibleWithTypeList::value, "No matched constructor found"); + auto *constructp = ccnew CTYPE(); + constructp->argCount = MTYPE::NEW_ARGN; + _ctx->constructors.emplace_back(constructp); + return *this; +} + +template +template +class_ &class_::constructor(F callback) { + using FTYPE = intl::FunctionWrapper; + static_assert(std::is_same::value, "Function should return a instance pointer"); + using CTYPE = intl::Constructor; + auto *constructp = ccnew CTYPE(); + constructp->argCount = FTYPE::ARG_N; + constructp->func = callback; + _ctx->constructors.emplace_back(constructp); + return *this; +} + +template +class_ &class_::constructor(SeCallbackFnPtr callback) { + auto *constructp = ccnew intl::ConstructorBase(); + constructp->argCount = -1; + constructp->bfnPtr = callback; + _ctx->constructors.emplace_back(constructp); + return *this; +} + +template +class_ &class_::finalizer(void (*callback)(T *)) { + auto *fin = ccnew intl::Finalizer(); + fin->func = callback; + _ctx->finalizeCallbacks.emplace_back(fin); + return *this; +} + +template +template +class_ &class_::function(const char *name, Method method) { + using MTYPE = intl::InstanceMethod; + static_assert(std::is_base_of::value, "incorrect class type"); + auto *methodp = ccnew MTYPE(); + methodp->methodName = name; + methodp->className = _ctx->className; + methodp->argCount = MTYPE::ARG_N; + methodp->func = method; + _ctx->functions.emplace_back(name, methodp); + return *this; +} + +template +class_ &class_::function(const char *name, SeCallbackFnPtr callback) { + auto *methodp = ccnew intl::InstanceMethodBase(); + methodp->methodName = name; + methodp->className = _ctx->className; + methodp->argCount = -1; + methodp->bfnPtr = callback; + _ctx->functions.emplace_back(name, methodp); + return *this; +} + +template +template +class_ &class_::property(const char *name, Field field) { + static_assert(std::is_member_pointer::value, "2nd parameter should be a member pointer"); + using FTYPE = intl::InstanceField; + static_assert(std::is_base_of::value, "class_type incorrect"); + auto *fieldp = ccnew FTYPE(); + fieldp->func = field; + fieldp->attrName = name; + fieldp->className = _ctx->className; + _ctx->fields.emplace_back(name, fieldp); + return *this; +} + +template +template +class_ &class_::property(const char *name, Getter getter, Setter setter) { + using ATYPE = intl::InstanceAttribute>; + auto *attrp = ccnew ATYPE(); + attrp->getterPtr = ATYPE::HAS_GETTER ? getter : nullptr; + attrp->setterPtr = ATYPE::HAS_SETTER ? setter : nullptr; + attrp->className = _ctx->className; + attrp->attrName = name; + _ctx->properties.emplace_back(name, attrp); + return *this; +} + +template +class_ &class_::property(const char *name, SeCallbackFnPtr getter, SeCallbackFnPtr setter) { + auto *attrp = ccnew intl::InstanceAttributeBase(); + attrp->bfnGetPtr = getter; + attrp->bfnSetPtr = setter; + attrp->className = _ctx->className; + attrp->attrName = name; + _ctx->properties.emplace_back(name, attrp); + return *this; +} + +template +template +class_ &class_::staticFunction(const char *name, Method method) { + using MTYPE = intl::StaticMethod; + auto *methodp = ccnew MTYPE(); + methodp->methodName = name; + methodp->className = _ctx->className; + methodp->argCount = MTYPE::ARG_N; + methodp->func = method; + _ctx->staticFunctions.emplace_back(name, methodp); + return *this; +} + +template +class_ &class_::staticFunction(const char *name, SeCallbackFnPtr callback) { + auto *methodp = ccnew intl::StaticMethodBase(); + methodp->methodName = name; + methodp->className = _ctx->className; + methodp->argCount = -1; + methodp->bfnPtr = callback; + _ctx->staticFunctions.emplace_back(name, methodp); + return *this; +} + +template +template +class_ &class_::staticProperty(const char *name, Getter getter, Setter setter) { + using ATYPE = intl::StaticAttribute>; + auto *attrp = ccnew ATYPE(); + attrp->getterPtr = ATYPE::HAS_GETTER ? getter : nullptr; + attrp->setterPtr = ATYPE::HAS_SETTER ? setter : nullptr; + attrp->className = _ctx->className; + attrp->attrName = name; + _ctx->staticProperties.emplace_back(name, attrp); + return *this; +} + +template +class_ &class_::staticProperty(const char *name, SeCallbackFnPtr getter, SeCallbackFnPtr setter) { + auto *attrp = ccnew intl::StaticAttributeBase(); + attrp->bfnGetPtr = getter; + attrp->bfnSetPtr = setter; + attrp->className = _ctx->className; + attrp->attrName = name; + _ctx->staticProperties.emplace_back(name, attrp); + return *this; +} + +} // namespace sebind diff --git a/native/cocos/bindings/sebind/class_v8.cpp b/native/cocos/bindings/sebind/class_v8.cpp new file mode 100644 index 0000000000..a13aaefc96 --- /dev/null +++ b/native/cocos/bindings/sebind/class_v8.cpp @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2022 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "class_v8.h" + +namespace sebind { +// adoption layer from v8 function to se function +void genericFunction(const v8::FunctionCallbackInfo &v8args) { + void *ctx = v8args.Data().IsEmpty() ? nullptr : v8args.Data().As()->Value(); + auto *method = reinterpret_cast(ctx); + assert(ctx); + bool ret = false; + v8::Isolate *isolate = v8args.GetIsolate(); + v8::HandleScope handleScope(isolate); + se::ValueArray &args = se::gValueArrayPool.get(v8args.Length()); + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; + se::internal::jsToSeArgs(v8args, args); + auto *thisObject = reinterpret_cast(se::internal::getPrivate(isolate, v8args.This())); + se::State state(thisObject, args); + ret = method->invoke(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", method->methodName.c_str(), __FILE__, __LINE__); + } + se::internal::setReturnValue(state.rval(), v8args); +} + +} // namespace sebind diff --git a/native/cocos/bindings/sebind/class_v8.h b/native/cocos/bindings/sebind/class_v8.h new file mode 100644 index 0000000000..374745c8d3 --- /dev/null +++ b/native/cocos/bindings/sebind/class_v8.h @@ -0,0 +1,194 @@ +/**************************************************************************** + Copyright (c) 2022 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "class.inl" + +namespace sebind { +// finalizer callback +template +void genericFinalizer(se::Object *obj) { + se::PrivateObjectBase *privateObject = obj->getPrivateObject(); + using context_type = typename class_::Context; + if (privateObject == nullptr) { + return; + } + auto *scriptEngine = se::ScriptEngine::getInstance(); + scriptEngine->_setGarbageCollecting(true); + auto *self = reinterpret_cast(privateObject->finalizerData); + auto *thisPtr = privateObject->get(); + for (auto &fin : self->finalizeCallbacks) { + fin->finalize(thisPtr); + } + scriptEngine->_setGarbageCollecting(false); +} + +// function wrappers for v8 +template +void genericConstructor(const v8::FunctionCallbackInfo &v8args) { + using context_type = typename class_::Context; + v8::Isolate *isolate = v8args.GetIsolate(); + v8::HandleScope handleScope(isolate); + bool ret = false; + se::ValueArray &args = se::gValueArrayPool.get(v8args.Length()); + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; + se::internal::jsToSeArgs(v8args, args); + auto *self = reinterpret_cast(v8args.Data().IsEmpty() ? nullptr : v8args.Data().As()->Value()); + se::Object *thisObject = se::Object::_createJSObject(self->kls, v8args.This()); + if (!self->finalizeCallbacks.empty()) { + auto *finalizer = &genericFinalizer; + thisObject->_setFinalizeCallback(finalizer); + } + se::State state(thisObject, args); + + assert(!self->constructors.empty()); + for (auto &ctor : self->constructors) { + if (ctor->argCount == -1 || ctor->argCount == args.size()) { + ret = ctor->construct(state); + if (ret) break; + } + } + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", "constructor", __FILE__, __LINE__); + } + assert(ret); // construction failure is not allowed. + if (!self->finalizeCallbacks.empty()) { + state.thisObject()->getPrivateObject()->finalizerData = self; + } + + se::Value propertyVal; + bool found = false; + found = thisObject->getProperty("_ctor", &propertyVal); + if (found) propertyVal.toObject()->call(args, thisObject); +} +// v8 property callback +template +void genericAccessorSet(v8::Local /*prop*/, v8::Local jsVal, + const v8::PropertyCallbackInfo &v8args) { + auto *attr = reinterpret_cast(v8args.Data().IsEmpty() ? nullptr : v8args.Data().As()->Value()); + assert(attr); + v8::Isolate *isolate = v8args.GetIsolate(); + v8::HandleScope handleScope(isolate); + bool ret = true; + auto *thisObject = reinterpret_cast(se::internal::getPrivate(isolate, v8args.This())); + se::ValueArray &args = se::gValueArrayPool.get(1); + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; + se::Value &data{args[0]}; + se::internal::jsToSeValue(isolate, jsVal, &data); + se::State state(thisObject, args); + ret = attr->set(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke set %s, location: %s:%d\n", attr->attrName.c_str(), __FILE__, __LINE__); + } +} +template +void genericAccessorGet(v8::Local /*prop*/, + const v8::PropertyCallbackInfo &v8args) { + auto *attr = reinterpret_cast(v8args.Data().IsEmpty() ? nullptr : v8args.Data().As()->Value()); + assert(attr); + v8::Isolate *isolate = v8args.GetIsolate(); + v8::HandleScope handleScope(isolate); + bool ret = true; + auto *thisObject = reinterpret_cast(se::internal::getPrivate(isolate, v8args.This())); + se::State state(thisObject); + ret = attr->get(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", attr->attrName.c_str(), __FILE__, __LINE__); + } + se::internal::setReturnValue(state.rval(), v8args); +} + +void genericFunction(const v8::FunctionCallbackInfo &v8args); + +template +bool class_::install(se::Object *nsObject) { + constexpr auto *cstp = &genericConstructor; + assert(nsObject); + _installed = true; + + if (_ctx->constructors.empty()) { + if CC_CONSTEXPR (std::is_default_constructible::value) { + constructor(); // add default constructor + } + } + _ctx->kls = se::Class::create(_ctx->className, nsObject, _ctx->parentProto, cstp, _ctx); + + auto *getter = &genericAccessorGet; + auto *setter = &genericAccessorSet; + for (auto &attr : _ctx->properties) { + _ctx->kls->defineProperty(std::get<0>(attr).c_str(), getter, setter, std::get<1>(attr).get()); + } + auto *fieldGetter = &genericAccessorGet; + auto *fieldSetter = &genericAccessorSet; + for (auto &field : _ctx->fields) { + _ctx->kls->defineProperty(std::get<0>(field).c_str(), fieldGetter, fieldSetter, std::get<1>(field).get()); + } + // defineFunctions + { + ccstd::unordered_map> multimap; + for (auto &method : _ctx->functions) { + multimap[std::get<0>(method)].emplace_back(std::get<1>(method).get()); + } + for (auto &method : multimap) { + if (method.second.size() > 1) { + auto *overloaded = ccnew intl::InstanceMethodOverloaded; + overloaded->className = _ctx->className; + overloaded->methodName = method.first; + for (auto *method : method.second) { + overloaded->functions.push_back(method); + } + _ctx->kls->defineFunction(method.first.c_str(), &genericFunction, overloaded); + } else { + _ctx->kls->defineFunction(method.first.c_str(), &genericFunction, method.second[0]); + } + } + } + // define static functions + { + ccstd::unordered_map> multimap; + for (auto &method : _ctx->staticFunctions) { + multimap[std::get<0>(method)].emplace_back(std::get<1>(method).get()); + } + for (auto &method : multimap) { + if (method.second.size() > 1) { + auto *overloaded = ccnew intl::StaticMethodOverloaded; + overloaded->className = _ctx->className; + overloaded->methodName = method.first; + for (auto *method : method.second) { + overloaded->functions.push_back(method); + } + _ctx->kls->defineStaticFunction(method.first.c_str(), &genericFunction, overloaded); + } else { + _ctx->kls->defineStaticFunction(method.first.c_str(), &genericFunction, method.second[0]); + } + } + } + for (auto &prop : _ctx->staticProperties) { + _ctx->kls->defineStaticProperty(std::get<0>(prop).c_str(), fieldGetter, fieldSetter, std::get<1>(prop).get()); + } + _ctx->kls->install(); + return true; +} +} // namespace sebind diff --git a/native/cocos/bindings/sebind/intl/common.cpp b/native/cocos/bindings/sebind/intl/common.cpp new file mode 100644 index 0000000000..dd79c9dd24 --- /dev/null +++ b/native/cocos/bindings/sebind/intl/common.cpp @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2022 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "common.h" +namespace sebind { + +namespace intl { +ContextDB::Context *ContextDB::operator[](const char *key) { + auto itr = _contexts.find(key); + if (itr == _contexts.end()) { + auto *ctx = ccnew Context; + _contexts.emplace(key, ctx); + return ctx; + } + return itr->second.get(); +} + +ContextDB &ContextDB::instance() { + static ContextDB database; + return database; +} + +void ContextDB::reset() { + auto &inst = instance(); + inst._contexts.clear(); +} +} // namespace intl +} // namespace sebind diff --git a/native/cocos/bindings/sebind/intl/common.h b/native/cocos/bindings/sebind/intl/common.h new file mode 100644 index 0000000000..55cdeb446c --- /dev/null +++ b/native/cocos/bindings/sebind/intl/common.h @@ -0,0 +1,1005 @@ +/**************************************************************************** + Copyright (c) 2022 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 +#include +#include +#include + +#include "bindings/manual/jsb_conversions.h" +#include "bindings/manual/jsb_global.h" + +#include "base/std/container/string.h" +#include "base/std/container/vector.h" +#include "base/std/container/array.h" +#include "base/std/container/unordered_map.h" + +namespace sebind { + +struct ThisObject {}; +using SeCallbackType = bool(se::State &); +using SeCallbackFnPtr = bool (*)(se::State &); + +namespace intl { + +template +struct TypeList; + +template +struct TypeList { + constexpr static size_t COUNT = 1 + sizeof...(OTHERS); + using head = T; + using tail = TypeList; + using tuple_type = std::tuple; + using tuple_type_mutable = std::tuple::type>::type, + typename std::remove_reference::type>::type...>; +}; + +template <> +struct TypeList<> { + constexpr static size_t COUNT = 0; + using head = void; + using tail = TypeList<>; + using tuple_type = std::tuple<>; + using tuple_type_mutable = std::tuple<>; +}; + +template +struct Cons; + +template +struct Cons> { + using type = TypeList; +}; + +template +struct FunctionWrapper; + +template +struct FunctionWrapper { + using type = R (*)(C *, ARGS...); + using return_type = R; + using arg_list = TypeList; + static constexpr size_t ARG_N = sizeof...(ARGS); + template + inline static R invoke(type func, C *self, ARGS2 &&... args) { + return (*func)(self, std::forward(args)...); + } +}; + +template +struct FunctionWrapper { + using type = R (C::*)(ARGS...); + using return_type = R; + using arg_list = TypeList; + static constexpr size_t ARG_N = sizeof...(ARGS); + template + inline static R invoke(type func, C *self, ARGS2 &&... args) { + return (self->*func)(std::forward(args)...); + } +}; + +template +struct FunctionWrapper { + using type = R (C::*)(ARGS...) const; + using return_type = R; + using arg_list = TypeList; + static constexpr size_t ARG_N = sizeof...(ARGS); + template + inline static R invoke(type func, C *self, ARGS2 &&... args) { + return (self->*func)(std::forward(args)...); + } +}; + +template <> +struct FunctionWrapper { + using type = std::nullptr_t; + using return_type = std::nullptr_t; + using arg_list = TypeList<>; + static constexpr size_t ARG_N = 0; + template + static void invoke(type /*func*/, C * /*self*/, ARGS &&... /*args*/) { + } +}; + +template +struct StaticFunctionWrapper; + +template +struct StaticFunctionWrapper { + using type = R (*)(ARGS...); + using return_type = R; + using arg_list = TypeList; + static constexpr size_t ARG_N = sizeof...(ARGS); + template + inline static R invoke(type func, ARGS2 &&... args) { + return (*func)(std::forward(args)...); + } +}; + +template <> +struct StaticFunctionWrapper { + using type = std::nullptr_t; + using return_type = void; + using arg_list = TypeList<>; + static constexpr size_t ARG_N = 0; + template + static void invoke(type /*func*/, ARGS &&... /*args*/) { + } +}; + +template +struct IsConstructibleWithTypeList; + +template +struct IsConstructibleWithTypeList> { + // NOLINTNEXTLINE + constexpr static bool value = std::is_constructible::value; +}; + +template +struct MapTypeListToTuple; + +template +struct MapTypeListToTuple> { + using tuple = std::tuple::value>...>; +}; + +template +struct IsThisObject { + // NOLINTNEXTLINE + constexpr static bool value = std::is_same::type>::type>::type>::value; +}; + +template +struct FilterThisObject; + +template +struct FilterThisObject { + using filtered_types = std::conditional_t::value, + typename FilterThisObject::filtered_types, + typename Cons::filtered_types>::type>; + using mapped_types = typename Cons::value, se::Object *, T>, + typename FilterThisObject::mapped_types>::type; +}; + +template <> +struct FilterThisObject<> { + using filtered_types = TypeList<>; + using mapped_types = TypeList<>; +}; + +template +struct MapArg { + constexpr static size_t FROM = From; + constexpr static size_t TO = To; // NOLINT + constexpr static bool SKIP = Skip; +}; + +template +struct GenMapArgImpl { + using list = typename Cons, typename GenMapArgImpl::list>::type; +}; + +template +struct GenMapArgImpl { + using list = TypeList<>; +}; + +template +struct GenMapArg { + using list = typename GenMapArgImpl<0, N>::list; +}; + +template +struct TypeListMapImpl { + constexpr static bool SHOULD_SKIP = IsThisObject::value; + constexpr static int NEXT_INCOMPLETE = SHOULD_SKIP ? IncompleteIdx : IncompleteIdx + 1; + constexpr static int NEXT_INCOMPLETE_REMAIN = SHOULD_SKIP ? IncompleteRemain : IncompleteRemain - 1; + using full_tail = typename FullTypeList::tail; + using incomplete_tail = std::conditional_t; + using map_value = MapArg; + using map_list = typename Cons::map_list>::type; +}; + +template +struct TypeListMapImpl { + using map_list = TypeList<>; +}; + +template +struct TypeListMapImpl { + static_assert(FullRemain == FullTypeList::COUNT, "Parameter count incorrect!"); + using map_list = typename GenMapArg::list; +}; + +template +struct TypeListMap { + using map_list = typename TypeListMapImpl<0, 0, FullTypeList::COUNT, IncompleteTypeList::COUNT, FullTypeList, IncompleteTypeList>::map_list; +}; + +template +struct TypeMapping; + +template +struct TypeMapping> { + using declare_types = TypeList; + using input_types = typename FilterThisObject::filtered_types; + using result_types = typename FilterThisObject::mapped_types; + using result_types_tuple = typename result_types::tuple_type; + using result_types_tuple_mutable = typename result_types::tuple_type_mutable; + using input_types_tuple = typename input_types::tuple_type; + using mapping_list = typename TypeListMap::map_list; + static constexpr size_t FULL_ARGN = sizeof...(ARGS); + static constexpr size_t NEW_ARGN = input_types::COUNT; + static constexpr bool NEED_REMAP = FULL_ARGN != NEW_ARGN; +}; +template +struct TypeMapReturnSwitch; + +template +struct TypeMapReturnSwitch { + template + static se::Object *select(se::Object *self, V & /*unused*/) { + return self; + } +}; + +template +struct TypeMapReturnSwitch { + template + static auto select(se::Object * /*unused*/, V &tuple) { + return std::get(tuple).value(); + } +}; + +struct ArgumentFilter { + template + static auto forward(se::Object *self, Tuple &tuple) { + constexpr static MapTuple TUPLE_VAL; + using map_arg = std::remove_reference_t(TUPLE_VAL))>; + return TypeMapReturnSwitch::select(self, tuple); + } +}; + +template +ResultType mapTupleArguments(se::Object *self, TupleIn &input, std::index_sequence /*args*/) { + using map_tuple = typename Mapping::mapping_list::tuple_type; + using result_type = typename Mapping::result_types_tuple_mutable; + static_assert(std::is_same::value, "result_type mismatch"); + //if CC_CONSTEXPR (std::tuple_size::value > 0) { + return result_type(ArgumentFilter::forward(self, input)...); + //} + //return result_type(); +} + +template +struct BoolArrayAndAll { + static constexpr bool cal(const ccstd::array &bools) { + return bools[M - 1] && BoolArrayAndAll::cal(bools); + } +}; + +template +struct BoolArrayAndAll<0, N> { + static constexpr bool cal(const ccstd::array & /*unused*/) { + return true; + } +}; + +template +// NOLINTNEXTLINE +bool convert_js_args_to_tuple(const se::ValueArray &jsArgs, std::tuple &args, se::Object *thisObj, std::index_sequence) { + constexpr static size_t ARG_N = sizeof...(ARGS); + ccstd::array all = {sevalue_to_native(jsArgs[indexes], &std::get(args).data, thisObj)...}; + return BoolArrayAndAll::cal(all); +} +template +// NOLINTNEXTLINE +bool convert_js_args_to_tuple(const se::ValueArray &jsArgs, std::tuple<> &args, se::Object *ctx, std::index_sequence) { + return true; +} + +struct ConstructorBase { + size_t argCount = 0; + SeCallbackFnPtr bfnPtr{nullptr}; + virtual bool construct(se::State &state) { + if (bfnPtr) { + return (*bfnPtr)(state); + } + return false; + } +}; +struct InstanceMethodBase { + ccstd::string className; + ccstd::string methodName; + size_t argCount = 0; + SeCallbackFnPtr bfnPtr{nullptr}; + virtual bool invoke(se::State &state) const { + if (bfnPtr) { + return (*bfnPtr)(state); + } + return false; + } +}; +struct FinalizerBase { + virtual void finalize(void * /*unused*/) {} +}; + +struct InstanceFieldBase { + ccstd::string className; + ccstd::string attrName; + SeCallbackFnPtr bfnSetPtr{nullptr}; + SeCallbackFnPtr bfnGetPtr{nullptr}; + virtual bool get(se::State &state) const { + if (bfnGetPtr) return (*bfnGetPtr)(state); + return false; + } + virtual bool set(se::State &state) const { + if (bfnSetPtr) return (*bfnSetPtr)(state); + return false; + } +}; + +struct InstanceAttributeBase { + ccstd::string className; + ccstd::string attrName; + SeCallbackFnPtr bfnSetPtr{nullptr}; + SeCallbackFnPtr bfnGetPtr{nullptr}; + virtual bool get(se::State &state) const { + if (bfnGetPtr) return (*bfnGetPtr)(state); + return false; + } + virtual bool set(se::State &state) const { + if (bfnSetPtr) return (*bfnSetPtr)(state); + return false; + } +}; + +struct StaticMethodBase { + ccstd::string className; + ccstd::string methodName; + size_t argCount = 0; + SeCallbackFnPtr bfnPtr{nullptr}; + virtual bool invoke(se::State &state) const { + if (bfnPtr) return (*bfnPtr)(state); + return false; + } +}; +struct StaticAttributeBase { + ccstd::string className; + ccstd::string attrName; + SeCallbackFnPtr bfnSetPtr{nullptr}; + SeCallbackFnPtr bfnGetPtr{nullptr}; + virtual bool get(se::State &state) const { + if (bfnGetPtr) return (*bfnGetPtr)(state); + return false; + } + virtual bool set(se::State &state) const { + if (bfnSetPtr) return (*bfnSetPtr)(state); + return false; + } +}; + +template +struct Constructor; + +template +struct InstanceField; + +template +struct InstanceMethod; + +template +struct InstanceAttribute; + +template +struct StaticMethod; + +template +struct StaticAttribute; + +template +struct Constructor> : ConstructorBase { + // no `if constexpr`, more code is needed... + template + struct ConstructFn; + template <> + struct ConstructFn { + template + static auto invoke(Self *self, se::Object *thisObj, std::tuple &args, std::index_sequence n) { + using type_mapping = TypeMapping>; + using map_list_type = typename type_mapping::mapping_list; + using map_tuple_type = typename type_mapping::result_types_tuple_mutable; + + static_assert(map_list_type::COUNT == sizeof...(ARGS), "type mapping incorrect"); + + map_tuple_type remapArgs = mapTupleArguments(thisObj, args, std::make_index_sequence{}); + + return self->constructWithTuple(remapArgs, n); + } + }; + template <> + struct ConstructFn { + template + static auto invoke(Self *self, se::Object * /*thisObj*/, std::tuple &args, std::index_sequence n) { + return self->constructWithTupleValue(args, n); + } + }; + + bool construct(se::State &state) override { + using type_mapping = TypeMapping>; + using args_holder_type = typename MapTypeListToTuple::tuple; + se::PrivateObjectBase *self{nullptr}; + se::Object *thisObj = state.thisObject(); + args_holder_type args{}; + const auto &jsArgs = state.args(); + convert_js_args_to_tuple(jsArgs, args, thisObj, std::make_index_sequence()); + self = ConstructFn::invoke(this, thisObj, args, std::make_index_sequence{}); + state.thisObject()->setPrivateObject(self); + return true; + } + + template + se::PrivateObjectBase *constructWithTuple(std::tuple &args, std::index_sequence /*unused*/) { + return JSB_MAKE_PRIVATE_OBJECT(T, std::get(args)...); + } + + template + se::PrivateObjectBase *constructWithTupleValue(std::tuple &args, std::index_sequence /*unused*/) { + return JSB_MAKE_PRIVATE_OBJECT(T, std::get(args).value()...); + } +}; + +template +struct Constructor : ConstructorBase { + using type = T *(*)(ARGS...); + type func{nullptr}; + bool construct(se::State &state) override { + if ((sizeof...(ARGS)) != state.args().size()) { + return false; + } + std::tuple::value>...> args{}; + const auto &jsArgs = state.args(); + se::Object *thisObj = state.thisObject(); + convert_js_args_to_tuple(jsArgs, args, thisObj, std::make_index_sequence()); + T *ptr = constructWithTuple(args, std::make_index_sequence()); + state.thisObject()->setPrivateData(ptr); + return true; + } + + template + T *constructWithTuple(std::tuple &args, std::index_sequence /*unused*/) { + return (*func)(std::get(args).value()...); + } +}; + +template +struct Finalizer : FinalizerBase { + using type = void (*)(T *); + using arg_type = T; + type func{nullptr}; + void finalize(void *ptr) override { + (*func)(reinterpret_cast(ptr)); + } +}; + +template +struct InstanceMethod : InstanceMethodBase { + using type = R (T::*)(ARGS...); + using return_type = R; + using class_type = std::remove_cv_t; + constexpr static size_t ARG_N = sizeof...(ARGS); + constexpr static bool RETURN_VOID = std::is_same::value; + + type func{nullptr}; + + template + struct Invoker; + template <> + struct Invoker { + template + static void invoke(S *method, T *self, se::State & /*state*/, std::tuple &args, std::index_sequence idx) { + method->callWithTuple(self, args, idx); + } + }; + template <> + struct Invoker { + template + static void invoke(S *method, T *self, se::State &state, std::tuple &args, std::index_sequence idx) { + nativevalue_to_se(method->callWithTuple(self, args, idx), state.rval(), state.thisObject()); + } + }; + + template + R callWithTuple(T *self, std::tuple &args, std::index_sequence /*unused*/) const { + return ((reinterpret_cast(self))->*func)(std::get(args).value()...); + } + + bool invoke(se::State &state) const override { + constexpr auto indexes{std::make_index_sequence()}; + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + const auto &jsArgs = state.args(); + if (ARG_N != jsArgs.size()) { + SE_LOGE("incorret argument size %d, expect %d\n", static_cast(jsArgs.size()), static_cast(ARG_N)); + return false; + } + std::tuple::value>...> args{}; + convert_js_args_to_tuple(jsArgs, args, thisObject, indexes); + Invoker::invoke(this, self, state, args, indexes); + return true; + } +}; + +template +struct InstanceMethod : InstanceMethodBase { + using type = R (T::*)(ARGS...) const; + using return_type = R; + using class_type = std::remove_cv_t; + constexpr static size_t ARG_N = sizeof...(ARGS); + constexpr static bool RETURN_VOID = std::is_same::value; + + type func{nullptr}; + + template + struct Invoker; + template <> + struct Invoker { + template + static void invoke(S *method, T *self, se::State & /*state*/, std::tuple &args, std::index_sequence idx) { + method->callWithTuple(self, args, idx); + } + }; + template <> + struct Invoker { + template + static void invoke(S *method, T *self, se::State &state, std::tuple &args, std::index_sequence idx) { + nativevalue_to_se(method->callWithTuple(self, args, idx), state.rval(), state.thisObject()); + } + }; + + template + R callWithTuple(T *self, std::tuple &args, std::index_sequence /*unused*/) const { + return ((reinterpret_cast(self))->*func)(std::get(args).value()...); + } + + bool invoke(se::State &state) const override { + constexpr auto indexes{std::make_index_sequence()}; + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + const auto &jsArgs = state.args(); + if (ARG_N != jsArgs.size()) { + SE_LOGE("incorret argument size %d, expect %d\n", static_cast(jsArgs.size()), static_cast(ARG_N)); + return false; + } + std::tuple::value>...> args{}; + convert_js_args_to_tuple(jsArgs, args, thisObject, indexes); + Invoker::invoke(this, self, state, args, indexes); + return true; + } +}; + +template +struct InstanceMethod : InstanceMethodBase { + using type = R (*)(T *, ARGS...); + using return_type = R; + using class_type = std::remove_cv_t; + constexpr static size_t ARG_N = sizeof...(ARGS); + constexpr static bool RETURN_VOID = std::is_same::value; + + type func{nullptr}; + + template + struct Invoker; + template <> + struct Invoker { + template + static void invoke(S *method, T *self, se::State & /*state*/, std::tuple &args, std::index_sequence idx) { + method->callWithTuple(self, args, idx); + } + }; + template <> + struct Invoker { + template + static void invoke(S *method, T *self, se::State &state, std::tuple &args, std::index_sequence idx) { + nativevalue_to_se(method->callWithTuple(self, args, idx), state.rval(), state.thisObject()); + } + }; + + template + R callWithTuple(T *self, std::tuple &args, std::index_sequence /*unused*/) const { + return (*func)(reinterpret_cast(self), std::get(args).value()...); + } + + bool invoke(se::State &state) const override { + constexpr auto indexes{std::make_index_sequence()}; + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + const auto &jsArgs = state.args(); + if (ARG_N != jsArgs.size()) { + SE_LOGE("incorret argument size %d, expect %d\n", static_cast(jsArgs.size()), static_cast(ARG_N)); + return false; + } + std::tuple::value>...> args{}; + convert_js_args_to_tuple(jsArgs, args, thisObject, indexes); + Invoker::invoke(this, self, state, args, indexes); + return true; + } +}; + +struct InstanceMethodOverloaded : InstanceMethodBase { + ccstd::vector functions; + bool invoke(se::State &state) const override { + bool ret = false; + auto argCount = state.args().size(); + for (auto *method : functions) { + if (method->argCount == -1 || method->argCount == argCount) { + ret = method->invoke(state); + if (ret) return true; + } + } + return false; + } +}; + +template +struct InstanceField : InstanceFieldBase { + using type = F(T::*); + using class_type = T; + using return_type = std::remove_cv_t; + + type func{nullptr}; + + bool get(se::State &state) const override { + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + return nativevalue_to_se((self->*func), state.rval(), thisObject); + } + + bool set(se::State &state) const override { + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + const auto &args = state.args(); + return sevalue_to_native(args[0], &(self->*func), thisObject); + } +}; + +template +struct AttributeAccessor; + +template +struct AccessorGet { +}; + +template +struct AccessorSet { +}; + +template <> +struct AccessorGet { + using class_type = std::nullptr_t; + using type = std::nullptr_t; + using return_type = std::nullptr_t; +}; + +template <> +struct AccessorSet { + using class_type = std::nullptr_t; + using type = std::nullptr_t; + using value_type = std::nullptr_t; +}; + +template +struct AccessorGet { + using class_type = T; + using type = R (T::*)(); + using return_type = R; + static_assert(!std::is_void::value, "Getter should return a value!"); +}; + +template +struct AccessorSet { + using class_type = T; + using type = R (T::*)(F); + using value_type = F; + using ignored_return_type = R; +}; + +template +struct AccessorGet { + using class_type = T; + using type = R (T::*)() const; + using return_type = R; + static_assert(!std::is_void::value, "Getter should return a value"); +}; + +template +struct AccessorSet { + using class_type = T; + using type = R (*)(T *, F); + using value_type = F; + using ignored_return_type = R; +}; +template +struct AccessorGet { + using class_type = T; + using type = R (*)(T *); + using return_type = R; + static_assert(!std::is_void::value, "Getter should return a value"); +}; + +template +struct InstanceAttribute> : InstanceAttributeBase { + using type = T; + using get_accessor = AccessorGet; + using set_accessor = AccessorSet; + using getter_type = typename get_accessor::type; + using setter_type = typename set_accessor::type; + using set_value_type = std::remove_reference_t>; + using get_value_type = std::remove_reference_t>; + using getter_class_type = typename get_accessor::class_type; + using setter_class_type = typename set_accessor::class_type; + + constexpr static bool HAS_GETTER = !std::is_null_pointer::value; + constexpr static bool HAS_SETTER = !std::is_null_pointer::value; + constexpr static bool GETTER_IS_MEMBER_FN = HAS_GETTER && std::is_member_function_pointer::value; + constexpr static bool SETTER_IS_MEMBER_FN = HAS_SETTER && std::is_member_function_pointer::value; + + static_assert(!HAS_GETTER || std::is_base_of::value, "Getter class type is not valid!"); + static_assert(!HAS_SETTER || std::is_base_of::value, "Setter class type is not valid!"); + + setter_type setterPtr; + getter_type getterPtr; + + template + struct Invoker; + + template <> + struct Invoker { + static bool invoke(getter_type getterPtr, se::State &state) { + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + using func_type = FunctionWrapper; + static_assert(!std::is_void::value, "should return a value"); + return nativevalue_to_se(func_type::invoke(getterPtr, self), state.rval(), thisObject); + } + }; + + template <> + struct Invoker { + static bool invoke(getter_type /*getterPtr*/, se::State & /*state*/) { + return false; + } + }; + + bool get(se::State &state) const override { + return Invoker::invoke(getterPtr, state); + } + + bool set(se::State &state) const override { + if + CC_CONSTEXPR(HAS_SETTER) { + T *self = reinterpret_cast(state.nativeThisObject()); + se::Object *thisObject = state.thisObject(); + const auto &args = state.args(); + HolderType::value> temp; + sevalue_to_native(args[0], &(temp.data), thisObject); + + using func_type = FunctionWrapper; + func_type::invoke(setterPtr, self, temp.value()); + return true; + } + return false; + } +}; + +template +struct StaticMethod : StaticMethodBase { + using type = R (*)(ARGS...); + using return_type = R; + constexpr static size_t ARG_N = sizeof...(ARGS); + constexpr static bool RETURN_VOID = std::is_same::value; + + type func{nullptr}; + + template + struct Invoker; + template <> + struct Invoker { + template + static void invoke(T *self, se::State & /*state*/, std::tuple &args, std::index_sequence idxs) { + self->callWithTuple(args, idxs); + } + }; + template <> + struct Invoker { + template + static void invoke(T *self, se::State &state, std::tuple &args, std::index_sequence idxs) { + nativevalue_to_se(self->callWithTuple(args, idxs), state.rval(), nullptr); + } + }; + + template + R callWithTuple(std::tuple &args, std::index_sequence /*unused*/) const { + return (*func)(std::get(args).value()...); + } + + bool invoke(se::State &state) const override { + constexpr auto indexes{std::make_index_sequence()}; + const auto &jsArgs = state.args(); + if (ARG_N != jsArgs.size()) { + SE_LOGE("incorret argument size %d, expect %d\n", static_cast(jsArgs.size()), static_cast(ARG_N)); + return false; + } + std::tuple::value>...> args{}; + convert_js_args_to_tuple(jsArgs, args, nullptr, indexes); + Invoker::invoke(this, state, args, indexes); + return true; + } +}; + +struct StaticMethodOverloaded : StaticMethodBase { + ccstd::vector functions; + bool invoke(se::State &state) const override { + bool ret = false; + auto argCount = state.args().size(); + for (auto *method : functions) { + if (method->argCount == -1 || method->argCount == argCount) { + ret = method->invoke(state); + if (ret) return true; + } + } + return false; + } +}; + +template +struct SAttributeAccessor; + +template +struct SAccessorGet { + using type = void; + using return_type = void; +}; + +template +struct SAccessorSet { + using type = void; + using value_type = void; +}; + +template <> +struct SAccessorGet { + using type = std::nullptr_t; + using return_type = std::nullptr_t; +}; + +template <> +struct SAccessorSet { + using type = std::nullptr_t; + using value_type = std::nullptr_t; +}; + +template +struct SAccessorGet { + using type = R(*); + using return_type = R; + static_assert(!std::is_void::value, "Getter should return value"); +}; + +template +struct SAccessorSet { + using type = R (*)(F); + using value_type = F; + using ignored_return_type = R; +}; + +template +struct StaticAttribute> : StaticAttributeBase { + using type = T; + using get_accessor = SAccessorGet; + using set_accessor = SAccessorSet; + using getter_type = typename get_accessor::type; + using setter_type = typename set_accessor::type; + using set_value_type = std::remove_reference_t>; + using get_value_type = std::remove_reference_t>; + + constexpr static bool HAS_GETTER = !std::is_null_pointer::value; + constexpr static bool HAS_SETTER = !std::is_null_pointer::value; + + static_assert(HAS_GETTER || HAS_SETTER, "Either getter or setter should be set"); + + setter_type setterPtr; + getter_type getterPtr; + + template + struct Invoker; + + template <> + struct Invoker { + static bool invoke(getter_type getterPtr, se::State &state) { + using func_type = StaticFunctionWrapper; + static_assert(!std::is_void::value, "should return a value"); + return nativevalue_to_se(func_type::invoke(getterPtr), state.rval(), nullptr); + } + }; + + template <> + struct Invoker { + static bool invoke(getter_type /*getterPtr*/, se::State & /*state*/) { + return false; + } + }; + + bool get(se::State &state) const override { + return Invoker::invoke(getterPtr, state); + } + + bool set(se::State &state) const override { + if + CC_CONSTEXPR(HAS_SETTER) { + const auto &args = state.args(); + HolderType::value> temp; + sevalue_to_native(args[0], &(temp.data), nullptr); + using func_type = StaticFunctionWrapper; + func_type::invoke(setterPtr, temp.value()); + return true; + } + return false; + } +}; + +// NOLINTNEXTLINE +class ContextDB { +public: + // NOLINTNEXTLINE + struct Context { + ccstd::vector>> properties; + ccstd::vector>> fields; + ccstd::vector>> functions; + ccstd::vector>> staticFunctions; + ccstd::vector>> staticProperties; + ccstd::vector> constructors; + ccstd::vector> finalizeCallbacks; + ccstd::string className; + se::Class *kls = nullptr; + // se::Object * nsObject = nullptr; + se::Object *parentProto = nullptr; + }; + Context *operator[](const char *key); + static ContextDB &instance(); + static void reset(); + +private: + ccstd::unordered_map> _contexts; +}; + +} // namespace intl +} // namespace sebind diff --git a/native/cocos/bindings/sebind/sebind.h b/native/cocos/bindings/sebind/sebind.h new file mode 100644 index 0000000000..1700e61c36 --- /dev/null +++ b/native/cocos/bindings/sebind/sebind.h @@ -0,0 +1,28 @@ +/**************************************************************************** + Copyright (c) 2022 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "class_v8.h" \ No newline at end of file diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 425aa85fa8..deb98f8dd2 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -31,6 +31,12 @@ #include "base/std/container/vector.h" #include "math/Math.h" +#ifdef Status +// Fix linux compile errors +// In /usr/include/X11/Xlib.h Status defined as int +#undef Status +#endif + /** * Some general guide lines: * Always use explicit numeric types rather than `int`, `long`, etc. for a stable memory layout diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index b33bea0543..4fbd8347cb 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -26,6 +26,7 @@ #include "base/std/container/unordered_map.h" #include "gfx-base/GFXDef.h" #include "gfx-gles-common/GLESCommandPool.h" +#include namespace cc { namespace gfx { @@ -591,4 +592,4 @@ private: }; } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/tests/sebind-tests/.gitignore b/native/tests/sebind-tests/.gitignore new file mode 100644 index 0000000000..28c4b1ff82 --- /dev/null +++ b/native/tests/sebind-tests/.gitignore @@ -0,0 +1,5 @@ +win64/ +mac/ +proj/ +linux/ +windows/ diff --git a/native/tests/sebind-tests/cfg.cmake b/native/tests/sebind-tests/cfg.cmake new file mode 100644 index 0000000000..49f93c4f82 --- /dev/null +++ b/native/tests/sebind-tests/cfg.cmake @@ -0,0 +1,18 @@ +set(CC_USE_GLES3 ON) +set(CC_USE_GLES2 ON) +set(USE_SERVER_MODE OFF) +set(NET_MODE 0) + +set(CC_ENABLE_SWAPPY OFF) +# set(APP_NAME test-cases) +# set(COCOS_X_PATH "I:/Github/editor-3d/resources/3d/engine/native") +set(USE_JOB_SYSTEM_TASKFLOW OFF) +set(USE_JOB_SYSTEM_TBB OFF) +set(ENABLE_ANTIALIAS_FXAA OFF) +set(CC_USE_VULKAN OFF) +set(USE_PHYSICS_PHYSX OFF) +set(USE_AUDIO ON) +set(USE_VIDEO ON) +set(USE_WEBVIEW ON) +set(USE_SPINE ON) +set(USE_DRAGONBONES ON) diff --git a/native/tests/sebind-tests/common/CMakeLists.txt b/native/tests/sebind-tests/common/CMakeLists.txt new file mode 100644 index 0000000000..11806d2307 --- /dev/null +++ b/native/tests/sebind-tests/common/CMakeLists.txt @@ -0,0 +1,51 @@ +enable_language(C ASM) +set(DEVELOPMENT_TEAM "" CACHE STRING "APPLE Developtment Team") +set(RES_DIR "" CACHE STRING "Resource path") +set(COCOS_X_PATH "" CACHE STRING "Path to engine/native/") + +set(TARGET_OSX_VERSION "10.14" CACHE STRING "Target MacOSX version" FORCE) +set(TARGET_IOS_VERSION "10.0" CACHE STRING "Target iOS version" FORCE) + +set(CMAKE_CXX_STANDARD 14) +option(USE_SE_V8 "Use V8 JavaScript Engine" ON) +option(USE_V8_DEBUGGER "Enable Chrome Remote inspector" ON) +option(USE_SOCKET "Enable WebSocket & SocketIO" ON) +option(USE_AUDIO "Enable Audio" ON) #Enable AudioEngine +option(USE_EDIT_BOX "Enable EditBox" ON) +option(USE_SE_JSC "Use JavaScriptCore on MacOSX/iOS" OFF) +option(USE_VIDEO "Enable VideoPlayer Component" ON) +option(USE_WEBVIEW "Enable WebView Component" ON) +option(USE_MIDDLEWARE "Enable Middleware" ON) +option(USE_DRAGONBONES "Enable Dragonbones" ON) +option(USE_SPINE "Enable Spine" ON) +option(USE_WEBSOCKET_SERVER "Enable WebSocket Server" OFF) +option(USE_JOB_SYSTEM_TASKFLOW "Use taskflow as job system backend" OFF) +option(USE_JOB_SYSTEM_TBB "Use tbb as job system backend" OFF) +option(USE_PHYSICS_PHYSX "USE PhysX Physics" ON) + +if(NOT RES_DIR) + message(FATAL_ERROR "RES_DIR is not set!") +endif() + +include(${RES_DIR}/proj/cfg.cmake) + +if(NOT COCOS_X_PATH) + message(FATAL_ERROR "COCOS_X_PATH is not set!") +endif() + +include(${COCOS_X_PATH}/CMakeLists.txt) + +list(APPEND CC_COMMON_SOURCES + ${CMAKE_CURRENT_LIST_DIR}/Classes/Game.h + ${CMAKE_CURRENT_LIST_DIR}/Classes/Game.cpp +) + +## add demo classes & glue code +list(APPEND CC_COMMON_SOURCES + ${CMAKE_CURRENT_LIST_DIR}/Classes/demo/Fruit.h + ${CMAKE_CURRENT_LIST_DIR}/Classes/demo/Fruit.cpp + ${CMAKE_CURRENT_LIST_DIR}/Classes/demo/Coconut.h + ${CMAKE_CURRENT_LIST_DIR}/Classes/demo/Coconut.cpp + ${CMAKE_CURRENT_LIST_DIR}/Classes/demo/sebind_fruits.h + ${CMAKE_CURRENT_LIST_DIR}/Classes/demo/sebind_fruits.cpp +) \ No newline at end of file diff --git a/native/tests/sebind-tests/common/Classes/Game.cpp b/native/tests/sebind-tests/common/Classes/Game.cpp new file mode 100644 index 0000000000..bb539f9864 --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/Game.cpp @@ -0,0 +1,77 @@ +/**************************************************************************** + Copyright (c) 2017-2018 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "Game.h" + +#include "bindings/sebind/sebind.h" + +#ifndef GAME_NAME + #define GAME_NAME "CocosGame"; +#endif + +#ifndef SCRIPT_XXTEAKEY + #define SCRIPT_XXTEAKEY ""; +#endif + +#include "demo/sebind_fruits.h" + +Game::Game() = default; + +int Game::init() { + _windowInfo.title = GAME_NAME; + // configurate window size + // _windowInfo.height = 600; + // _windowInfo.width = 800; + +#if CC_DEBUG + _debuggerInfo.enabled = true; +#else + _debuggerInfo.enabled = false; +#endif + _debuggerInfo.port = 6086; + _debuggerInfo.address = "0.0.0.0"; + _debuggerInfo.pauseOnStart = false; + + _xxteaKey = SCRIPT_XXTEAKEY; + auto *seengine = se::ScriptEngine::getInstance(); + seengine->addRegisterCallback(jsb_register_fruits); + seengine->addAfterCleanupHook([]() { sebind::reset(); }); + + BaseGame::init(); + return 0; +} + +void Game::onPause() { + BaseGame::onPause(); +} + +void Game::onResume() { + BaseGame::onResume(); +} + +void Game::onClose() { + BaseGame::onClose(); +} + +CC_REGISTER_APPLICATION(Game); diff --git a/native/tests/sebind-tests/common/Classes/Game.h b/native/tests/sebind-tests/common/Classes/Game.h new file mode 100644 index 0000000000..6969606dd0 --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/Game.h @@ -0,0 +1,42 @@ +/**************************************************************************** + Copyright (c) 2018 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 engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "cocos/cocos.h" + +/** + @brief The cocos2d Application. + + The reason for implement as private inheritance is to hide some interface call by Director. + */ +class Game : public cc::BaseGame { +public: + Game(); + int init() override; + //bool init() override; + void onPause() override; + void onResume() override; + void onClose() override; +}; diff --git a/native/tests/sebind-tests/common/Classes/demo/Coconut.cpp b/native/tests/sebind-tests/common/Classes/demo/Coconut.cpp new file mode 100644 index 0000000000..e0eec5e764 --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/demo/Coconut.cpp @@ -0,0 +1,19 @@ +#include "Coconut.h" + +namespace demo { + +std::string Coconut::callJSFunction(const std::string &name) { + if (!_jsThis) { + return "jsThis is not set"; + } + se::Value prop; + _jsThis->getProperty(name, &prop); + if (prop.isNullOrUndefined()) { + return "function found!"; + } + se::Value ret; + prop.toObject()->call({}, _jsThis, &prop); + assert(prop.isString()); + return prop.toString(); +} +} // namespace demo diff --git a/native/tests/sebind-tests/common/Classes/demo/Coconut.h b/native/tests/sebind-tests/common/Classes/demo/Coconut.h new file mode 100644 index 0000000000..0d3274bb8b --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/demo/Coconut.h @@ -0,0 +1,39 @@ +#pragma once + +#include "Fruit.h" +#include "bindings/jswrapper/SeApi.h" + +#include + +namespace demo { +class Coconut : public Fruit { +public: + Coconut() = default; + Coconut(se::Object *jsThis) : Fruit("Coconut"), _jsThis(jsThis) {} + Coconut(se::Object *jsThis, const std::string &name, float price) : Fruit(name, price), _jsThis(jsThis) {} + Coconut(float r) : Fruit("Coconut"), _radius(r) {} + + float getRadius() const { return _radius; } + void setRadius(float r) { _radius = r; } + + float growRadius(float x) { _radius += x; } + + void doNothing() const {} + + std::shared_ptr combine(Coconut *other) const { + return std::make_shared(other->_radius + _radius); + } + + std::string callJSFunction(const std::string &name); + + static std::vector OneTwoThree() { + return {1,2,3}; + } + static void IgnoreInput(int ) {} + static void StaticDoNothing() {} + +private: + se::Object *_jsThis{nullptr}; + float _radius{10.0f}; +}; +} // namespace demo diff --git a/native/tests/sebind-tests/common/Classes/demo/Fruit.cpp b/native/tests/sebind-tests/common/Classes/demo/Fruit.cpp new file mode 100644 index 0000000000..ef3b7d1ab5 --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/demo/Fruit.cpp @@ -0,0 +1,18 @@ +#include "Fruit.h" +#include +namespace demo { + +Fruit::Fruit(const std::string& name) : _name(name) {} + +Fruit::Fruit(const std::string &name, int price):_name(name), _price(price) {} + + +std::string Fruit::fullInfo() const { + std::stringstream ss; + ss << "Full information about fruit " << _name << std::endl + << " price: " << _price << std::endl + << " sweetness: " << _sweetness << std::endl; + return ss.str(); +} + +} // namespace demo diff --git a/native/tests/sebind-tests/common/Classes/demo/Fruit.h b/native/tests/sebind-tests/common/Classes/demo/Fruit.h new file mode 100644 index 0000000000..0231e262cd --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/demo/Fruit.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +namespace demo { +class Fruit { +public: + Fruit() = default; + Fruit(const std::string &name); + Fruit(const std::string &name, int price); + + std::string fullInfo() const; + std::string toString() const { return fullInfo(); } + + void setSweetness(int value) { _sweetness = value; } + double getSweetness() const {return _sweetness; }; + + int uid{-1}; + + std::string getName() const { return _name; } + + double getPrice() const {return _price;} + +private: + std::string _name; + int _price{1}; + int _sweetness{0}; +}; +} // namespace demo diff --git a/native/tests/sebind-tests/common/Classes/demo/sebind_fruits.cpp b/native/tests/sebind-tests/common/Classes/demo/sebind_fruits.cpp new file mode 100644 index 0000000000..c27fd9325d --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/demo/sebind_fruits.cpp @@ -0,0 +1,120 @@ +#include "sebind_fruits.h" +#include +#include +#include "bindings/sebind/intl/common.h" +#include "bindings/sebind/sebind.h" +#include "tests/sebind-tests/common/Classes/demo/Coconut.h" +#include "tests/sebind-tests/common/Classes/demo/Fruit.h" + +namespace { +struct Utils {}; + +void doAssert(bool value, const std::string &message) { + if (!value) { + CC_LOG_ERROR("Assert Fail: %s", message.c_str()); + std::cerr << "Assert Failed: " << message << std::endl;; + std::exit(-1); + } +} + +void WriteLog(const std::string &message) { + // std::cout << "[log] " << message << std::endl; + CC_LOG_DEBUG("[log] %s", message.c_str()); +} + +void successQuit(int code) { + if (code == 0) { + FILE *fp = fopen("result.txt", "wt"); + fwrite("ok\n", 3, 1, fp); + fclose(fp); + } + std::exit(code); +} + +int Coconut_time() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); +} + +float Coconut_area(demo::Coconut *d) { + return d->getRadius() * d->getRadius() * 3.14F; +} + +bool Coconut_weight(se::State &s) { + s.rval().setFloat(88.8); + return true; +} + +} // namespace + +bool jsb_register_fruits(se::Object *globalThis) { + se::Object *ns{nullptr}; + { + se::Value demo; + globalThis->getProperty("demo", &demo); + if (!demo.isObject()) { + ns = se::Object::createPlainObject(); + globalThis->setProperty("demo", se::Value(ns)); + } else { + ns = demo.toObject(); + } + } + + sebind::class_ fruitClass("Fruit"); + { + fruitClass.constructor() + .constructor() + .function("fullInfo", &demo::Fruit::fullInfo) + .function("toString", &demo::Fruit::fullInfo) + .property("uid", &demo::Fruit::uid) + .property("name", &demo::Fruit::getName, nullptr) + .property("sweetness", &demo::Fruit::getSweetness, &demo::Fruit::setSweetness) + .property("price", &demo::Fruit::getPrice, nullptr) + .install(ns); + } + sebind::class_ coconutClass("Coconut", fruitClass.prototype()); + { + coconutClass.constructor() + .constructor() + .property("radius", &demo::Coconut::getRadius, nullptr) + .property("radius2", nullptr, &demo::Coconut::setRadius) + .function("combine", &demo::Coconut::combine) + .function("setRadius", &demo::Coconut::setRadius) + .function("getRadius", &demo::Coconut::getRadius) + .function("doNothing", &demo::Coconut::doNothing) + .function("callJsFunction", &demo::Coconut::callJSFunction) + .staticFunction("OneTwoThree", &demo::Coconut::OneTwoThree) + .staticFunction("StaticDoNothing", &demo::Coconut::StaticDoNothing) + .staticProperty("p123_1", &demo::Coconut::OneTwoThree, &demo::Coconut::IgnoreInput) + .staticProperty("p123_2", &demo::Coconut::OneTwoThree, nullptr) + .staticProperty("p123_3", nullptr, &demo::Coconut::IgnoreInput) + .staticProperty("p123", &demo::Coconut::OneTwoThree, nullptr) + .install(ns); + } + + sebind::class_ utilsClass("utils"); + { + utilsClass.staticFunction("assert", &doAssert) + .staticFunction("exit", &successQuit) + .staticFunction("log", &WriteLog) + .install(globalThis); + } + + sebind::class_ coconutExtClass("CoconutExt", fruitClass.prototype()); + { + coconutExtClass.constructor() + .staticProperty("time", &Coconut_time, nullptr) + .staticFunction("getTime", &Coconut_time) + .property("area", &Coconut_area, nullptr) + .function("getArea", &Coconut_area) + .property("weight", &Coconut_weight, &Coconut_weight) + .function("getWeight", &Coconut_weight) + .finalizer([](demo::Coconut*){ + + }) + .install(ns); + } + + return true; +} diff --git a/native/tests/sebind-tests/common/Classes/demo/sebind_fruits.h b/native/tests/sebind-tests/common/Classes/demo/sebind_fruits.h new file mode 100644 index 0000000000..a41e7728ed --- /dev/null +++ b/native/tests/sebind-tests/common/Classes/demo/sebind_fruits.h @@ -0,0 +1,12 @@ +#include "bindings/jswrapper/SeApi.h" +#include "bindings/manual/jsb_conversions.h" +#include "bindings/manual/jsb_global.h" + +#include "Fruit.h" +#include "Coconut.h" + +JSB_REGISTER_OBJECT_TYPE(demo::Fruit); +JSB_REGISTER_OBJECT_TYPE(demo::Coconut); + + +bool jsb_register_fruits(se::Object *); \ No newline at end of file diff --git a/native/tests/sebind-tests/data/jsb-adapter/jsb-builtin.js b/native/tests/sebind-tests/data/jsb-adapter/jsb-builtin.js new file mode 100644 index 0000000000..95197570d7 --- /dev/null +++ b/native/tests/sebind-tests/data/jsb-adapter/jsb-builtin.js @@ -0,0 +1,2 @@ + +console.log("load jsb-builtni.js"); diff --git a/native/tests/sebind-tests/data/main.js b/native/tests/sebind-tests/data/main.js new file mode 100644 index 0000000000..8b498a9474 --- /dev/null +++ b/native/tests/sebind-tests/data/main.js @@ -0,0 +1,119 @@ + +const l = utils.log; + +function assert(value, message) { + if (!value) { + utils.assert(value, message); + } +} + +let blocks = []; +function block(name, fn) { + blocks.push({ name, fn }); +} + +function flush() { + for(let i = 0 ; i < blocks.length; i++) { + l(`:: Run test ${i+1}/${blocks.length}, ${blocks[i].name}`); + blocks[i].fn(); + } +} + + +try { + + let f1 = new demo.Fruit("Banana"); + block("create fruit", () => { + f1 = new demo.Fruit("Banana"); + }); + + block(`fruit name ${f1.name}`, () => { + assert(f1.name === "Banana", "access fruit name attribute"); + }); + + block("call toString & fullInfo", () => { + assert(f1.toString() === f1.fullInfo(), "call full info"); + }); + block("update uid", () => { + f1.uid = 888; + assert(f1.uid === 888, "set and get uid"); + }); + + block("update sweetness", () => { + f1.sweetness = 8989; + assert(f1.sweetness === 8989, "set and get sweetness"); + }); + block("update name", () => { + f1.name = "None"; + assert(f1.name === "Banana", "name should not be modified"); + }); + let f2; + block("other fruit constructor", () => { + f2 = new demo.Fruit("Apple", 100); + assert(f2.name == "Apple", "check fruit name of Apple"); + assert(f2.price == 100, "check price 100"); + }); + + demo.Coconut.prototype.rock = function () { + return "Coconut Rock"; + } + let c = new demo.Coconut(); + block("call js", () => { + assert(c.callJsFunction("rock") == "Coconut Rock", "Call JS function"); + }); + block("call setRadius", () => { + assert(typeof c.setRadius === 'function', "function setRadius"); + }); + block("call getRadius", () => { + assert(typeof c.getRadius === 'function', "function getRadius"); + }); + block("call static 123", () => { + assert(typeof demo.Coconut.OneTwoThree === 'function', "static function OneTwoThree"); + let ret = demo.Coconut.OneTwoThree(); + assert(ret.length === 3, "[1,2,3]"); + }); + block("call inherited function", () => { + assert(typeof c.fullInfo === 'function', "function fullInfo/toString found"); + }); + + + l("create CoconutExt"); + let d = new demo.CoconutExt; + block("check time", () => { + assert(typeof demo.CoconutExt.time === 'number', "attribute time"); + l(`time is ${demo.CoconutExt.time}`) + }); + block("check getTime", () => { + assert(typeof demo.CoconutExt.getTime === 'function', "static time"); + l(`gettime is ${demo.CoconutExt.getTime()}`); + }); + block("check area", () => { + assert(typeof d.area === 'number', "attribute area"); + l(`area is ${d.area}`); + }); + block("check getArea", () => { + assert(typeof d.getArea === 'function', "getArea function"); + l(`get Area is ${d.getArea()}`); + }); + block(`check weight`, () => { + assert(typeof d.weight === 'number', "attribute weight"); + l(`weight is ${d.weight}`); + }); + block("check getWeight", () => { + assert(typeof d.getWeight === 'function', "getWeight function"); + }); + + flush(); + + l("----------done---------------"); + utils.exit(0); + +} catch (e) { + console.log(e); + debugger; + utils.exit(1); +} + +function gameTick(dt) { + // console.log("run game tick"); +} diff --git a/native/tests/sebind-tests/run-windows.sh b/native/tests/sebind-tests/run-windows.sh new file mode 100644 index 0000000000..9593884e18 --- /dev/null +++ b/native/tests/sebind-tests/run-windows.sh @@ -0,0 +1,21 @@ +#!bin/bash +set -x + +cp -r ../../../templates/windows win64 +mkdir -p proj +cp cfg.cmake proj/ +GW="$(realpath `pwd`/../..)" +cmake -B proj -S win64 -DRES_DIR="${GW}/tests/sebind-tests" -DCOCOS_X_PATH="${GW}" \ + -DAPP_NAME=sebind + +cmake --build proj +cd proj/Debug +rm -f result.txt +./sebind.exe || true +if [[ -f "result.txt" ]]; +then +echo "success!" +else +echo "Run sebind-tests fail!" +exit 1 +fi \ No newline at end of file