diff --git a/native/.travis.yml b/native/.travis.yml index 354ff1ba97..9a897a4545 100644 --- a/native/.travis.yml +++ b/native/.travis.yml @@ -6,9 +6,12 @@ script: sudo: required before_install: - tools/travis-scripts/before-install.sh + +# blocklist branches: - only: - - develop + except: + - master + env: global: - secure: bUrk522Qw5Mc3SfDXHZtJ/aF9QbLXYDnUVSOJXt1wUB1d8xAQphTcZ1ARNYu7I5m3ZXqRfzTS4POOT58qeS3sYPpJ8urWW18hgX3I/dmsL1WJXmwnOV+0J3xLt6AT3ttqj7/emaf0xxuBvZ0szyRz0rU4wprtWftWMFiUrsF8G1an2Qa/g/f5LhilnDiKAqFdHMkn0ogaggL0PbgliHeHo7SEOfSF2gQaSIBta7jzE/BEZZ3R4AuReB3oNDwxr+1E4BpPaGO1lMLzdr8MAjWBGVLBRlpVDihgFTTmdka8UYasjEWDs6GbSjJRsTZQkluOo+1UylSiLn5o1tnWMqINo5DDaayBSKWRV/x+Sx+KMG221BwHLGFHrhEm8Jwc3g5IBiFrc9Xn/PAoCL3Zi/m0m8Y/TVIlA2nWuU0jeMZYXOb0ALCplAQMrG/Yt7euzgSjZ9iPvO7HO8BkaRkUxafcp6svWyMedNeDczG6liLSquJak+XIbOpWCOW+KVxc2S2Unz37MSOQR/aB9dJ8fKI/4e3LCdYrSKW9MSKAz9BSYA2IK2F8Fgr6zY3IPTANQCi6o8i/N54wsmpY17uvzqNDGuag5m/FkNpFWVQUy/TdONanXV6m1jvREaxtDHucSnP3olmvx6pi1awRspDfRmcILK08yvul+yLol0nQwenlx0= diff --git a/native/README.md b/native/README.md index d2e149af7f..fe4fe366e2 100644 --- a/native/README.md +++ b/native/README.md @@ -42,26 +42,31 @@ Git user attention 1. Clone the repo from GitHub. - $ git clone https://github.com/cocos-creator/cocos2d-x-lite.git + $ git clone https://github.com/cocos-creator/cocos2d-x-lite.git 2. After cloning the repo, please execute `download-deps.py` to download and install dependencies. - $ cd cocos2d-x-lite - $ python download-deps.py + $ cd cocos2d-x-lite + $ python download-deps.py 3. After running `download-deps.py`. - $ git submodule update --init + $ git submodule update --init 4. Build simulator - $ npm install - $ gulp gen-simulator - $ gulp update-simulator-config + $ npm install + $ gulp sign-simulator + $ gulp gen-simulator + $ gulp update-simulator-config + + `gulp sign-simulator` only need to run on Mac. It can help you to sign the simulator project in "tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj", so you can debug the simulator on Mac. This command will open the XCode project in the background. Then you should set the signing manually, and close XCode to make it finished. If you don't want to sign it, just close XCode directly. You need to rerun this command once the project is changed. + ![](https://user-images.githubusercontent.com/1503156/32046986-3ab1f0b6-ba0a-11e7-9c7f-7fe0a385d338.png) + 5. Build prebuilt library - $ gulp gen-libs + $ gulp gen-libs Contributing to the Project -------------------------------- diff --git a/native/cocos/2d/CCLabel.cpp b/native/cocos/2d/CCLabel.cpp index cb24a8183e..823e19b835 100644 --- a/native/cocos/2d/CCLabel.cpp +++ b/native/cocos/2d/CCLabel.cpp @@ -1672,13 +1672,18 @@ void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) { return; } - // Don't do calculate the culling if the transform was not updated - bool transformUpdated = flags & FLAGS_TRANSFORM_DIRTY; -#if CC_USE_CULLING - _insideBounds = transformUpdated ? renderer->checkVisibility(transform, _contentSize) : _insideBounds; + + if (_director->isCullingEnabled()) { + // Don't calculate the culling if the transform was not updated + if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) { + _insideBounds = renderer->checkVisibility(transform, _contentSize); + } + } + else { + _insideBounds = true; + } if (_insideBounds) -#endif { if (!_shadowEnabled && (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP)) { @@ -1696,7 +1701,7 @@ void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) else { _customCommand.init(_globalZOrder, transform, flags); - _customCommand.func = CC_CALLBACK_0(Label::onDraw, this, transform, transformUpdated); + _customCommand.func = CC_CALLBACK_0(Label::onDraw, this, transform, flags & FLAGS_TRANSFORM_DIRTY); renderer->addCommand(&_customCommand); } @@ -1735,8 +1740,7 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare // IMPORTANT: // To ease the migration to v3.0, we still support the Mat4 stack, // but it is deprecated and your code should not rely on it - _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); - _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform); + _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform); if (!_children.empty()) { diff --git a/native/cocos/2d/CCMenuItem.cpp b/native/cocos/2d/CCMenuItem.cpp index efce0b1e53..95b2f70027 100644 --- a/native/cocos/2d/CCMenuItem.cpp +++ b/native/cocos/2d/CCMenuItem.cpp @@ -406,7 +406,11 @@ void MenuItemSprite::setNormalImage(Node* image) } _normalImage = image; - this->setContentSize(_normalImage->getContentSize()); + if (_normalImage) + { + this->setContentSize(_normalImage->getContentSize()); + } + this->updateImagesVisibility(); } } diff --git a/native/cocos/2d/CCNode.cpp b/native/cocos/2d/CCNode.cpp index a4814f8271..b252cad3f5 100644 --- a/native/cocos/2d/CCNode.cpp +++ b/native/cocos/2d/CCNode.cpp @@ -82,6 +82,7 @@ Node::Node() , _additionalTransform(nullptr) , _additionalTransformDirty(false) , _transformUpdated(true) +, _cullingDirty(true) // children (lazy allocs) // lazy alloc , _localZOrderAndArrival(0) @@ -1216,6 +1217,7 @@ uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFl uint32_t flags = parentFlags; flags |= (_transformUpdated ? FLAGS_TRANSFORM_DIRTY : 0); flags |= (_contentSizeDirty ? FLAGS_CONTENT_SIZE_DIRTY : 0); + flags |= (_cullingDirty ? FLAGS_CULLING_DIRTY : 0); if(flags & FLAGS_DIRTY_MASK) @@ -1223,6 +1225,7 @@ uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFl _transformUpdated = false; _contentSizeDirty = false; + _cullingDirty = false; return flags; } @@ -1249,8 +1252,7 @@ void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t paren // IMPORTANT: // To ease the migration to v3.0, we still support the Mat4 stack, // but it is deprecated and your code should not rely on it - _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); - _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform); + _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform); auto camera = creator::CameraNode::getInstance(); if (camera) { @@ -2147,9 +2149,9 @@ void Node::setCameraMask(unsigned short mask, bool applyChildren) } } -void Node::markTransformUpdated() +void Node::markCullingDirty() { - _transformUpdated = true; + _cullingDirty = true; } NS_CC_END diff --git a/native/cocos/2d/CCNode.h b/native/cocos/2d/CCNode.h index 2b4373d5a1..c396000608 100644 --- a/native/cocos/2d/CCNode.h +++ b/native/cocos/2d/CCNode.h @@ -109,6 +109,7 @@ public: FLAGS_TRANSFORM_DIRTY = (1 << 0), FLAGS_CONTENT_SIZE_DIRTY = (1 << 1), FLAGS_RENDER_AS_3D = (1 << 3), + FLAGS_CULLING_DIRTY = (1 << 4), FLAGS_DIRTY_MASK = (FLAGS_TRANSFORM_DIRTY | FLAGS_CONTENT_SIZE_DIRTY), }; @@ -1775,9 +1776,9 @@ public: virtual void setCameraMask(unsigned short mask, bool applyChildren = true); /** - * Mark transformUpdated as true, this will make flags contains FLAGS_TRANSFORM_DIRTY flag. + * Mark cullingDirty as true, this will make flags contains FLAGS_CULLING_DIRTY flag. */ - void markTransformUpdated(); + void markCullingDirty(); CC_CONSTRUCTOR_ACCESS: // Nodes should be created using create(); @@ -1929,7 +1930,8 @@ protected: mutable bool _additionalTransformDirty; ///< transform dirty ? bool _transformUpdated; ///< Whether or not the Transform object was updated since the last frame - char padding[7]; + bool _cullingDirty; ///< Whether culling is dirty + private: CC_DISALLOW_COPY_AND_ASSIGN(Node); }; diff --git a/native/cocos/2d/CCRenderTexture.cpp b/native/cocos/2d/CCRenderTexture.cpp index 212da76fd5..6f823ce2a4 100644 --- a/native/cocos/2d/CCRenderTexture.cpp +++ b/native/cocos/2d/CCRenderTexture.cpp @@ -744,6 +744,12 @@ void RenderTexture::draw(Renderer *renderer, const Mat4 &transform, uint32_t fla } } +void RenderTexture::cleanup() +{ + Node::cleanup(); + _saveFileCallback = nullptr; +} + void RenderTexture::begin() { Director* director = Director::getInstance(); diff --git a/native/cocos/2d/CCRenderTexture.h b/native/cocos/2d/CCRenderTexture.h index 9a3776e079..b507e0e7c0 100644 --- a/native/cocos/2d/CCRenderTexture.h +++ b/native/cocos/2d/CCRenderTexture.h @@ -262,6 +262,7 @@ public: // Overrides virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override; virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override; + virtual void cleanup() override; /** Flag: Use stack matrix computed from scene hierarchy or generate new modelView and projection matrix. * diff --git a/native/cocos/2d/CCSprite.cpp b/native/cocos/2d/CCSprite.cpp index b407d34f20..0e729d94fb 100644 --- a/native/cocos/2d/CCSprite.cpp +++ b/native/cocos/2d/CCSprite.cpp @@ -645,11 +645,16 @@ void Sprite::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) return; } -#if CC_USE_CULLING - // Don't calculate the culling if the transform was not updated - _insideBounds = (flags & FLAGS_TRANSFORM_DIRTY) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds; + if (_director->isCullingEnabled()) { + if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) { + _insideBounds = renderer->checkVisibility(transform, _contentSize); + } + } + else { + _insideBounds = true; + } + if(_insideBounds) -#endif { _trianglesCommand.init(_globalZOrder, _texture, diff --git a/native/cocos/Android.mk b/native/cocos/Android.mk index fb760c398e..96e33ae36c 100644 --- a/native/cocos/Android.mk +++ b/native/cocos/Android.mk @@ -2,7 +2,9 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := cocos2dx_internal_static +# cis is short name for cocos2dx_internal_static +# Shorter name could avoid compilation errors on Windows system which has a limitation of 260 bytes for build path. +LOCAL_MODULE := cis LOCAL_MODULE_FILENAME := libcocos2dxinternal LOCAL_ARM_MODE := arm @@ -283,7 +285,7 @@ LOCAL_STATIC_LIBRARIES += cocos_ui_static LOCAL_STATIC_LIBRARIES += spine_static LOCAL_STATIC_LIBRARIES += dragonbones_static LOCAL_STATIC_LIBRARIES += creator_static -LOCAL_STATIC_LIBRARIES += cocos2dx_internal_static +LOCAL_STATIC_LIBRARIES += cis include $(BUILD_STATIC_LIBRARY) diff --git a/native/cocos/base/CCDirector.cpp b/native/cocos/base/CCDirector.cpp index ee6b325e4b..e3cca89539 100644 --- a/native/cocos/base/CCDirector.cpp +++ b/native/cocos/base/CCDirector.cpp @@ -91,6 +91,44 @@ const char *Director::EVENT_BEFORE_UPDATE = "director_before_update"; const char *Director::EVENT_AFTER_UPDATE = "director_after_update"; const char *Director::EVENT_RESET = "director_reset"; + +Director::MatrixStack::MatrixStack() +{ +} + +void Director::MatrixStack::init() { + _stack.clear(); + _stack.reserve(16); + + _stack.push_back(Mat4::IDENTITY); + _stackTop = 0; +} + +void Director::MatrixStack::push(const Mat4& m) { + if (_stackTop >= _stack.size() - 1) { + _stack.push_back(m); + } + else { + _stack[_stackTop + 1] = m; + } + ++_stackTop; +} + +void Director::MatrixStack::pop() { + if (_stackTop > 0) { + --_stackTop; + } +} + +Mat4& Director::MatrixStack::top() { + return _stack[_stackTop]; +} + +const Mat4& Director::MatrixStack::top() const { + return _stack[_stackTop]; +} + + Director* Director::getInstance() { if (!s_SharedDirector) @@ -105,7 +143,8 @@ Director* Director::getInstance() Director::Director() : _isStatusLabelUpdated(true), -_invalid(true) +_invalid(true), +_isCullingEnabled(true) { } @@ -430,24 +469,9 @@ void Director::setNextDeltaTimeZero(bool nextDeltaTimeZero) // void Director::initMatrixStack() { - while (!_modelViewMatrixStack.empty()) - { - _modelViewMatrixStack.pop(); - } - - while (!_projectionMatrixStack.empty()) - { - _projectionMatrixStack.pop(); - } - - while (!_textureMatrixStack.empty()) - { - _textureMatrixStack.pop(); - } - - _modelViewMatrixStack.push(Mat4::IDENTITY); - _projectionMatrixStack.push(Mat4::IDENTITY); - _textureMatrixStack.push(Mat4::IDENTITY); + _modelViewMatrixStack.init(); + _projectionMatrixStack.init(); + _textureMatrixStack.init(); } void Director::resetMatrixStack() @@ -539,15 +563,35 @@ void Director::pushMatrix(MATRIX_STACK_TYPE type) { if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW) { - _modelViewMatrixStack.push(_modelViewMatrixStack.top()); + pushMatrix(type, _modelViewMatrixStack.top()); } else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION) { - _projectionMatrixStack.push(_projectionMatrixStack.top()); + pushMatrix(type, _projectionMatrixStack.top()); } else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE) { - _textureMatrixStack.push(_textureMatrixStack.top()); + pushMatrix(type, _textureMatrixStack.top()); + } + else + { + CCASSERT(false, "unknown matrix stack type"); + } +} + +void Director::pushMatrix(MATRIX_STACK_TYPE type, const Mat4& mat) +{ + if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW) + { + _modelViewMatrixStack.push(mat); + } + else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION) + { + _projectionMatrixStack.push(mat); + } + else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE) + { + _textureMatrixStack.push(mat); } else { diff --git a/native/cocos/base/CCDirector.h b/native/cocos/base/CCDirector.h index 330347a4f4..ca884930db 100644 --- a/native/cocos/base/CCDirector.h +++ b/native/cocos/base/CCDirector.h @@ -81,6 +81,7 @@ enum class MATRIX_STACK_TYPE MATRIX_STACK_TEXTURE }; + /** @brief Class that creates and handles the main Window and manages how and when to execute the Scenes. @@ -452,6 +453,11 @@ public: * @js NA */ void pushMatrix(MATRIX_STACK_TYPE type); + /** + * Put a specified type matrix to the top of specified type of matrix stack. + * @js NA + */ + void pushMatrix(MATRIX_STACK_TYPE type, const Mat4& mat); /** Pops the top matrix of the specified type of matrix stack. * @js NA */ @@ -499,6 +505,9 @@ public: bool isPurgeDirectorInNextLoop() const { return _purgeDirectorInNextLoop; } bool isValid() const { return !_invalid; } + + void setCullingEnabled (bool enable) { _isCullingEnabled = enable; } + bool isCullingEnabled () const { return _isCullingEnabled; } protected: void reset(); @@ -524,10 +533,7 @@ protected: void destroyTextureCache(); void initMatrixStack(); - - std::stack _modelViewMatrixStack; - std::stack _projectionMatrixStack; - std::stack _textureMatrixStack; + /** Scheduler associated with this director @since v2.0 @@ -623,6 +629,31 @@ protected: // GLView will recreate stats labels to fit visible rect friend class GLView; + + bool _isCullingEnabled; + +private: + /** + Use std::vector to implement a quick matrix stack. + */ + class MatrixStack + { + public: + MatrixStack(); + void init(); + void pop(); + void push(const Mat4& m); + Mat4& top(); + const Mat4& top() const; + protected: + std::vector _stack; + int _stackTop; + }; + + + MatrixStack _modelViewMatrixStack; + MatrixStack _projectionMatrixStack; + MatrixStack _textureMatrixStack; }; // end of base group diff --git a/native/cocos/base/CCEventDispatcher.cpp b/native/cocos/base/CCEventDispatcher.cpp index c1f304d718..d458928f20 100644 --- a/native/cocos/base/CCEventDispatcher.cpp +++ b/native/cocos/base/CCEventDispatcher.cpp @@ -690,7 +690,10 @@ void EventDispatcher::removeEventListener(EventListener* listener) if (isFound) { - releaseListener(listener); + if (_inDispatch > 0) + CC_SAFE_RELEASE(listener); + else + releaseListener(listener); } else { diff --git a/native/cocos/base/CCUserDefault-apple.mm b/native/cocos/base/CCUserDefault-apple.mm index 109f389e1c..132629c179 100644 --- a/native/cocos/base/CCUserDefault-apple.mm +++ b/native/cocos/base/CCUserDefault-apple.mm @@ -405,6 +405,8 @@ Data UserDefault::getDataForKey(const char* pKey, const Data& defaultValue) // delete xmle node deleteNode(doc, node); } + } else { + delete doc; } #endif diff --git a/native/cocos/base/ccConfig.h b/native/cocos/base/ccConfig.h index 81bf3c98b2..1887886523 100644 --- a/native/cocos/base/ccConfig.h +++ b/native/cocos/base/ccConfig.h @@ -278,11 +278,6 @@ THE SOFTWARE. #define CC_LUA_ENGINE_DEBUG 0 #endif -/** Use culling or not. */ -#ifndef CC_USE_CULLING -#define CC_USE_CULLING 1 -#endif - /** Support PNG or not. If your application don't use png format picture, you can undefine this macro to save package size. */ #ifndef CC_USE_PNG diff --git a/native/cocos/editor-support/creator/Android.mk b/native/cocos/editor-support/creator/Android.mk index afdd0a4183..dd3f045050 100644 --- a/native/cocos/editor-support/creator/Android.mk +++ b/native/cocos/editor-support/creator/Android.mk @@ -26,6 +26,4 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. \ $(LOCAL_PATH)/../.. \ $(LOCAL_PATH)/../../../external/sources -# LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static - include $(BUILD_STATIC_LIBRARY) diff --git a/native/cocos/editor-support/creator/CCCameraNode.cpp b/native/cocos/editor-support/creator/CCCameraNode.cpp index cb1bb648da..5d72ab620e 100644 --- a/native/cocos/editor-support/creator/CCCameraNode.cpp +++ b/native/cocos/editor-support/creator/CCCameraNode.cpp @@ -19,7 +19,6 @@ namespace creator { CameraNode::CameraNode() { _mat.setIdentity(); - _cameraInstance = this; visitingIndex = 0; } @@ -34,7 +33,16 @@ namespace creator { } _commands.clear(); } - _cameraInstance = nullptr; + } + + void CameraNode::setEnable(bool enable) + { + if (enable) { + _cameraInstance = this; + } + else { + _cameraInstance = nullptr; + } } CameraNode* CameraNode::getInstance() { diff --git a/native/cocos/editor-support/creator/CCCameraNode.h b/native/cocos/editor-support/creator/CCCameraNode.h index 19b4d296b4..9b8b74ae8b 100644 --- a/native/cocos/editor-support/creator/CCCameraNode.h +++ b/native/cocos/editor-support/creator/CCCameraNode.h @@ -47,6 +47,8 @@ namespace creator { static CameraNode* getInstance(); + void setEnable(bool enable); + void setTransform(float a, float b, float c, float d, float tx, float ty); bool containsNode(cocos2d::Node* node); diff --git a/native/cocos/editor-support/creator/CCScale9Sprite.cpp b/native/cocos/editor-support/creator/CCScale9Sprite.cpp index 4e49cd96ee..b533230cc8 100755 --- a/native/cocos/editor-support/creator/CCScale9Sprite.cpp +++ b/native/cocos/editor-support/creator/CCScale9Sprite.cpp @@ -1102,11 +1102,18 @@ void Scale9SpriteV2::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &tran if (!this->_spriteFrame || !this->_spriteFrame->getTexture()) { return; } -#if CC_USE_CULLING - // Don't calculate the culling if the transform was not updated - _insideBounds = (flags & FLAGS_TRANSFORM_DIRTY) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds; + + if (_director->isCullingEnabled()) { + // Don't calculate the culling if the transform was not updated + if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) { + _insideBounds = renderer->checkVisibility(transform, _contentSize); + } + } + else { + _insideBounds = true; + } + if (_insideBounds) -#endif { if (this->_quadsDirty) { //rebuild quads diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp b/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp index f7ac776445..adfa819531 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp @@ -168,16 +168,18 @@ bool DBCCSprite::_checkVisibility(const cocos2d::Mat4& transform, const cocos2d: void DBCCSprite::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) { -#if CC_USE_CULLING - const auto& rect = this->_polyInfo.rect; - - if ((flags & FLAGS_TRANSFORM_DIRTY)) - { - _insideBounds = _checkVisibility(transform, _contentSize, rect); + if (_director->isCullingEnabled()) { + // Don't calculate the culling if the transform was not updated + if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) + { + _insideBounds = _checkVisibility(transform, _contentSize, this->_polyInfo.rect); + } + } + else { + _insideBounds = true; } if (_insideBounds) -#endif { _trianglesCommand.init(_globalZOrder, _texture->getName(), getGLProgramState(), _blendFunc, _polyInfo.triangles, transform, flags); renderer->addCommand(&_trianglesCommand); diff --git a/native/cocos/editor-support/dragonbones/proj.android/Android.mk b/native/cocos/editor-support/dragonbones/proj.android/Android.mk index ce355afed5..15be361d8f 100644 --- a/native/cocos/editor-support/dragonbones/proj.android/Android.mk +++ b/native/cocos/editor-support/dragonbones/proj.android/Android.mk @@ -39,8 +39,6 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../.. \ $(LOCAL_PATH)/../../.. \ $(LOCAL_PATH)/../../../../external/sources -# LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static - LOCAL_CFLAGS += -Wno-psabi LOCAL_EXPORT_CFLAGS += -Wno-psabi diff --git a/native/cocos/network/Android.mk b/native/cocos/network/Android.mk index 85690ed065..509b95d414 100644 --- a/native/cocos/network/Android.mk +++ b/native/cocos/network/Android.mk @@ -22,7 +22,6 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../external/websockets/include/android \ $(LOCAL_PATH)/.. \ $(LOCAL_PATH)/../../external/sources -# LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static LOCAL_STATIC_LIBRARIES += libwebsockets_static LOCAL_STATIC_LIBRARIES += cocos_ssl_static LOCAL_STATIC_LIBRARIES += cocos_crypto_static diff --git a/native/cocos/network/CCDownloader-apple.mm b/native/cocos/network/CCDownloader-apple.mm index 8d67db6d96..13d9348797 100644 --- a/native/cocos/network/CCDownloader-apple.mm +++ b/native/cocos/network/CCDownloader-apple.mm @@ -338,6 +338,7 @@ namespace cocos2d { namespace network { { DLLOG("Destruct DownloaderAppleImpl %p", self); self.downloadSession = nil; + self.taskDict = nil; [super dealloc]; } #pragma mark - NSURLSessionTaskDelegate methods diff --git a/native/cocos/network/SocketIO.cpp b/native/cocos/network/SocketIO.cpp index b47459a1b1..f7318106f6 100644 --- a/native/cocos/network/SocketIO.cpp +++ b/native/cocos/network/SocketIO.cpp @@ -813,7 +813,9 @@ void SIOClientImpl::onMessage(WebSocket* /*ws*/, const WebSocket::Data& data) case 0: CCLOGINFO("Received Disconnect Signal for Endpoint: %s\n", endpoint.c_str()); disconnectFromEndpoint(endpoint); - c->fireEvent("disconnect", payload); + if (c) { + c->fireEvent("disconnect", payload); + } break; case 1: CCLOGINFO("Connected to endpoint: %s \n", endpoint.c_str()); diff --git a/native/cocos/platform/android/java/libs/libcocosanalytics.jar b/native/cocos/platform/android/java/libs/libcocosanalytics.jar index a772eb89ed..29e665f8f5 100644 Binary files a/native/cocos/platform/android/java/libs/libcocosanalytics.jar and b/native/cocos/platform/android/java/libs/libcocosanalytics.jar differ diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/CAAgentWrapper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/CAAgentWrapper.java new file mode 100644 index 0000000000..11a8f48a7d --- /dev/null +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/CAAgentWrapper.java @@ -0,0 +1,65 @@ +/**************************************************************************** + * Copyright (c) 2017 Chukong Technologies Inc. + * + * http://www.cocos2d-x.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + ****************************************************************************/ + +package org.cocos2dx.lib; + +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.util.Log; + +import com.cocos.analytics.CAAgent; + +public class CAAgentWrapper { + + private static final String TAG = "CAAgentWrapper"; + + public static void init(String channelID, String appID, String appSecret) { + CAAgent.init(Cocos2dxActivity.getContext(), channelID, appID, appSecret); + } + + public static String getChannelID() { + try { + ApplicationInfo applicationInfo = Cocos2dxActivity.getContext().getPackageManager() + .getApplicationInfo(Cocos2dxActivity.getContext().getPackageName(), + PackageManager.GET_META_DATA); + if (applicationInfo != null) { + if (applicationInfo.metaData != null) { + if (applicationInfo.metaData.containsKey("ASC_ChannelID")) + { + String channelID = applicationInfo.metaData.get("ASC_ChannelID") + ""; + if (channelID.startsWith("A")) { + channelID = channelID.substring(1); + } + return channelID; + } + } + } + + } catch (Exception e) { + Log.e(TAG,"Could not get channel ID", e); + } + + return ""; + } +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index 44242722a2..175bae89f0 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -45,6 +45,8 @@ import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; +import com.cocos.analytics.CAAgent; + import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener; import javax.microedition.khronos.egl.EGL10; @@ -272,6 +274,8 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe this.hideVirtualButton(); + CAAgent.enableDebug(false); + onLoadNativeLibraries(); sContext = this; @@ -348,6 +352,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe @Override protected void onDestroy() { Cocos2dxAudioFocusManager.unregisterAudioFocusListener(this); + CAAgent.onDestroy(); super.onDestroy(); } diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java index 60deb7e2ab..4385eaf085 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -35,6 +35,7 @@ import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; +import com.cocos.analytics.CAAgent; public class Cocos2dxGLSurfaceView extends GLSurfaceView { // =========================================================== @@ -178,6 +179,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume(); + CAAgent.onResume(Cocos2dxGLSurfaceView.this.getContext()); } }); } @@ -188,6 +190,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause(); + CAAgent.onPause(Cocos2dxGLSurfaceView.this.getContext()); } }); this.setRenderMode(RENDERMODE_WHEN_DIRTY); diff --git a/native/cocos/platform/android/libcocos2dx/build.gradle b/native/cocos/platform/android/libcocos2dx/build.gradle index d2dcf1314a..cb1d217962 100644 --- a/native/cocos/platform/android/libcocos2dx/build.gradle +++ b/native/cocos/platform/android/libcocos2dx/build.gradle @@ -2,7 +2,7 @@ apply plugin: 'com.android.library' android { compileSdkVersion 22 - buildToolsVersion '25.0.0' + buildToolsVersion '26.0.2' defaultConfig { minSdkVersion 10 diff --git a/native/cocos/renderer/CCRenderer.cpp b/native/cocos/renderer/CCRenderer.cpp index ff46f8d281..2e6f6b03e7 100644 --- a/native/cocos/renderer/CCRenderer.cpp +++ b/native/cocos/renderer/CCRenderer.cpp @@ -792,9 +792,32 @@ bool Renderer::checkVisibility(const Mat4& transform, const Size& size) visibleRect = camera->getVisibleRect(); } - Rect rect(0,0, size.width, size.height); - rect = RectApplyTransform(rect, transform); - return rect.intersectsRect(visibleRect); + // half size of the screen + Size screen_half = visibleRect.size; + screen_half.width /= 2; + screen_half.height /= 2; + + float hSizeX = size.width / 2; + float hSizeY = size.height / 2; + + Vec4 v4world, v4local; + v4local.set(hSizeX, hSizeY, 0, 1); + transform.transformVector(v4local, &v4world); + + // center of screen is (0,0) + v4world.x = v4world.x - screen_half.width - visibleRect.origin.x; + v4world.y = v4world.y - screen_half.height - visibleRect.origin.y; + + // convert content size to world coordinates + float wshw = std::max(fabsf(hSizeX * transform.m[0] + hSizeY * transform.m[4]), fabsf(hSizeX * transform.m[0] - hSizeY * transform.m[4])); + float wshh = std::max(fabsf(hSizeX * transform.m[1] + hSizeY * transform.m[5]), fabsf(hSizeX * transform.m[1] - hSizeY * transform.m[5])); + + // compare if it in the positive quadrant of the screen + float tmpx = (fabsf(v4world.x) - wshw); + float tmpy = (fabsf(v4world.y) - wshh); + bool ret = (tmpx < screen_half.width && tmpy < screen_half.height); + + return ret; } void Renderer::setClearColor(const Color4F &clearColor) diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index 0934551641..bf915006d1 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -2,7 +2,7 @@ Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -158,8 +158,8 @@ void TextureCache::addImageAsync(const std::string &path, const std::function ul(_requestMutex); _requestQueue.push_back(data); - _requestMutex.unlock(); - _sleepCondition.notify_one(); } @@ -213,13 +211,11 @@ void TextureCache::unbindAllImageAsync() void TextureCache::loadImage() { AsyncStruct *asyncStruct = nullptr; - std::mutex signalMutex; - std::unique_lock signal(signalMutex); while (!_needQuit) { + std::unique_lock ul(_requestMutex); // pop an AsyncStruct from request queue - _requestMutex.lock(); - if(_requestQueue.empty()) + if (_requestQueue.empty()) { asyncStruct = nullptr; } @@ -228,12 +224,15 @@ void TextureCache::loadImage() asyncStruct = _requestQueue.front(); _requestQueue.pop_front(); } - _requestMutex.unlock(); if (nullptr == asyncStruct) { - _sleepCondition.wait(signal); + if (_needQuit) { + break; + } + _sleepCondition.wait(ul); continue; } + ul.unlock(); // load image asyncStruct->loadSuccess = asyncStruct->image->initWithImageFile(asyncStruct->filename); @@ -582,8 +581,10 @@ std::string TextureCache::getTextureFilePath( cocos2d::Texture2D *texture )const void TextureCache::waitForQuit() { // notify sub thread to quick + std::unique_lock ul(_requestMutex); _needQuit = true; _sleepCondition.notify_one(); + ul.unlock(); if (_loadingThread) _loadingThread->join(); // Clear async tasks which are still in the queue. diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index 290fadb8dc..c6b47601ff 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -118,6 +118,16 @@ getAlphaTextureName : function ( return 0; }, +/** + * @method getName + * @return {unsigned int} + */ +getName : function ( +) +{ + return 0; +}, + /** * @method initWithString * @param {String|String} str @@ -811,14 +821,6 @@ getChildren : function( return new Array(); }, -/** - * @method markTransformUpdated - */ -markTransformUpdated : function ( -) -{ -}, - /** * @method pause */ @@ -2014,6 +2016,14 @@ isCascadeColorEnabled : function ( return false; }, +/** + * @method markCullingDirty + */ +markCullingDirty : function ( +) +{ +}, + /** * @method stopAction * @param {cc.Action} arg0 @@ -2529,6 +2539,16 @@ getDeltaTime : function ( return 0; }, +/** + * @method isCullingEnabled + * @return {bool} + */ +isCullingEnabled : function ( +) +{ + return false; +}, + /** * @method setGLDefaultValues */ @@ -2577,6 +2597,16 @@ mat4 { }, +/** + * @method setCullingEnabled + * @param {bool} arg0 + */ +setCullingEnabled : function ( +bool +) +{ +}, + /** * @method getNotificationNode * @return {cc.Node} @@ -2695,10 +2725,12 @@ vec2 /** * @method pushMatrix - * @param {cc.MATRIX_STACK_TYPE} arg0 - */ -pushMatrix : function ( -matrix_stack_type +* @param {cc.MATRIX_STACK_TYPE|cc.MATRIX_STACK_TYPE} matrix_stack_type +* @param {mat4_object} mat4 +*/ +pushMatrix : function( +matrix_stack_type, +mat4 ) { }, @@ -13731,6 +13763,24 @@ begin : function ( { }, +/** + * @method saveToFile +* @param {String|String} str +* @param {cc.Image::Format|bool} format +* @param {bool|function} bool +* @param {function} func +* @return {bool|bool} +*/ +saveToFile : function( +str, +format, +bool, +func +) +{ + return false; +}, + /** * @method setAutoDraw * @param {bool} arg0 @@ -13970,12 +14020,28 @@ str }, /** - * @method setUniformLocationWith1f - * @param {int} arg0 - * @param {float} arg1 + * @method getProgram + * @return {unsigned int} */ -setUniformLocationWith1f : function ( -int, +getProgram : function ( +) +{ + return 0; +}, + +/** + * @method setUniformLocationWith2f +* @param {int|int|int|int} int +* @param {float|float|float|float} float +* @param {float|float|float} float +* @param {float|float} float +* @param {float} float +*/ +setUniformLocationWith2f : function( +int, +float, +float, +float, float ) { @@ -13997,22 +14063,6 @@ str return false; }, -/** - * @method setUniformLocationWith3f - * @param {int} arg0 - * @param {float} arg1 - * @param {float} arg2 - * @param {float} arg3 - */ -setUniformLocationWith3f : function ( -int, -float, -float, -float -) -{ -}, - /** * @method setUniformsForBuiltins * @param {mat4_object} mat4 @@ -14023,40 +14073,6 @@ mat4 { }, -/** - * @method setUniformLocationWith3i - * @param {int} arg0 - * @param {int} arg1 - * @param {int} arg2 - * @param {int} arg3 - */ -setUniformLocationWith3i : function ( -int, -int, -int, -int -) -{ -}, - -/** - * @method setUniformLocationWith4f - * @param {int} arg0 - * @param {float} arg1 - * @param {float} arg2 - * @param {float} arg3 - * @param {float} arg4 - */ -setUniformLocationWith4f : function ( -int, -float, -float, -float, -float -) -{ -}, - /** * @method updateUniforms */ @@ -14065,18 +14081,6 @@ updateUniforms : function ( { }, -/** - * @method getUniformLocation - * @param {String} arg0 - * @return {int} - */ -getUniformLocation : function ( -str -) -{ - return 0; -}, - /** * @method link * @return {bool} @@ -14095,6 +14099,16 @@ reset : function ( { }, +/** + * @method getProgramLog + * @return {String} + */ +getProgramLog : function ( +) +{ + return ; +}, + /** * @method getAttribLocation * @param {String} arg0 @@ -14108,58 +14122,30 @@ str }, /** - * @method setUniformLocationWith2f - * @param {int} arg0 - * @param {float} arg1 - * @param {float} arg2 + * @method getUniformLocation + * @param {String} arg0 + * @return {int} */ -setUniformLocationWith2f : function ( -int, -float, -float -) -{ -}, - -/** - * @method setUniformLocationWith4i - * @param {int} arg0 - * @param {int} arg1 - * @param {int} arg2 - * @param {int} arg3 - * @param {int} arg4 - */ -setUniformLocationWith4i : function ( -int, -int, -int, -int, -int -) -{ -}, - -/** - * @method setUniformLocationWith1i - * @param {int} arg0 - * @param {int} arg1 - */ -setUniformLocationWith1i : function ( -int, -int +getUniformLocation : function ( +str ) { + return 0; }, /** * @method setUniformLocationWith2i - * @param {int} arg0 - * @param {int} arg1 - * @param {int} arg2 - */ -setUniformLocationWith2i : function ( -int, -int, +* @param {int|int|int|int} int +* @param {int|int|int|int} int +* @param {int|int|int} int +* @param {int|int} int +* @param {int} int +*/ +setUniformLocationWith2i : function( +int, +int, +int, +int, int ) { diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_creator_camera_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_creator_camera_auto_api.js index 520daf783c..64261bca29 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_creator_camera_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_creator_camera_auto_api.js @@ -48,6 +48,16 @@ getVisibleRect : function ( return cc.Rect; }, +/** + * @method setEnable + * @param {bool} arg0 + */ +setEnable : function ( +bool +) +{ +}, + /** * @method containsNode * @param {cc.Node} arg0 diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index c502b744eb..d2f9ac81d3 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -351,6 +351,24 @@ static bool js_cocos2dx_Texture2D_getAlphaTextureName(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Texture2D_getAlphaTextureName) +static bool js_cocos2dx_Texture2D_getName(se::State& s) +{ + cocos2d::Texture2D* cobj = (cocos2d::Texture2D*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Texture2D_getName : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + unsigned int result = cobj->getName(); + ok &= uint32_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Texture2D_getName : Error processing arguments"); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Texture2D_getName) + static bool js_cocos2dx_Texture2D_initWithString(se::State& s) { CC_UNUSED bool ok = true; @@ -862,6 +880,7 @@ bool js_register_cocos2dx_Texture2D(se::Object* obj) cls->defineFunction("hasPremultipliedAlpha", _SE(js_cocos2dx_Texture2D_hasPremultipliedAlpha)); cls->defineFunction("getPixelsHigh", _SE(js_cocos2dx_Texture2D_getPixelsHigh)); cls->defineFunction("getAlphaTextureName", _SE(js_cocos2dx_Texture2D_getAlphaTextureName)); + cls->defineFunction("getName", _SE(js_cocos2dx_Texture2D_getName)); cls->defineFunction("initWithString", _SE(js_cocos2dx_Texture2D_initWithString)); cls->defineFunction("setMaxT", _SE(js_cocos2dx_Texture2D_setMaxT)); cls->defineFunction("getPath", _SE(js_cocos2dx_Texture2D_getPath)); @@ -1993,21 +2012,6 @@ static bool js_cocos2dx_Node_getChildren(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Node_getChildren) -static bool js_cocos2dx_Node_markTransformUpdated(se::State& s) -{ - cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_Node_markTransformUpdated : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->markTransformUpdated(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_cocos2dx_Node_markTransformUpdated) - static bool js_cocos2dx_Node_pause(se::State& s) { cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject(); @@ -4417,6 +4421,21 @@ static bool js_cocos2dx_Node_isCascadeColorEnabled(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Node_isCascadeColorEnabled) +static bool js_cocos2dx_Node_markCullingDirty(se::State& s) +{ + cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Node_markCullingDirty : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->markCullingDirty(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Node_markCullingDirty) + static bool js_cocos2dx_Node_stopAction(se::State& s) { cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject(); @@ -4529,7 +4548,6 @@ bool js_register_cocos2dx_Node(se::Object* obj) cls->defineFunction("setOpacityModifyRGB", _SE(js_cocos2dx_Node_setOpacityModifyRGB)); cls->defineFunction("setCascadeOpacityEnabled", _SE(js_cocos2dx_Node_setCascadeOpacityEnabled)); cls->defineFunction("getChildren", _SE(js_cocos2dx_Node_getChildren)); - cls->defineFunction("markTransformUpdated", _SE(js_cocos2dx_Node_markTransformUpdated)); cls->defineFunction("pause", _SE(js_cocos2dx_Node_pause)); cls->defineFunction("convertToWorldSpaceAR", _SE(js_cocos2dx_Node_convertToWorldSpaceAR)); cls->defineFunction("isIgnoreAnchorPointForPosition", _SE(js_cocos2dx_Node_isIgnoreAnchorPointForPosition)); @@ -4645,6 +4663,7 @@ bool js_register_cocos2dx_Node(se::Object* obj) cls->defineFunction("convertToNodeSpace", _SE(js_cocos2dx_Node_convertToNodeSpace)); cls->defineFunction("setTag", _SE(js_cocos2dx_Node_setTag)); cls->defineFunction("isCascadeColorEnabled", _SE(js_cocos2dx_Node_isCascadeColorEnabled)); + cls->defineFunction("markCullingDirty", _SE(js_cocos2dx_Node_markCullingDirty)); cls->defineFunction("stopAction", _SE(js_cocos2dx_Node_stopAction)); cls->defineFunction("getActionManager", _SE(js_cocos2dx_Node_getActionManager)); cls->defineFunction("ctor", _SE(js_cocos2dx_Node_ctor)); @@ -5579,6 +5598,24 @@ static bool js_cocos2dx_Director_getDeltaTime(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Director_getDeltaTime) +static bool js_cocos2dx_Director_isCullingEnabled(se::State& s) +{ + cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Director_isCullingEnabled : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + bool result = cobj->isCullingEnabled(); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Director_isCullingEnabled : Error processing arguments"); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Director_isCullingEnabled) + static bool js_cocos2dx_Director_setGLDefaultValues(se::State& s) { cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject(); @@ -5668,6 +5705,25 @@ static bool js_cocos2dx_Director_loadMatrix(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Director_loadMatrix) +static bool js_cocos2dx_Director_setCullingEnabled(se::State& s) +{ + cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Director_setCullingEnabled : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + bool arg0; + ok &= seval_to_boolean(args[0], &arg0); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Director_setCullingEnabled : Error processing arguments"); + cobj->setCullingEnabled(arg0); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Director_setCullingEnabled) + static bool js_cocos2dx_Director_getNotificationNode(se::State& s) { cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject(); @@ -5881,19 +5937,35 @@ SE_BIND_FUNC(js_cocos2dx_Director_convertToUI) static bool js_cocos2dx_Director_pushMatrix(se::State& s) { + CC_UNUSED bool ok = true; cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_Director_pushMatrix : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_cocos2dx_Director_pushMatrix : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - cocos2d::MATRIX_STACK_TYPE arg0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - SE_PRECONDITION2(ok, false, "js_cocos2dx_Director_pushMatrix : Error processing arguments"); - cobj->pushMatrix(arg0); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + do { + if (argc == 2) { + cocos2d::MATRIX_STACK_TYPE arg0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + cocos2d::Mat4 arg1; + ok &= seval_to_Mat4(args[1], &arg1); + if (!ok) { ok = true; break; } + cobj->pushMatrix(arg0, arg1); + return true; + } + } while(false); + + do { + if (argc == 1) { + cocos2d::MATRIX_STACK_TYPE arg0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + cobj->pushMatrix(arg0); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } SE_BIND_FUNC(js_cocos2dx_Director_pushMatrix) @@ -6646,11 +6718,13 @@ bool js_register_cocos2dx_Director(se::Object* obj) cls->defineFunction("getContentScaleFactor", _SE(js_cocos2dx_Director_getContentScaleFactor)); cls->defineFunction("getWinSizeInPixels", _SE(js_cocos2dx_Director_getWinSizeInPixels)); cls->defineFunction("getDeltaTime", _SE(js_cocos2dx_Director_getDeltaTime)); + cls->defineFunction("isCullingEnabled", _SE(js_cocos2dx_Director_isCullingEnabled)); cls->defineFunction("setGLDefaultValues", _SE(js_cocos2dx_Director_setGLDefaultValues)); cls->defineFunction("setActionManager", _SE(js_cocos2dx_Director_setActionManager)); cls->defineFunction("setAlphaBlending", _SE(js_cocos2dx_Director_setAlphaBlending)); cls->defineFunction("popToRootScene", _SE(js_cocos2dx_Director_popToRootScene)); cls->defineFunction("loadMatrix", _SE(js_cocos2dx_Director_loadMatrix)); + cls->defineFunction("setCullingEnabled", _SE(js_cocos2dx_Director_setCullingEnabled)); cls->defineFunction("getNotificationNode", _SE(js_cocos2dx_Director_getNotificationNode)); cls->defineFunction("getWinSize", _SE(js_cocos2dx_Director_getWinSize)); cls->defineFunction("end", _SE(js_cocos2dx_Director_end)); @@ -31205,6 +31279,173 @@ static bool js_cocos2dx_RenderTexture_begin(se::State& s) } SE_BIND_FUNC(js_cocos2dx_RenderTexture_begin) +static bool js_cocos2dx_RenderTexture_saveToFile(se::State& s) +{ + CC_UNUSED bool ok = true; + cocos2d::RenderTexture* cobj = (cocos2d::RenderTexture*)s.nativeThisObject(); + SE_PRECONDITION2( cobj, false, "js_cocos2dx_RenderTexture_saveToFile : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + do { + if (argc == 2) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + if (!ok) { ok = true; break; } + cocos2d::Image::Format arg1; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + bool result = cobj->saveToFile(arg0, arg1); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments"); + return true; + } + } while(false); + + do { + if (argc == 3) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + if (!ok) { ok = true; break; } + cocos2d::Image::Format arg1; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + bool arg2; + ok &= seval_to_boolean(args[2], &arg2); + bool result = cobj->saveToFile(arg0, arg1, arg2); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments"); + return true; + } + } while(false); + + do { + if (argc == 4) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + if (!ok) { ok = true; break; } + cocos2d::Image::Format arg1; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + bool arg2; + ok &= seval_to_boolean(args[2], &arg2); + std::function &)> arg3; + do { + if (args[3].isObject() && args[3].toObject()->isFunction()) + { + se::Value jsThis(s.thisObject()); + se::Value jsFunc(args[3]); + jsThis.toObject()->attachObject(jsFunc.toObject()); + auto lambda = [=](cocos2d::RenderTexture* larg0, const std::basic_string & larg1) -> void { + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + CC_UNUSED bool ok = true; + se::ValueArray args; + args.resize(2); + ok &= native_ptr_to_seval((cocos2d::RenderTexture*)larg0, &args[0]); + ok &= std_string_to_seval(larg1, &args[1]); + se::Value rval; + se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; + se::Object* funcObj = jsFunc.toObject(); + bool succeed = funcObj->call(args, thisObj, &rval); + if (!succeed) { + se::ScriptEngine::getInstance()->clearException(); + } + }; + arg3 = lambda; + } + else + { + arg3 = nullptr; + } + } while(false) + ; + if (!ok) { ok = true; break; } + bool result = cobj->saveToFile(arg0, arg1, arg2, arg3); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments"); + return true; + } + } while(false); + + do { + if (argc == 1) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + if (!ok) { ok = true; break; } + bool result = cobj->saveToFile(arg0); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments"); + return true; + } + } while(false); + + do { + if (argc == 2) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + if (!ok) { ok = true; break; } + bool arg1; + ok &= seval_to_boolean(args[1], &arg1); + bool result = cobj->saveToFile(arg0, arg1); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments"); + return true; + } + } while(false); + + do { + if (argc == 3) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + if (!ok) { ok = true; break; } + bool arg1; + ok &= seval_to_boolean(args[1], &arg1); + std::function &)> arg2; + do { + if (args[2].isObject() && args[2].toObject()->isFunction()) + { + se::Value jsThis(s.thisObject()); + se::Value jsFunc(args[2]); + jsThis.toObject()->attachObject(jsFunc.toObject()); + auto lambda = [=](cocos2d::RenderTexture* larg0, const std::basic_string & larg1) -> void { + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + CC_UNUSED bool ok = true; + se::ValueArray args; + args.resize(2); + ok &= native_ptr_to_seval((cocos2d::RenderTexture*)larg0, &args[0]); + ok &= std_string_to_seval(larg1, &args[1]); + se::Value rval; + se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; + se::Object* funcObj = jsFunc.toObject(); + bool succeed = funcObj->call(args, thisObj, &rval); + if (!succeed) { + se::ScriptEngine::getInstance()->clearException(); + } + }; + arg2 = lambda; + } + else + { + arg2 = nullptr; + } + } while(false) + ; + if (!ok) { ok = true; break; } + bool result = cobj->saveToFile(arg0, arg1, arg2); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments"); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} +SE_BIND_FUNC(js_cocos2dx_RenderTexture_saveToFile) + static bool js_cocos2dx_RenderTexture_setAutoDraw(se::State& s) { cocos2d::RenderTexture* cobj = (cocos2d::RenderTexture*)s.nativeThisObject(); @@ -31610,6 +31851,7 @@ bool js_register_cocos2dx_RenderTexture(se::Object* obj) cls->defineFunction("setKeepMatrix", _SE(js_cocos2dx_RenderTexture_setKeepMatrix)); cls->defineFunction("setClearFlags", _SE(js_cocos2dx_RenderTexture_setClearFlags)); cls->defineFunction("begin", _SE(js_cocos2dx_RenderTexture_begin)); + cls->defineFunction("saveToFile", _SE(js_cocos2dx_RenderTexture_saveToFile)); cls->defineFunction("setAutoDraw", _SE(js_cocos2dx_RenderTexture_setAutoDraw)); cls->defineFunction("setClearColor", _SE(js_cocos2dx_RenderTexture_setClearColor)); cls->defineFunction("beginWithClear", _SE(js_cocos2dx_RenderTexture_beginWithClear)); @@ -31796,26 +32038,105 @@ static bool js_cocos2dx_GLProgram_initWithByteArrays(se::State& s) } SE_BIND_FUNC(js_cocos2dx_GLProgram_initWithByteArrays) -static bool js_cocos2dx_GLProgram_setUniformLocationWith1f(se::State& s) +static bool js_cocos2dx_GLProgram_getProgram(se::State& s) { cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith1f : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getProgram : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 2) { - int arg0 = 0; - float arg1 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_float(args[1], &arg1); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith1f : Error processing arguments"); - cobj->setUniformLocationWith1f(arg0, arg1); + if (argc == 0) { + unsigned int result = cobj->getProgram(); + ok &= uint32_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getProgram : Error processing arguments"); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1f) +SE_BIND_FUNC(js_cocos2dx_GLProgram_getProgram) + +static bool js_cocos2dx_GLProgram_setUniformLocationWith2f(se::State& s) +{ + CC_UNUSED bool ok = true; + cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); + SE_PRECONDITION2( cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2f : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + do { + if (argc == 3) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + float arg1 = 0; + ok &= seval_to_float(args[1], &arg1); + if (!ok) { ok = true; break; } + float arg2 = 0; + ok &= seval_to_float(args[2], &arg2); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith2f(arg0, arg1, arg2); + return true; + } + } while(false); + + do { + if (argc == 2) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + float arg1 = 0; + ok &= seval_to_float(args[1], &arg1); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith1f(arg0, arg1); + return true; + } + } while(false); + + do { + if (argc == 4) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + float arg1 = 0; + ok &= seval_to_float(args[1], &arg1); + if (!ok) { ok = true; break; } + float arg2 = 0; + ok &= seval_to_float(args[2], &arg2); + if (!ok) { ok = true; break; } + float arg3 = 0; + ok &= seval_to_float(args[3], &arg3); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith3f(arg0, arg1, arg2, arg3); + return true; + } + } while(false); + + do { + if (argc == 5) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + float arg1 = 0; + ok &= seval_to_float(args[1], &arg1); + if (!ok) { ok = true; break; } + float arg2 = 0; + ok &= seval_to_float(args[2], &arg2); + if (!ok) { ok = true; break; } + float arg3 = 0; + ok &= seval_to_float(args[3], &arg3); + if (!ok) { ok = true; break; } + float arg4 = 0; + ok &= seval_to_float(args[4], &arg4); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith4f(arg0, arg1, arg2, arg3, arg4); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} +SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f) static bool js_cocos2dx_GLProgram_initWithFilenames(se::State& s) { @@ -31862,31 +32183,6 @@ static bool js_cocos2dx_GLProgram_initWithFilenames(se::State& s) } SE_BIND_FUNC(js_cocos2dx_GLProgram_initWithFilenames) -static bool js_cocos2dx_GLProgram_setUniformLocationWith3f(se::State& s) -{ - cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith3f : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 4) { - int arg0 = 0; - float arg1 = 0; - float arg2 = 0; - float arg3 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_float(args[1], &arg1); - ok &= seval_to_float(args[2], &arg2); - ok &= seval_to_float(args[3], &arg3); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith3f : Error processing arguments"); - cobj->setUniformLocationWith3f(arg0, arg1, arg2, arg3); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4); - return false; -} -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3f) - static bool js_cocos2dx_GLProgram_setUniformsForBuiltins(se::State& s) { CC_UNUSED bool ok = true; @@ -31916,58 +32212,6 @@ static bool js_cocos2dx_GLProgram_setUniformsForBuiltins(se::State& s) } SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformsForBuiltins) -static bool js_cocos2dx_GLProgram_setUniformLocationWith3i(se::State& s) -{ - cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith3i : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 4) { - int arg0 = 0; - int arg1 = 0; - int arg2 = 0; - int arg3 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_int32(args[1], (int32_t*)&arg1); - ok &= seval_to_int32(args[2], (int32_t*)&arg2); - ok &= seval_to_int32(args[3], (int32_t*)&arg3); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith3i : Error processing arguments"); - cobj->setUniformLocationWith3i(arg0, arg1, arg2, arg3); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4); - return false; -} -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3i) - -static bool js_cocos2dx_GLProgram_setUniformLocationWith4f(se::State& s) -{ - cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith4f : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 5) { - int arg0 = 0; - float arg1 = 0; - float arg2 = 0; - float arg3 = 0; - float arg4 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_float(args[1], &arg1); - ok &= seval_to_float(args[2], &arg2); - ok &= seval_to_float(args[3], &arg3); - ok &= seval_to_float(args[4], &arg4); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith4f : Error processing arguments"); - cobj->setUniformLocationWith4f(arg0, arg1, arg2, arg3, arg4); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 5); - return false; -} -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4f) - static bool js_cocos2dx_GLProgram_updateUniforms(se::State& s) { cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); @@ -31983,27 +32227,6 @@ static bool js_cocos2dx_GLProgram_updateUniforms(se::State& s) } SE_BIND_FUNC(js_cocos2dx_GLProgram_updateUniforms) -static bool js_cocos2dx_GLProgram_getUniformLocation(se::State& s) -{ - cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getUniformLocation : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - std::string arg0; - ok &= seval_to_std_string(args[0], &arg0); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments"); - int result = cobj->getUniformLocation(arg0); - ok &= int32_to_seval(result, &s.rval()); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments"); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_cocos2dx_GLProgram_getUniformLocation) - static bool js_cocos2dx_GLProgram_link(se::State& s) { cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); @@ -32037,6 +32260,24 @@ static bool js_cocos2dx_GLProgram_reset(se::State& s) } SE_BIND_FUNC(js_cocos2dx_GLProgram_reset) +static bool js_cocos2dx_GLProgram_getProgramLog(se::State& s) +{ + cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getProgramLog : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + std::string result = cobj->getProgramLog(); + ok &= std_string_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getProgramLog : Error processing arguments"); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_GLProgram_getProgramLog) + static bool js_cocos2dx_GLProgram_getAttribLocation(se::State& s) { cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); @@ -32058,96 +32299,105 @@ static bool js_cocos2dx_GLProgram_getAttribLocation(se::State& s) } SE_BIND_FUNC(js_cocos2dx_GLProgram_getAttribLocation) -static bool js_cocos2dx_GLProgram_setUniformLocationWith2f(se::State& s) +static bool js_cocos2dx_GLProgram_getUniformLocation(se::State& s) { cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2f : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getUniformLocation : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 3) { - int arg0 = 0; - float arg1 = 0; - float arg2 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_float(args[1], &arg1); - ok &= seval_to_float(args[2], &arg2); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith2f : Error processing arguments"); - cobj->setUniformLocationWith2f(arg0, arg1, arg2); + if (argc == 1) { + std::string arg0; + ok &= seval_to_std_string(args[0], &arg0); + SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments"); + int result = cobj->getUniformLocation(arg0); + ok &= int32_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments"); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f) - -static bool js_cocos2dx_GLProgram_setUniformLocationWith4i(se::State& s) -{ - cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith4i : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 5) { - int arg0 = 0; - int arg1 = 0; - int arg2 = 0; - int arg3 = 0; - int arg4 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_int32(args[1], (int32_t*)&arg1); - ok &= seval_to_int32(args[2], (int32_t*)&arg2); - ok &= seval_to_int32(args[3], (int32_t*)&arg3); - ok &= seval_to_int32(args[4], (int32_t*)&arg4); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith4i : Error processing arguments"); - cobj->setUniformLocationWith4i(arg0, arg1, arg2, arg3, arg4); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 5); - return false; -} -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4i) - -static bool js_cocos2dx_GLProgram_setUniformLocationWith1i(se::State& s) -{ - cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith1i : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 2) { - int arg0 = 0; - int arg1 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_int32(args[1], (int32_t*)&arg1); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith1i : Error processing arguments"); - cobj->setUniformLocationWith1i(arg0, arg1); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; -} -SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1i) +SE_BIND_FUNC(js_cocos2dx_GLProgram_getUniformLocation) static bool js_cocos2dx_GLProgram_setUniformLocationWith2i(se::State& s) { + CC_UNUSED bool ok = true; cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2i : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2i : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 3) { - int arg0 = 0; - int arg1 = 0; - int arg2 = 0; - ok &= seval_to_int32(args[0], (int32_t*)&arg0); - ok &= seval_to_int32(args[1], (int32_t*)&arg1); - ok &= seval_to_int32(args[2], (int32_t*)&arg2); - SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith2i : Error processing arguments"); - cobj->setUniformLocationWith2i(arg0, arg1, arg2); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); + do { + if (argc == 3) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + int arg1 = 0; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + int arg2 = 0; + ok &= seval_to_int32(args[2], (int32_t*)&arg2); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith2i(arg0, arg1, arg2); + return true; + } + } while(false); + + do { + if (argc == 2) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + int arg1 = 0; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith1i(arg0, arg1); + return true; + } + } while(false); + + do { + if (argc == 4) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + int arg1 = 0; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + int arg2 = 0; + ok &= seval_to_int32(args[2], (int32_t*)&arg2); + if (!ok) { ok = true; break; } + int arg3 = 0; + ok &= seval_to_int32(args[3], (int32_t*)&arg3); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith3i(arg0, arg1, arg2, arg3); + return true; + } + } while(false); + + do { + if (argc == 5) { + int arg0 = 0; + ok &= seval_to_int32(args[0], (int32_t*)&arg0); + if (!ok) { ok = true; break; } + int arg1 = 0; + ok &= seval_to_int32(args[1], (int32_t*)&arg1); + if (!ok) { ok = true; break; } + int arg2 = 0; + ok &= seval_to_int32(args[2], (int32_t*)&arg2); + if (!ok) { ok = true; break; } + int arg3 = 0; + ok &= seval_to_int32(args[3], (int32_t*)&arg3); + if (!ok) { ok = true; break; } + int arg4 = 0; + ok &= seval_to_int32(args[4], (int32_t*)&arg4); + if (!ok) { ok = true; break; } + cobj->setUniformLocationWith4i(arg0, arg1, arg2, arg3, arg4); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2i) @@ -32279,21 +32529,17 @@ bool js_register_cocos2dx_GLProgram(se::Object* obj) cls->defineFunction("getVertexShaderLog", _SE(js_cocos2dx_GLProgram_getVertexShaderLog)); cls->defineFunction("getUniform", _SE(js_cocos2dx_GLProgram_getUniform)); cls->defineFunction("initWithString", _SE(js_cocos2dx_GLProgram_initWithByteArrays)); - cls->defineFunction("setUniformLocationWith1f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith1f)); + cls->defineFunction("getProgram", _SE(js_cocos2dx_GLProgram_getProgram)); + cls->defineFunction("setUniformLocationF32", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2f)); cls->defineFunction("init", _SE(js_cocos2dx_GLProgram_initWithFilenames)); - cls->defineFunction("setUniformLocationWith3f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith3f)); cls->defineFunction("setUniformsForBuiltins", _SE(js_cocos2dx_GLProgram_setUniformsForBuiltins)); - cls->defineFunction("setUniformLocationWith3i", _SE(js_cocos2dx_GLProgram_setUniformLocationWith3i)); - cls->defineFunction("setUniformLocationWith4f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith4f)); cls->defineFunction("updateUniforms", _SE(js_cocos2dx_GLProgram_updateUniforms)); - cls->defineFunction("getUniformLocation", _SE(js_cocos2dx_GLProgram_getUniformLocation)); cls->defineFunction("link", _SE(js_cocos2dx_GLProgram_link)); cls->defineFunction("reset", _SE(js_cocos2dx_GLProgram_reset)); + cls->defineFunction("getProgramLog", _SE(js_cocos2dx_GLProgram_getProgramLog)); cls->defineFunction("getAttribLocation", _SE(js_cocos2dx_GLProgram_getAttribLocation)); - cls->defineFunction("setUniformLocationWith2f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2f)); - cls->defineFunction("setUniformLocationWith4i", _SE(js_cocos2dx_GLProgram_setUniformLocationWith4i)); - cls->defineFunction("setUniformLocationI32", _SE(js_cocos2dx_GLProgram_setUniformLocationWith1i)); - cls->defineFunction("setUniformLocationWith2i", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2i)); + cls->defineFunction("getUniformLocation", _SE(js_cocos2dx_GLProgram_getUniformLocation)); + cls->defineFunction("setUniformLocationI32", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2i)); cls->defineFunction("ctor", _SE(js_cocos2dx_GLProgram_ctor)); cls->defineStaticFunction("createWithByteArrays", _SE(js_cocos2dx_GLProgram_createWithByteArrays)); cls->defineStaticFunction("createWithFilenames", _SE(js_cocos2dx_GLProgram_createWithFilenames)); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp index 9fe17ba40f..ccf02982fa 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -24,6 +24,7 @@ SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getMaxS); SE_DECLARE_FUNC(js_cocos2dx_Texture2D_hasPremultipliedAlpha); SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getPixelsHigh); SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getAlphaTextureName); +SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getName); SE_DECLARE_FUNC(js_cocos2dx_Texture2D_initWithString); SE_DECLARE_FUNC(js_cocos2dx_Texture2D_setMaxT); SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getPath); @@ -123,7 +124,6 @@ SE_DECLARE_FUNC(js_cocos2dx_Node_getDescription); SE_DECLARE_FUNC(js_cocos2dx_Node_setOpacityModifyRGB); SE_DECLARE_FUNC(js_cocos2dx_Node_setCascadeOpacityEnabled); SE_DECLARE_FUNC(js_cocos2dx_Node_getChildren); -SE_DECLARE_FUNC(js_cocos2dx_Node_markTransformUpdated); SE_DECLARE_FUNC(js_cocos2dx_Node_pause); SE_DECLARE_FUNC(js_cocos2dx_Node_convertToWorldSpaceAR); SE_DECLARE_FUNC(js_cocos2dx_Node_isIgnoreAnchorPointForPosition); @@ -239,6 +239,7 @@ SE_DECLARE_FUNC(js_cocos2dx_Node_getParentToNodeTransform); SE_DECLARE_FUNC(js_cocos2dx_Node_convertToNodeSpace); SE_DECLARE_FUNC(js_cocos2dx_Node_setTag); SE_DECLARE_FUNC(js_cocos2dx_Node_isCascadeColorEnabled); +SE_DECLARE_FUNC(js_cocos2dx_Node_markCullingDirty); SE_DECLARE_FUNC(js_cocos2dx_Node_stopAction); SE_DECLARE_FUNC(js_cocos2dx_Node_getActionManager); SE_DECLARE_FUNC(js_cocos2dx_Node_create); @@ -304,11 +305,13 @@ SE_DECLARE_FUNC(js_cocos2dx_Director_setContentScaleFactor); SE_DECLARE_FUNC(js_cocos2dx_Director_getContentScaleFactor); SE_DECLARE_FUNC(js_cocos2dx_Director_getWinSizeInPixels); SE_DECLARE_FUNC(js_cocos2dx_Director_getDeltaTime); +SE_DECLARE_FUNC(js_cocos2dx_Director_isCullingEnabled); SE_DECLARE_FUNC(js_cocos2dx_Director_setGLDefaultValues); SE_DECLARE_FUNC(js_cocos2dx_Director_setActionManager); SE_DECLARE_FUNC(js_cocos2dx_Director_setAlphaBlending); SE_DECLARE_FUNC(js_cocos2dx_Director_popToRootScene); SE_DECLARE_FUNC(js_cocos2dx_Director_loadMatrix); +SE_DECLARE_FUNC(js_cocos2dx_Director_setCullingEnabled); SE_DECLARE_FUNC(js_cocos2dx_Director_getNotificationNode); SE_DECLARE_FUNC(js_cocos2dx_Director_getWinSize); SE_DECLARE_FUNC(js_cocos2dx_Director_end); @@ -2076,6 +2079,7 @@ SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_isAutoDraw); SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setKeepMatrix); SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setClearFlags); SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_begin); +SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_saveToFile); SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setAutoDraw); SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setClearColor); SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_beginWithClear); @@ -2101,20 +2105,16 @@ SE_DECLARE_FUNC(js_cocos2dx_GLProgram_use); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getVertexShaderLog); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getUniform); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_initWithByteArrays); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1f); +SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getProgram); +SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_initWithFilenames); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3f); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformsForBuiltins); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3i); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4f); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_updateUniforms); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getUniformLocation); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_link); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_reset); +SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getProgramLog); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getAttribLocation); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4i); -SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1i); +SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getUniformLocation); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2i); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_createWithByteArrays); SE_DECLARE_FUNC(js_cocos2dx_GLProgram_createWithFilenames); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.cpp index 6ca22619a8..ef5448b3be 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.cpp @@ -72,6 +72,25 @@ static bool js_creator_camera_CameraNode_getVisibleRect(se::State& s) } SE_BIND_FUNC(js_creator_camera_CameraNode_getVisibleRect) +static bool js_creator_camera_CameraNode_setEnable(se::State& s) +{ + creator::CameraNode* cobj = (creator::CameraNode*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_creator_camera_CameraNode_setEnable : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + bool arg0; + ok &= seval_to_boolean(args[0], &arg0); + SE_PRECONDITION2(ok, false, "js_creator_camera_CameraNode_setEnable : Error processing arguments"); + cobj->setEnable(arg0); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_creator_camera_CameraNode_setEnable) + static bool js_creator_camera_CameraNode_containsNode(se::State& s) { creator::CameraNode* cobj = (creator::CameraNode*)s.nativeThisObject(); @@ -163,6 +182,7 @@ bool js_register_creator_camera_CameraNode(se::Object* obj) cls->defineFunction("removeTarget", _SE(js_creator_camera_CameraNode_removeTarget)); cls->defineFunction("setTransform", _SE(js_creator_camera_CameraNode_setTransform)); cls->defineFunction("getVisibleRect", _SE(js_creator_camera_CameraNode_getVisibleRect)); + cls->defineFunction("setEnable", _SE(js_creator_camera_CameraNode_setEnable)); cls->defineFunction("containsNode", _SE(js_creator_camera_CameraNode_containsNode)); cls->defineFunction("addTarget", _SE(js_creator_camera_CameraNode_addTarget)); cls->defineStaticFunction("getInstance", _SE(js_creator_camera_CameraNode_getInstance)); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.hpp index 1238fd73ef..ce9488aebe 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_creator_camera_auto.hpp @@ -11,6 +11,7 @@ bool register_all_creator_camera(se::Object* obj); SE_DECLARE_FUNC(js_creator_camera_CameraNode_removeTarget); SE_DECLARE_FUNC(js_creator_camera_CameraNode_setTransform); SE_DECLARE_FUNC(js_creator_camera_CameraNode_getVisibleRect); +SE_DECLARE_FUNC(js_creator_camera_CameraNode_setEnable); SE_DECLARE_FUNC(js_creator_camera_CameraNode_containsNode); SE_DECLARE_FUNC(js_creator_camera_CameraNode_addTarget); SE_DECLARE_FUNC(js_creator_camera_CameraNode_getInstance); diff --git a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md new file mode 100644 index 0000000000..1d9db8658a --- /dev/null +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md @@ -0,0 +1,1202 @@ +# The Tutorial for JSB 2.0 + +## The Abstraction Layer of Script Engine + +### Architecture + +![](JSB2.0-Architecture.png) + +### Macro + +The abstraction layer is bound to take more CPU execution time than using the JS engine API directly. How to minimize the overhead of the abstraction layer becomes the first goal of the design. + +Most of work in JS binding is actually setting JS related operations with CPP callbacks and associating CPP object within the callback function. In fact, it mainly contains the following two situation: + +* Register JS functions (including global functions, class constructors, class destructors, class member functions, and class static member functions), binding revevant CPP callbacks + +* Register accessors for JS properties, bind CPP callbacks for reading and writing properties respectively + +How to achieve the minimum overhead for the abstract layer and expose the unified API? + +For example, to register a JS function in CPP, there are different definitions in JavaScriptCore, SpiderMonkey, V8, ChakraCore as follows: + +**JavaScriptCore:** + +```c++ +JSValueRef JSB_foo_func( + JSContextRef _cx, + JSObjectRef _function, + JSObjectRef _thisObject, + size_t argc, + const JSValueRef _argv[], + JSValueRef* _exception + ); +``` + +**SpiderMonkey:** + +```c++ +bool JSB_foo_func( + JSContext* _cx, + unsigned argc, + JS::Value* _vp + ); +``` + +**V8:** + +```c++ +void JSB_foo_func( + const v8::FunctionCallbackInfo& v8args + ); +``` + +**ChakraCore:** + +```c++ +JsValueRef JSB_foo_func( + JsValueRef _callee, + bool _isConstructCall, + JsValueRef* _argv, + unsigned short argc, + void* _callbackState + ); +``` + +We evaluated several options and eventually decided to use `macros` to reduce the differences between the definition and parameter types of different JS engine callbacks, regardless of which engine is used, and developers could use an unified callback definition. We refer to the definition of Lua callback function. The definition of all JS to CPP callback functions in the abstract layer is defined as: + +```c++ +bool foo(se::State& s) +{ + ... + ... +} +SE_BIND_FUNC(foo) // Binding a JS function as an example +``` + +After a developer has bound a JS function, remember to wrap the callback function with the macros which start with `SE_BIND_`. Currently, we provide the following macros: + +* SE\_BIND\_PROP_GET: Wrap a JS object property read callback function +* SE\_BIND\_PROP_SET: Wrap a JS object property written callback function +* SE\_BIND\_FUNC: Wrap a JS function that can be used for global functions, class member functions or class static functions +* SE\_DECLARE\_FUNC: Declare a JS function, generally used in the header file +* SE\_BIND\_CTOR: Wrap a JS constructor +* SE\_BIND\_SUB\_CLS\_CTOR: Wrap the constructor of a JS subclass by using cc.Class.extend. +* SE\_FINALIZE\_FUNC: Wrap the finalize function of a JS object, finalize function is invoked when the object is released by Garbage Collector +* SE\_DECLARE\_FINALIZE\_FUNC: Declares the finalize function of a JS object +* _SE: The macro for making callback be recognized by different JS engine. Note that the first character is underscored, similar to `_T ('xxx')` in Windows for wrapping Unicode or MultiBytes string + +## API + +### CPP Namespace + +All types of the abstraction layer are under the `se` namespace, which is an abbreviation of `ScriptEngine`. + +### Types + +#### se::ScriptEngine + +`se::ScriptEngine` is the JS engine administrator, responsible for JS engine initialization, destruction, restart, native module registration, loading scripts, doing garbage collection, JS exception cleanup and whether to enable the debugger. +It is a singleton that could be accessed via `se::ScriptEngine::getInstance()`. + +#### se::Value + +`se::Value` can be understood as a JS variable reference in the CPP layer. There are six types of JS variables: `object`,` number`, `string`,` boolean`, `null`,` undefined`, so `se::Value` uses an `union` to include ` object`, `number`,` string `,` boolean` these 4 kinds of `value types`, `non-value types` like `null` and `undefined` can be represented by `_type` directly. + +```c++ +namespace se { + class Value { + enum class Type : char + { + Undefined = 0, + Null, + Number, + Boolean, + String, + Object + }; + ... + ... + private: + union { + bool _boolean; + double _number; + std::string* _string; + Object* _object; + } _u; + + Type _type; + ... + ... + }; +} +``` + +If a `se::Value` stores the underlying data types, such as `number`,` string`, `boolean`, which is directly stored by `value copy`. +The storage of `object` is special because it is a `weak reference` to JS objects via `se::Object*`. + +#### se::Object + +`se::Object` extends from `se::RefCounter` which is a class for reference count management. Currently, only `se::Object` inherits from `se::RefCounter` in the abstraction layer. +As we mentioned in the last section, `se::Object` is a weak reference to the JS object, therefore I will explain why it's a weak reference. + +* Reason 1: The requirement of controlling the life cycle of CPP objects by JS objects + +After creating a Sprite in the script layer via `var sp = new cc.Sprite("a.png");`, we create a `se::Object` in the constructor callback and leave it in a global map (NativePtrToObjectMap), this map is used to query the `cocos2d::Sprite*` to get the corresponding JS object `se::Object*`. + +```c++ +static bool js_cocos2d_Sprite_finalize(se::State& s) +{ + CCLOG("jsbindings: finalizing JS object %p (cocos2d::Sprite)", s.nativeThisObject()); + cocos2d::Sprite* cobj = (cocos2d::Sprite*)s.nativeThisObject(); + if (cobj->getReferenceCount() == 1) + cobj->autorelease(); + else + cobj->release(); + return true; +} +SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize) + +static bool js_cocos2dx_Sprite_constructor(se::State& s) +{ + cocos2d::Sprite* cobj = new (std::nothrow) cocos2d::Sprite(); // cobj will be released in the finalize callback + s.thisObject()->setPrivateData(cobj); // setPrivateData will make a mapping between se::Object* and cobj + return true; +} +SE_BIND_CTOR(js_cocos2dx_Sprite_constructor, __jsb_cocos2d_Sprite_class, js_cocos2d_Sprite_finalize) +``` + +Imagine if you force `se::Object` to be a strong reference to a JS object that leaves JS objects out of GC control and the finalize callback will never be fired because `se::Object` is always present in map which will cause memory leak. + +It is precisely because the `se::Object` holds a weak reference to a JS object so that controlling the life of the CPP object by JS object can be achieved. In the above code, when the JS object is released, it will trigger the finalize callback, developers only need to release the corresponding CPP object in `js_cocos2d_Sprite_finalize`, the release of `se::Object` has been included in the` SE_BIND_FINALIZE_FUNC` macro by automatic processing, developers do not have to manage the release of `se::Object` in `JS Object Control CPP Object` mode, but in` CPP Object Control JS Object` mode, developers have the responsibility to manage the release of `se::Object`. I will give an example in the next section. + +* Reason 2:More flexible, supporting strong reference by calling the se::Object::root method manually + +`se::Object` provides `root/unroot` method for developers to invoke, `root` will put JS object into the area not be scanned by the GC. After calling `root`, `se::Object*` is a strong reference to the JS object. JS object will be put back to the area scanned by the GC only when `se::Object` is destructed or `unroot` is called to make root count to zero. + +Under normal circumstances, if CPP object is not a subclass of `cocos2d :: Ref`, CPP object will be used to control the life cycle of the JS object in binding. Binding the engine modules, like spine, dragonbones, box2d, anysdk and other third-party libraries uses this method. When the CPP object is released, you need to find the corresponding `se::Object` in the `NativePtrToObjectMap`, then manually `unroot` and `decRef` it. Take the binding of `spTrackEntry` in spine as an example: + +```c++ +spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ + // The callback of spTrackEntry destruction + auto cleanup = [entry](){ + + if (!se::ScriptEngine::getInstance()->isValid()) + return; + + se::AutoHandleScope hs; + se::ScriptEngine::getInstance()->clearException(); + + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + CCLOG("spTrackEntry %p was recycled!", entry); + se::Object* seObj = iter->second; + seObj->clearPrivateData(); // Remove the mapping + seObj->unroot(); // unroot,make JS objects controlled by garbage collector + seObj->decRef(); // Decrease the reference of se::Object + } + }; + + // Make sure not to touch JS engine API while garbage collecting. + if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) + { + cleanup(); + } + else + { // Put the cleanning task at the end of current game frame if it's in garbage collection. + CleanupTask::pushTaskToAutoReleasePool(cleanup); + } + }); +``` + + +__se::Object Types__ + +* Native Binding Object + + The creation of native binding object has been hidden in the `SE_BIND_CTOR` and` SE_BIND_SUB_CLS_CTOR` macros, if developers need to use the `se::Object` in the binding callback, just get it by invoking `s.thisObject()`. Where `s` is `se::State&` which will be described in the following chapters. + +In addition, `se::Object` currently supports the manual creation of the following objects: + +* Plain Object: Created by `se::Object::createPlainObject`, similar to `var a = {};` in JS +* Array Object: Created by `se::Object::createArrayObject`, similar to `var a = [];` in JS +* Uint8 Typed Array Object: Created by `se::Object::createUint8TypedArray`, like `var a = new Uint8Array(buffer);` in JS +* Array Buffer Object: Created by `se::Object::createArrayBufferObject` similar to `var a = new ArrayBuffer(len);` in JS + +__The Release of The Objects Created Manually__ + +`se::Object::createXXX` is unlike the create method in cocos2d-x, the abstraction layer is a completely separate module which does not rely on the autorelease mechanism in cocos2d-x. Although `se::Object` also inherits the reference count class `se::RefCounter`, developers need to handle the release for **objects created manually**. + +```c++ +se::Object* obj = se::Object::createPlainObject(); +... +... +obj->decRef(); // Decrease the reference count to avoid memory leak +``` + +#### se::HandleObject + +`se::HandleObject` is the recommended helper class for managing the objects created manually. + +* If using manual creation of objects in complex logic, developers often forget to deal with `decRef` in different conditions + +```c++ +bool foo() +{ + se::Object* obj = se::Object::createPlainObject(); + if (var1) + return false; // Return directly, forget to do 'decRef' operation + + if (var2) + return false; // Return directly, forget to do 'decRef' operation + ... + ... + obj->decRef(); + return true; +} +``` + +Plus adding `decRef` to different return condition branches can result in logically complex and difficult to maintain, and it is easy to forget about `decRef` if you make another return branch later. + +* If the JS engine did a GC operationJS engine right after `se::Object::createXXX`, which will result in the `se::Object` reference to an illegal pointer, the program may crash. + +In order to solve the above problems, the abstraction layer defines a type that assists in the management of **manually created objects**, namely `se::HandleObject`. + +`se::HandleObject` is a helper class for easier management of the `release (decRef)`, `root`, and `unroot` operations of manually created `se::Object` objects. +The following two code snippets are equivalent, the use of `se::HandleObject` significantly smaller amount of code, and more secure. + +```c++ + { + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty(...); + otherObject->setProperty("foo", se::Value(obj)); + } + + is equal to: + + { + se::Object* obj = se::Object::createPlainObject(); + obj->root(); // Root the object immediatelly to prevent the object being garabge collected. + + obj->setProperty(...); + otherObject->setProperty("foo", se::Value(obj)); + + obj->unroot(); // Call unroot while the object is needed anymore. + obj->decRef(); // Decrease the reference count to avoid memory leak. + } +``` + +**NOTE** + +* Do not try to use `se::HandleObject` to create a native binding object. In the `JS controls of CPP` mode, the release of the bound object will be automatically handled by the abstraction layer. In the `CPP controls JS` mode, the previous chapter has already described. + +* The `se::HandleObject` object can only be allocated on the stack, and a `se::Object` pointer must be passed in. + + +#### se::Class + +`se::Class` is used to expose CPP classes to JS, it creates a constructor function in JS that has a corresponding name. + +It has the following methods: + +* `static se::Class* create(className, obj, parentProto, ctor)` + + **Creating a Class**. If the registration is successful, we could create an object by `var xxx = new SomeClass ();` in the JS layer. + +* `bool defineFunction(name, func)`: Define a member function for a class. +* `bool defineProperty(name, getter, setter)`: Define a property accessor for a class. +* `bool defineStaticFunction(name, func)`: Define a static function for a class, the JS function could be accessed by `SomeClass.foo()` rather than the method of `var obj = new SomeClass(); obj.foo()`, means it' s a class method instead of an instance method. +* `bool defineStaticProperty(name, getter, setter)`: Define a static property accessor which could be invoked by `SomeClass.propertyA`,it's nothing about instance object. +* `bool defineFinalizeFunction(func)`: Define the finalize callback function after JS object is garbage collected. +* `bool install()`: Install a class JS engine. +* `Object* getProto()`: Get the prototype of JS constructor installed, similar to `function Foo(){}` `Foo.prototype` in JS. +* `const char* getName() const`: Get the class name which is also the name of JS constructor. + +**NOTE** + +You do not need to release memory manually after `se::Class` type is created, it will be automatically encapsulated layer. + +You could look through the API documentation or code comments for more specific API instructions. + +#### se::AutoHandleScope + +The `se::AutoHandleScope` object type is purely a concept introduced to address V8 compatibility issues. +In V8, any action that calls `v8::Local<>` on a CPP function that needs to trigger a JS related operation, such as calling a JS function, accessing a JS property, etc, requires a `v8::HandleScope` function be invoked before calling these operations, otherwise it will cause the program to crash. + +So the concept of `se::AutoHandleScope` was introduced into the abstraction layer, which is implemented only on V8, and the other JS engines are currently just empty implementations. + +Developers need to remember that in any code execution from CPP, you need to declare a `se::AutoHandleScope` before calling JS's logic. For example: + +```c++ +class SomeClass { + void update(float dt) { + se::ScriptEngine::getInstance()->clearException(); // Clear JS exceptions + se::AutoHandleScope hs; // Declare a handle scope, it's needed for V8 + + se::Object* obj = ...; + obj->setProperty(...); + ... + ... + obj->call(...); + } +}; +``` + +#### se::State + +In the previous section, we have mentioned the `se::State` type, which is an environment in the binding callback. We can get the current CPP pointer, `se::Object` object pointer, parameter list and return value reference through `se::State` argument. + +```c++ +bool foo(se::State& s) +{ + // Get native object pointer bound with the current JS object. + SomeClass* cobj = (SomeClass*)s.nativeThisObject(); + // Get se::Object pointer that represents the current JS object. + se::Object* thisObject = s.thisObject(); + // Get argument list of the current function. + const se::ValueArray& args = s.args(); + // Set return value for current function. + s.rval().setInt32(100); + // Return true to indicate the function is executed successfully. + return true; +} +SE_BIND_FUNC(foo) +``` + +## Does The Abstraction Layer Depend on Cocos2D-X? + +No. + +This abstraction layer was originally designed as a stand-alone module which is completely independent of Cocos2D-X engine. Developers can copy the abstraction layer code in `cocos/scripting/js-bindings/jswrapper` directory and paste them to other projects directly. + +## Manual Binding + +### Define A Callback Function + +```c++ +static bool Foo_balabala(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + + if (argc >= 2) // Limit the number of parameters must be greater than or equal to 2, or throw an error to the JS layer and return false. { + ... + ... + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} + +// If binding a function, we use SE_BIND_FUNC macro. For binding a constructor, destructor, subclass constructor, please use SE_BIND_balabala macros memtioned above. +SE_BIND_FUNC(Foo_balabala) +``` + +### Set A Property Value for JS object + +```c++ +se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // We get the global object just for easiler demenstration. +globalObj->setProperty("foo", se::Value(100)); // Set a property called `foo` with a value of 100 to the global object. +``` + +Then, you can use the `foo` global variable in JS directly. + +```js +cc.log("foo value: " + foo); // Print `foo value: 100`. +``` + +### Set A Property Accessor for JS Object + +```c++ +// The read callback of `foo` property of the global object +static bool Global_get_foo(se::State& s) +{ + NativeObj* cobj = (NativeObj*)s.nativeThisObject(); + int32_t ret = cobj->getValue(); + s.rval().setInt32(ret); + return true; +} +SE_BIND_PROP_GET(Global_get_foo) + +// The write callback of `foo` property of the global object +static bool Global_set_foo(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc >= 1) + { + NativeObj* cobj = (NativeObj*)s.nativeThisObject(); + int32_t arg1 = args[0].toInt32(); + cobj->setValue(arg1); + // Do not need to call `s.rval().set(se::Value::Undefined)` for functions without return value. + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +SE_BIND_PROP_SET(Global_set_foo) + +void some_func() +{ + se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // We get the global object just for easiler demenstration. + globalObj->defineProperty("foo", _SE(Global_get_foo), _SE(Global_set_foo)); // Use _SE macro to package specific function name. +} +``` + +### Define A Function for JS Object + +```c++ +static bool Foo_function(se::State& s) +{ + ... + ... +} +SE_BIND_FUNC(Foo_function) + +void some_func() +{ + se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // We get the global object just for easiler demenstration. + globalObj->defineFunction("foo", _SE(Foo_function)); // Use _SE macro to package specific function name. +} + +``` + +### Register A CPP Class to JS Virtual Machine + +```c++ +static se::Object* __jsb_ns_SomeClass_proto = nullptr; +static se::Class* __jsb_ns_SomeClass_class = nullptr; + +namespace ns { + class SomeClass + { + public: + SomeClass() + : xxx(0) + {} + + void foo() { + printf("SomeClass::foo\n"); + + Director::getInstance()->getScheduler()->schedule([this](float dt){ + static int counter = 0; + ++counter; + if (_cb != nullptr) + _cb(counter); + }, this, 1.0f, CC_REPEAT_FOREVER, 0.0f, false, "iamkey"); + } + + static void static_func() { + printf("SomeClass::static_func\n"); + } + + void setCallback(const std::function& cb) { + _cb = cb; + if (_cb != nullptr) + { + printf("setCallback(cb)\n"); + } + else + { + printf("setCallback(nullptr)\n"); + } + } + + int xxx; + private: + std::function _cb; + }; +} // namespace ns { + +static bool js_SomeClass_finalize(se::State& s) +{ + return true; +} +SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize) + +static bool js_SomeClass_constructor(se::State& s) +{ + ns::SomeClass* cobj = new ns::SomeClass(); + s.thisObject()->setPrivateData(cobj); + return true; +} +SE_BIND_CTOR(js_SomeClass_constructor, __jsb_ns_SomeClass_class, js_SomeClass_finalize) + +static bool js_SomeClass_foo(se::State& s) +{ + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + cobj->foo(); + return true; +} +SE_BIND_FUNC(js_SomeClass_foo) + +static bool js_SomeClass_get_xxx(se::State& s) +{ + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + s.rval().setInt32(cobj->xxx); + return true; +} +SE_BIND_PROP_GET(js_SomeClass_get_xxx) + +static bool js_SomeClass_set_xxx(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc > 0) + { + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + cobj->xxx = args[0].toInt32(); + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +SE_BIND_PROP_SET(js_SomeClass_set_xxx) + +static bool js_SomeClass_static_func(se::State& s) +{ + ns::SomeClass::static_func(); + return true; +} +SE_BIND_FUNC(js_SomeClass_static_func) + +bool js_register_ns_SomeClass(se::Object* global) +{ + // Make sure the namespace exists + se::Value nsVal; + if (!global->getProperty("ns", &nsVal)) + { + // If it doesn't exist, create one. Similar as `var ns = {};` in JS. + se::HandleObject jsobj(se::Object::createPlainObject()); + nsVal.setObject(jsobj); + + // Set the object to the global object with the property name `ns`. + global->setProperty("ns", nsVal); + } + se::Object* ns = nsVal.toObject(); + + // Create a se::Class object, developers do not need to consider the release of the se::Class object, which is automatically handled by the ScriptEngine. + auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // If the registered class doesn't need a constructor, the last argument can be passed in with nullptr, it will make `new SomeClass();` illegal. + + // Define member functions, member properties. + cls->defineFunction("foo", _SE(js_SomeClass_foo)); + cls->defineProperty("xxx", _SE(js_SomeClass_get_xxx), _SE(js_SomeClass_set_xxx)); + + // Define finalize callback function + cls->defineFinalizeFunction(_SE(js_SomeClass_finalize)); + + // Install the class to JS virtual machine + cls->install(); + + // JSBClassType::registerClass is a helper function in the Cocos2D-X native binding code, which is not a part of the ScriptEngine. + JSBClassType::registerClass(cls); + + // Save the result to global variable for easily use in other places, for example class inheritence. + __jsb_ns_SomeClass_proto = cls->getProto(); + __jsb_ns_SomeClass_class = cls; + + // Set a property `yyy` with the string value `helloyyy` for each object instantiated by this class. + __jsb_ns_SomeClass_proto->setProperty("yyy", se::Value("helloyyy")); + + // Register static member variables and static member functions + se::Value ctorVal; + if (ns->getProperty("SomeClass", &ctorVal) && ctorVal.isObject()) + { + ctorVal.toObject()->setProperty("static_val", se::Value(200)); + ctorVal.toObject()->defineFunction("static_func", _SE(js_SomeClass_static_func)); + } + + // Clear JS exceptions + se::ScriptEngine::getInstance()->clearException(); + return true; +} +``` + +### How to Bind A CPP Callback Function + +```c++ +static bool js_SomeClass_setCallback(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc >= 1) + { + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + + se::Value jsFunc = args[0]; + se::Value jsTarget = argc > 1 ? args[1] : se::Value::Undefined; + + if (jsFunc.isNullOrUndefined()) + { + cobj->setCallback(nullptr); + } + else + { + assert(jsFunc.isObject() && jsFunc.toObject()->isFunction()); + + // If the current SomeClass is a class that can be created by `new`, we use se::Object::attachObject to associate jsFunc with jsTarget to the current object. + s.thisObject()->attachObject(jsFunc.toObject()); + s.thisObject()->attachObject(jsTarget.toObject()); + + // If the current SomeClass class is a singleton, or a class that always has only one instance, we can not associate it with se::Object::attachObject. + // Instead, you must use se::Object::root, developers do not need to unroot since unroot operation will be triggered in the destruction of lambda which makes the se::Value jsFunc be destroyed, then se::Object destructor will do the unroot operation automatically. + // The binding function `js_cocos2dx_EventDispatcher_addCustomEventListener` implements it in this way because `EventDispatcher` is always a singleton. + // Using s.thisObject->attachObject(jsFunc.toObject); for binding addCustomEventListener will cause jsFunc and jsTarget varibales can't be released, which will result in memory leak. + + // jsFunc.toObject()->root(); + // jsTarget.toObject()->root(); + + cobj->setCallback([jsFunc, jsTarget](int counter){ + + // Add the following two lines of code in CPP callback function before passing data to the JS. + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + // + + se::ValueArray args; + args.push_back(se::Value(counter)); + + se::Object* target = jsTarget.isObject() ? jsTarget.toObject() : nullptr; + jsFunc.toObject()->call(args, target); + }); + } + + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +SE_BIND_FUNC(js_SomeClass_setCallback) +``` + +After SomeClass is registered, you can use it in JS like the following: + +```js + var myObj = new ns.SomeClass(); + myObj.foo(); + ns.SomeClass.static_func(); + cc.log("ns.SomeClass.static_val: " + ns.SomeClass.static_val); + cc.log("Old myObj.xxx:" + myObj.xxx); + myObj.xxx = 1234; + cc.log("New myObj.xxx:" + myObj.xxx); + cc.log("myObj.yyy: " + myObj.yyy); + + var delegateObj = { + onCallback: function(counter) { + cc.log("Delegate obj, onCallback: " + counter + ", this.myVar: " + this.myVar); + this.setVar(); + }, + + setVar: function() { + this.myVar++; + }, + + myVar: 100 + }; + + myObj.setCallback(delegateObj.onCallback, delegateObj); + + setTimeout(function(){ + myObj.setCallback(null); + }, 6000); // Clear callback after 6 seconds. +``` + +There will be some logs outputed in console: + +``` +SomeClass::foo +SomeClass::static_func +ns.SomeClass.static_val: 200 +Old myObj.xxx:0 +New myObj.xxx:1234 +myObj.yyy: helloyyy +setCallback(cb) +Delegate obj, onCallback: 1, this.myVar: 100 +Delegate obj, onCallback: 2, this.myVar: 101 +Delegate obj, onCallback: 3, this.myVar: 102 +Delegate obj, onCallback: 4, this.myVar: 103 +Delegate obj, onCallback: 5, this.myVar: 104 +Delegate obj, onCallback: 6, this.myVar: 105 +setCallback(nullptr) +``` + +### How to Use The Helper Functions in Cocos2D-X Binding for Easiler Native<->JS Type Conversions + +The helper functions for native<->JS type conversions are located in `cocos/scripting/js-bindings/manual/jsb_conversions.hpp/.cpp`, it includes: + +#### Convert se::Value to CPP Type + +``` +bool seval_to_int32(const se::Value& v, int32_t* ret); +bool seval_to_uint32(const se::Value& v, uint32_t* ret); +bool seval_to_int8(const se::Value& v, int8_t* ret); +bool seval_to_uint8(const se::Value& v, uint8_t* ret); +bool seval_to_int16(const se::Value& v, int16_t* ret); +bool seval_to_uint16(const se::Value& v, uint16_t* ret); +bool seval_to_boolean(const se::Value& v, bool* ret); +bool seval_to_float(const se::Value& v, float* ret); +bool seval_to_double(const se::Value& v, double* ret); +bool seval_to_long(const se::Value& v, long* ret); +bool seval_to_ulong(const se::Value& v, unsigned long* ret); +bool seval_to_longlong(const se::Value& v, long long* ret); +bool seval_to_ssize(const se::Value& v, ssize_t* ret); +bool seval_to_std_string(const se::Value& v, std::string* ret); +bool seval_to_Vec2(const se::Value& v, cocos2d::Vec2* pt); +bool seval_to_Vec3(const se::Value& v, cocos2d::Vec3* pt); +bool seval_to_Vec4(const se::Value& v, cocos2d::Vec4* pt); +bool seval_to_Mat4(const se::Value& v, cocos2d::Mat4* mat); +bool seval_to_Size(const se::Value& v, cocos2d::Size* size); +bool seval_to_Rect(const se::Value& v, cocos2d::Rect* rect); +bool seval_to_Color3B(const se::Value& v, cocos2d::Color3B* color); +bool seval_to_Color4B(const se::Value& v, cocos2d::Color4B* color); +bool seval_to_Color4F(const se::Value& v, cocos2d::Color4F* color); +bool seval_to_ccvalue(const se::Value& v, cocos2d::Value* ret); +bool seval_to_ccvaluemap(const se::Value& v, cocos2d::ValueMap* ret); +bool seval_to_ccvaluemapintkey(const se::Value& v, cocos2d::ValueMapIntKey* ret); +bool seval_to_ccvaluevector(const se::Value& v, cocos2d::ValueVector* ret); +bool sevals_variadic_to_ccvaluevector(const se::ValueArray& args, cocos2d::ValueVector* ret); +bool seval_to_blendfunc(const se::Value& v, cocos2d::BlendFunc* ret); +bool seval_to_std_vector_string(const se::Value& v, std::vector* ret); +bool seval_to_std_vector_int(const se::Value& v, std::vector* ret); +bool seval_to_std_vector_float(const se::Value& v, std::vector* ret); +bool seval_to_std_vector_Vec2(const se::Value& v, std::vector* ret); +bool seval_to_std_vector_Touch(const se::Value& v, std::vector* ret); +bool seval_to_std_map_string_string(const se::Value& v, std::map* ret); +bool seval_to_FontDefinition(const se::Value& v, cocos2d::FontDefinition* ret); +bool seval_to_Acceleration(const se::Value& v, cocos2d::Acceleration* ret); +bool seval_to_Quaternion(const se::Value& v, cocos2d::Quaternion* ret); +bool seval_to_AffineTransform(const se::Value& v, cocos2d::AffineTransform* ret); +//bool seval_to_Viewport(const se::Value& v, cocos2d::experimental::Viewport* ret); +bool seval_to_Data(const se::Value& v, cocos2d::Data* ret); +bool seval_to_DownloaderHints(const se::Value& v, cocos2d::network::DownloaderHints* ret); +bool seval_to_TTFConfig(const se::Value& v, cocos2d::TTFConfig* ret); + +//box2d seval to native convertion +bool seval_to_b2Vec2(const se::Value& v, b2Vec2* ret); +bool seval_to_b2AABB(const se::Value& v, b2AABB* ret); + +template +bool seval_to_native_ptr(const se::Value& v, T* ret); + +template +bool seval_to_Vector(const se::Value& v, cocos2d::Vector* ret); + +template +bool seval_to_Map_string_key(const se::Value& v, cocos2d::Map* ret) + +``` + +#### Convert C++ Type to se::Value + +```c++ +bool int8_to_seval(int8_t v, se::Value* ret); +bool uint8_to_seval(uint8_t v, se::Value* ret); +bool int32_to_seval(int32_t v, se::Value* ret); +bool uint32_to_seval(uint32_t v, se::Value* ret); +bool int16_to_seval(uint16_t v, se::Value* ret); +bool uint16_to_seval(uint16_t v, se::Value* ret); +bool boolean_to_seval(bool v, se::Value* ret); +bool float_to_seval(float v, se::Value* ret); +bool double_to_seval(double v, se::Value* ret); +bool long_to_seval(long v, se::Value* ret); +bool ulong_to_seval(unsigned long v, se::Value* ret); +bool longlong_to_seval(long long v, se::Value* ret); +bool ssize_to_seval(ssize_t v, se::Value* ret); +bool std_string_to_seval(const std::string& v, se::Value* ret); + +bool Vec2_to_seval(const cocos2d::Vec2& v, se::Value* ret); +bool Vec3_to_seval(const cocos2d::Vec3& v, se::Value* ret); +bool Vec4_to_seval(const cocos2d::Vec4& v, se::Value* ret); +bool Mat4_to_seval(const cocos2d::Mat4& v, se::Value* ret); +bool Size_to_seval(const cocos2d::Size& v, se::Value* ret); +bool Rect_to_seval(const cocos2d::Rect& v, se::Value* ret); +bool Color3B_to_seval(const cocos2d::Color3B& v, se::Value* ret); +bool Color4B_to_seval(const cocos2d::Color4B& v, se::Value* ret); +bool Color4F_to_seval(const cocos2d::Color4F& v, se::Value* ret); +bool ccvalue_to_seval(const cocos2d::Value& v, se::Value* ret); +bool ccvaluemap_to_seval(const cocos2d::ValueMap& v, se::Value* ret); +bool ccvaluemapintkey_to_seval(const cocos2d::ValueMapIntKey& v, se::Value* ret); +bool ccvaluevector_to_seval(const cocos2d::ValueVector& v, se::Value* ret); +bool blendfunc_to_seval(const cocos2d::BlendFunc& v, se::Value* ret); +bool std_vector_string_to_seval(const std::vector& v, se::Value* ret); +bool std_vector_int_to_seval(const std::vector& v, se::Value* ret); +bool std_vector_float_to_seval(const std::vector& v, se::Value* ret); +bool std_vector_Touch_to_seval(const std::vector& v, se::Value* ret); +bool std_map_string_string_to_seval(const std::map& v, se::Value* ret); +bool uniform_to_seval(const cocos2d::Uniform* v, se::Value* ret); +bool FontDefinition_to_seval(const cocos2d::FontDefinition& v, se::Value* ret); +bool Acceleration_to_seval(const cocos2d::Acceleration* v, se::Value* ret); +bool Quaternion_to_seval(const cocos2d::Quaternion& v, se::Value* ret); +bool ManifestAsset_to_seval(const cocos2d::extension::ManifestAsset& v, se::Value* ret); +bool AffineTransform_to_seval(const cocos2d::AffineTransform& v, se::Value* ret); +bool Data_to_seval(const cocos2d::Data& v, se::Value* ret); +bool DownloadTask_to_seval(const cocos2d::network::DownloadTask& v, se::Value* ret); + +template +bool Vector_to_seval(const cocos2d::Vector& v, se::Value* ret); + +template +bool Map_string_key_to_seval(const cocos2d::Map& v, se::Value* ret); + +template +bool native_ptr_to_seval(typename std::enable_if::value,T>::type* v, se::Value* ret, bool* isReturnCachedValue = nullptr); + +template +bool native_ptr_to_seval(typename std::enable_if::value,T>::type* v, se::Class* cls, se::Value* ret, bool* isReturnCachedValue = nullptr) + +template +bool native_ptr_to_seval(typename std::enable_if::value,T>::type* v, se::Value* ret, bool* isReturnCachedValue = nullptr); + +template +bool native_ptr_to_seval(typename std::enable_if::value,T>::type* v, se::Class* cls, se::Value* ret, bool* isReturnCachedValue = nullptr); + +template +bool native_ptr_to_rooted_seval(typename std::enable_if::value,T>::type* v, se::Value* ret, bool* isReturnCachedValue = nullptr); + +template +bool native_ptr_to_rooted_seval(typename std::enable_if::value,T>::type* v, se::Class* cls, se::Value* ret, bool* isReturnCachedValue = nullptr); + + +// Spine conversions +bool speventdata_to_seval(const spEventData& v, se::Value* ret); +bool spevent_to_seval(const spEvent& v, se::Value* ret); +bool spbonedata_to_seval(const spBoneData& v, se::Value* ret); +bool spbone_to_seval(const spBone& v, se::Value* ret); +bool spskeleton_to_seval(const spSkeleton& v, se::Value* ret); +bool spattachment_to_seval(const spAttachment& v, se::Value* ret); +bool spslotdata_to_seval(const spSlotData& v, se::Value* ret); +bool spslot_to_seval(const spSlot& v, se::Value* ret); +bool sptimeline_to_seval(const spTimeline& v, se::Value* ret); +bool spanimationstate_to_seval(const spAnimationState& v, se::Value* ret); +bool spanimation_to_seval(const spAnimation& v, se::Value* ret); +bool sptrackentry_to_seval(const spTrackEntry& v, se::Value* ret); + +// Box2d +bool b2Vec2_to_seval(const b2Vec2& v, se::Value* ret); +bool b2Manifold_to_seval(const b2Manifold* v, se::Value* ret); +bool b2AABB_to_seval(const b2AABB& v, se::Value* ret); + +``` + +Auxiliary conversion functions are not part of the abstraction layer (`Script Engine Wrapper`), they belong to the Cocos2D-X binding layer and are encapsulated to facilitate more convenient conversion in the binding code. +Each conversion function returns the type `bool` indicating whether the conversion was successful or not. Developers need to check the return value after calling these interfaces. + +You can know the specific usage directly according to interface names. The first parameter in the interface is input, and the second parameter is the output parameter. The usage is as follows: + +```c++ +se::Value v; +bool ok = int32_to_seval(100, &v); // The second parameter is the output parameter, passing in the address of the output parameter +``` + +```c++ +int32_t v; +bool ok = seval_to_int32(args[0], &v); // The second parameter is the output parameter, passing in the address of the output parameter +``` + +#### (IMPORTANT) Understand The Difference Between native\_ptr\_to\_seval and native\_ptr\_to\_rooted\_seval + +**Developers must understand the difference to make sure these conversion functions not being misused. In that case, JS memory leaks, which is really difficult to fix, could be avoided.** + +* `native_ptr_to_seval` is used in `JS control CPP object life cycle` mode. This method can be called when a `se::Value` needs to be obtained from a CPP object pointer at the binding code. Most subclasses in the Cocos2D-X that inherit from `cocos2d::Ref` take this approach to get `se::Value`. Please remember, when the binding object, which is controlled by the JS object's life cycle, need to be converted to seval, use this method, otherwise consider using `native_ptr_to_rooted_seval`. +* `native_ptr_to_rooted_seval` is used in `CPP controlling JS object lifecycle` mode. In general, this method is used for object bindings in third-party libraries. This method will try to find the cached `se::Object` according the incoming CPP object pointer, if the cached `se::Object`is not exist, then it will create a rooted `se::Object` which isn't controlled by Garbage Collector and will always keep alive until `unroot` is called. Developers need to observe the release of the CPP object, and `unroot` `se::Object`. Please refer to the section introduces `spTrackEntry` binding (spTrackEntry_setDisposeCallback) described above. + + +## Automatic Binding + +### Configure Module .ini Files + +The configuration method is the same as that in Creator v1.6. The main points to note are: In Creator v1.7 `script_control_cpp` field is deprecated because `script_control_cpp` field affects the entire module. If the module needs to bind the `cocos2d::Ref` subclass and non- `cocos2d::Ref` class, the original binding configuration in v1.6 can not meet the demand. The new field introduced in v1.7 is `classes_owned_by_cpp`, which indicates which classes need to be controlled by the CPP object's life cycle. + +An additional, there is a configuration field in v1.7 is `persistent_classes` to indicate which classes are always present during game play, such as: `TextureCache`, `SpriteFrameCache`, `FileUtils`, `EventDispatcher`, `ActionManager`, `Scheduler`. + +Other fields are the same as v1.6. + +For more specific, please refer to the engine directory `tools/tojs/cocos2dx.ini` file. + +### Understand The Meaning of Each Field in The .ini file + +``` +# Module name +[cocos2d-x] + +# The prefix for callback functions and the binding file name. +prefix = cocos2dx + +# The namspace of the binding class attaches to. +target_namespace = cc + +# Automatic binding tools is based on the Android NDK. The android_headers field configures the search path of Android header file. +android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/include + +# Configure building parameters for Android. +android_flags = -D_SIZE_T_DEFINED_ + +# Configure the search path for clang header file. +clang_headers = -I%(clangllvmdir)s/%(clang_include)s + +# Configure building parameters for clang +clang_flags = -nostdinc -x c++ -std=c++11 -U __SSE__ + +# Configure the search path for Cocos2D-X header file +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external/sources + +# Configure building parameters for Cocos2D-X +cocos_flags = -DANDROID + +# Configure extra building parameters +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# Which header files needed to be parsed +headers = %(cocosdir)s/cocos/cocos2d.h %(cocosdir)s/cocos/scripting/js-bindings/manual/BaseJSAction.h + +# Rename the header file in the generated binding code +replace_headers=CCProtectedNode.h::2d/CCProtectedNode.h,CCAsyncTaskPool.h::base/CCAsyncTaskPool.h + +# Which classes need to be bound, you can use regular expressions, separated by space. +classes = + +# Which classes which use cc.Class.extend to inherit, separated by space. +classes_need_extend = + +# Which classes need to bind properties, separated by commas +field = Acceleration::[x y z timestamp] + +# Which classes need to be skipped, separated by commas +skip = AtlasNode::[getTextureAtlas], + ParticleBatchNode::[getTextureAtlas], + +# Which functions need to be renamed, separated by commas +rename_functions = ComponentContainer::[get=getComponent], + LayerColor::[initWithColor=init], + +# Which classes need to be renamed, separated by commas +rename_classes = SimpleAudioEngine::AudioEngine, + SAXParser::PlistParser, + + +# Which classes do not have parents in JS +classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application GLViewProtocol SAXParser Configuration + +# Which C++ base classes need to be skipped +base_classes_to_skip = Ref Clonable + +# Which classes are abstract classes which do not have a constructor in JS +abstract_classes = Director SpriteFrameCache Set SimpleAudioEngine + +# Which classes are singleton or always keep alive until game exits +persistent_classes = TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler + +# Which classes use `CPP object controls JS object's life cycle`, the unconfigured classes will use `JS controls CPP object's life cycle`. +classes_owned_by_cpp = +``` + +## Remote Debugging and Profile + +The remote debugging and profile are valid in debug mode, if you need to enable in release mode, you need to manually modify the macro in `cocos/scripting/js-bindings/jswrapper/config.hpp`. + +```c++ +#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0 +#define SE_ENABLE_INSPECTOR 1 +#define SE_DEBUG 2 +#else +#define SE_ENABLE_INSPECTOR 0 +#define SE_DEBUG 0 +#endif +``` + +Change to: + +```c++ +#if 1 // Change to 1 to force enable remote debugging +#define SE_ENABLE_INSPECTOR 1 +#define SE_DEBUG 2 +#else +#define SE_ENABLE_INSPECTOR 0 +#define SE_DEBUG 0 +#endif +``` + +### Remote Debugging V8 in Chrome + +#### Windows + +* Compile, run the game (or run directly in the Creator simulator) +* Open with Chrome: [chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008) + +Breakpoint debugging: +![](v8-win32-debug.jpg) + +Catch JS Heap +![](v8-win32-memory.jpg) + +Profile +![](v8-win32-profile.jpg) + +#### Android + +* Make sure your Android device is on the same network as your PC or Mac +* Compile and run your game +* Open with Chrome: [chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008), `xxx.xxx.xxx.xxx` is the IP address of Android device +* The remote debugging interface is the same as debugging Windows. + + +### Remote Debugging JavaScriptCore in Safari + +#### macOS + +1. Open Safari on your Mac, Preferences -> Advanced -> Show Develop menu in menu bar +2. Add entitlements file to Xcode project, skip this step if entitlements exist. If it does not exist, open the App Sandbox in the Capabilities setting of the project, and then close again. At this point, the .entitlements file is automatically added to the project.![](jsc-entitlements.png). You also need to make sure the entitlements file is included in the Code Signing Entitlemenets option in the Build Setting. ![](jsc-entitlements-check.png) +3. Open the entitlements file, add com.apple.security.get-task-allow, the value type is Boolean, the value is YES. ![](jsc-security-key.png) +4. Signature: General -> Choose your Mac Project -> Signing -> Choose your Developer Certificate +5. Compile and run your game +6. If it is run directly in Creator's simulator, you can skip steps 2,3,4,5 +7. Click Safari menu, select Develop -> your Mac device name -> Cocos2d-x JSB will automatically open the Web Inspector page, and then you can set breakpoints, Timeline profile, console and other operations.![](jsc-mac-debug.png) ![](jsc-breakpoint.png) ![](jsc-timeline.png) + +**NOTE** + +If developers have to modify the engine source or merge some patches, they need to recompile the simulator, remember to reset the simulator project certificate. + +![](jsc-mac-simulator-sign.png) + +Then run `gulp gen-simulator` in terminal to generate simulator. + +#### iOS + +1. Open the iPhone Settings -> Safari -> Advanced -> Web Inspector +2. Add entitlements file to Xcode project, skip this step if entitlements exist. If it does not exist, open the App Sandbox in the Capabilities setting of the project, and then close again. At this point, the .entitlements file is automatically added to the project. You also need to make sure the entitlements file is included in the Code Signing Entitlemenets option in the Build Setting. (The illustration image is similar to step 2 of macOS) +3. Open the entitlements file, add com.apple.security.get-task-allow, the value type is Boolean, the value is YES. (The illustration image is similar to step 3 of macOS) +4. Signature: General -> Choose your iOS project -> Signing -> Choose your developer certificate +5. Compile and run your game +6. Click Safari menu, select Develop -> your iOS device name -> Cocos2d-x JSB will automatically open the Web Inspector page, and then you can set breakpoints, Timeline profile, console and other operations.(The illustration image is similar to step 7 of macOS) + +## Q & A + +### What's The Difference between se::ScriptEngine and ScriptingCore? Why to keep ScriptingCore? + +In Creator v1.7, the abstraction layer was designed as a stand-alone module that had no relation to the engine. The management of the JS engine was moved from the `ScriptingCore` to `se::ScriptEngine` class. `ScriptingCore` was retained in hopes of passing engine events to the abstraction layer, which acts like a adapter. + +ScriptingCore only needs to be used once in AppDelegate.cpp, and all subsequent operations only require `se::ScriptEngine`. + +```c++ +bool AppDelegate::applicationDidFinishLaunching() +{ + ... + ... + director->setAnimationInterval(1.0 / 60); + + // These two lines set the ScriptingCore adapter to the engine for passing engine events, such as Node's onEnter, onExit, Action's update + ScriptingCore* sc = ScriptingCore::getInstance(); + ScriptEngineManager::getInstance()->setScriptEngine(sc); + + se::ScriptEngine* se = se::ScriptEngine::getInstance(); + ... + ... +} +``` +### What's The Difference between se::Object::root/unroot and se::Object::incRef/decRef? + +`root`/`unroot` is used to control whether JS objects are controlled by GC, `root` means JS object should not be controlled by GC, `unroot` means it should be controlled by GC. For a `se::Object`, `root` and `unroot` can be called multiple times, `se::Object`'s internal `_rootCount` variables is used to indicate the count of `root` operation. When `unroot` is called and `_rootCount` reach **0**, the JS object associated with `se::Object` is handed over to the GC. Another situation is that if `se::Object` destructor is triggered and `_rootCount` is still greater than 0, it will force the JS object to be controlled by the GC. + +`incRef`/`decRef` is used to control the life cycle of `se::Object` CPP object. As mentioned in the previous section, it is recommended that you use `se::HandleObject` to control the manual creation of unbound objects's life cycle. So, in general, developers do not need to touch `incRef`/`decRef`. + + +### The Association and Disassociation of Object's Life Cycle + +Use se::Object::attachObject to associate object's life cycle. +Use se::Object::dettachObject to disassociate object's life cycle. + +`objA->attachObject(objB);` is similar as `objA .__ nativeRefs [index] = objB` in JS. Only when `objA` is garbage collected, `objB` will be possible garbage collected. +`objA->dettachObject(objB);` is similar as `delete objA.__nativeRefs[index];` in JS. After invoking dettachObject, objB's life cycle will not be controlled by objA + +### What's The Difference of Object Life Management between The Subclass of `cocos2d::Ref` and non-`cocos2d::Ref` class? + +The binding of `cocos2d::Ref` subclass in the current engine adopts JS object controls the life cycle of CPP object. The advantage of doing so is to solve the `retain`/`release` problem that has been criticized in the JS layer. + +Non-`cocos2d::Ref` class takes the way of CPP object controls the life of a JS object. This method requires that after CPP object is destroyed, it needs to notify the binding layer to call the `clearPrivateData`, `unroot`, and `decRef` methods corresponding to `se::Object`. JS code must be careful operation of the object, when there may be illegal object logic, use `cc.sys.isObjectValid` to determine whether the CPP object is released. + +### NOTE of Binding The Finalize Function for cocos2d::Ref Subclass + +Calling any JS engine's API in a finalize callback can lead to a crash. Because the current engine is in garbage collection process, which can not be interrupted to deal with other operations. +Finalize callback is to tell the CPP layer to release the memory of the corresponding CPP object, we should not call any JS engine API in the CPP object's destructor either. + +#### But if that must be called, how should we deal with? + +In Cocos2D-X binding, if the native object's reference count is 1, we do not use the `release`, but using `autorelease` to delay CPP object's destructor to be executed at the end of frame. For instance: + +```c++ +static bool js_cocos2d_Sprite_finalize(se::State& s) +{ + CCLOG("jsbindings: finalizing JS object %p (cocos2d::Sprite)", s.nativeThisObject()); + cocos2d::Sprite* cobj = (cocos2d::Sprite*)s.nativeThisObject(); + if (cobj->getReferenceCount() == 1) + cobj->autorelease(); + else + cobj->release(); + return true; +} +SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize) +``` + +### Please DO NOT Assign A Subclass of cocos2d::Ref on The Stack + +Subclasses of `cocos2d::Ref` must be allocated on the heap, via `new`, and then released by` release`. In JS object's finalize callback function, we should use 'autorelease` or `release` to release. If it is allocated on the stack, the reference count is likely to be 0, and then calling `release` in finalize callback will result `delete` is invoked, which causing the program to crash. So in order to prevent this behavior from happening, developers can identify destructors as `protected` or` private` in the binding classes that inherit from `cocos2d::Ref`, ensuring that this problem can be found during compilation. + +E.g: + +```c++ +class CC_EX_DLL EventAssetsManagerEx : public cocos2d::EventCustom +{ +public: + ... + ... +private: + virtual ~EventAssetsManagerEx() {} + ... + ... +}; + +EventAssetsManagerEx event(...); // Compilation ERROR +dispatcher->dispatchEvent(&event); + +// Must modify to: + +EventAssetsManagerEx* event = new EventAssetsManagerEx(...); +dispatcher->dispatchEvent(event); +event->release(); +``` + + + +### How to Observe JS Exception? + +In AppDelegate.cpp, using `se::ScriptEngine::getInstance()->setExceptionCallback(...)` to set the callback of JS exception. + +```c++ +bool AppDelegate::applicationDidFinishLaunching() +{ + ... + ... + se::ScriptEngine* se = se::ScriptEngine::getInstance(); + + se->setExceptionCallback([](const char* location, const char* message, const char* stack){ + // Send exception information to server like Tencent Bugly. + // ... + // ... + }); + + jsb_register_all_modules(); + ... + ... + return true; +} + +``` + + + + diff --git a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md index 6f4b05d9d4..196c64649a 100644 --- a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md @@ -1,4 +1,4 @@ -# JSB2.0 绑定教程 +# JSB 2.0 绑定教程 ## 抽象层 @@ -6,18 +6,18 @@ ![](JSB2.0-Architecture.png) -### 宏(macro) +### 宏(Macro) -抽象层必然会比直接使用JS引擎API的方式多占用一些CPU执行时间,如何把抽象层本身的开销降到最低成为设计的第一目标。 +抽象层必然会比直接使用 JS 引擎 API 的方式多占用一些 CPU 执行时间,如何把抽象层本身的开销降到最低成为设计的第一目标。 -JS绑定的大部分工作其实就是设定JS相关操作的CPP回调,在回调函数中关联CPP对象。其实主要包含如下两种类型: +JS 绑定的大部分工作其实就是设定 JS 相关操作的 CPP 回调,在回调函数中关联 CPP 对象。其实主要包含如下两种类型: -* 注册JS函数(包含全局函数,类构造函数、类析构函数、类成员函数,类静态成员函数),绑定一个CPP回调 -* 注册JS对象的属性读写访问器,分别绑定读与写的CPP回调 +* 注册 JS 函数(包含全局函数,类构造函数、类析构函数、类成员函数,类静态成员函数),绑定一个 CPP 回调 +* 注册 JS 对象的属性读写访问器,分别绑定读与写的 CPP 回调 -如何做到抽象层开销最小而且暴露统一的API供上层使用? +如何做到抽象层开销最小而且暴露统一的 API 供上层使用? -以注册JS函数的回调定义为例,JavaScriptCore, SpiderMonkey, V8, ChakraCore的定义各不相同,具体如下: +以注册 JS 函数的回调定义为例,JavaScriptCore,SpiderMonkey,V8,ChakraCore 的定义各不相同,具体如下: **JavaScriptCore:** @@ -62,7 +62,7 @@ JsValueRef JSB_foo_func( ); ``` -我们评估了几种方案,最终确定使用`宏`来抹平不同JS引擎回调函数定义与参数类型的不同,不管底层是使用什么引擎,开发者统一使用一种回调函数的定义。我们借鉴了lua的回调函数定义方式,抽象层所有的JS到CPP的回调函数的定义为: +我们评估了几种方案,最终确定使用`宏`来抹平不同 JS 引擎回调函数定义与参数类型的不同,不管底层是使用什么引擎,开发者统一使用一种回调函数的定义。我们借鉴了 lua 的回调函数定义方式,抽象层所有的 JS 到 CPP 的回调函数的定义为: ```c++ bool foo(se::State& s) @@ -73,34 +73,34 @@ bool foo(se::State& s) SE_BIND_FUNC(foo) // 此处以回调函数的定义为例 ``` -开发者编写完回调函数后,记住使用`SE_BIND_XXX`系列的宏对回调函数进行包装。目前提供了如下几个宏: +开发者编写完回调函数后,记住使用 `SE_BIND_XXX` 系列的宏对回调函数进行包装。目前提供了如下几个宏: -* SE\_BIND\_PROP_GET: 包装一个JS对象属性读取的回调函数 -* SE\_BIND\_PROP_SET: 包装一个JS对象属性写入的回调函数 -* SE\_BIND_FUNC: 包装一个JS函数,可用于全局函数、类成员函数、类静态函数 -* SE\_DECLARE_FUNC: 声明一个JS函数,一般在.h头文件中使用 -* SE\_BIND_CTOR: 包装一个JS构造函数 -* SE\_BIND\_SUB\_CLS\_CTOR: 包装一个JS子类的构造函数,此子类使用cc.Class.extend继承Native绑定类 -* SE\_FINALIZE_FUNC: 包装一个JS对象被GC回收后的回调函数 -* SE\_DECLARE\_FINALIZE_FUNC: 声明一个JS对象被GC回收后的回调函数 -* _SE: 包装回调函数的名称,转义为每个JS引擎能够识别的回调函数的定义,注意,第一个字符为下划线,类似Windows下用的`_T("xxx")`来包装Unicode或者MultiBytes字符串 +* SE\_BIND\_PROP_GET:包装一个 JS 对象属性读取的回调函数 +* SE\_BIND\_PROP_SET:包装一个 JS 对象属性写入的回调函数 +* SE\_BIND_FUNC:包装一个 JS 函数,可用于全局函数、类成员函数、类静态函数 +* SE\_DECLARE_FUNC:声明一个 JS 函数,一般在 .h 头文件中使用 +* SE\_BIND_CTOR:包装一个 JS 构造函数 +* SE\_BIND\_SUB\_CLS\_CTOR:包装一个 JS 子类的构造函数,此子类使用 cc.Class.extend 继承 Native 绑定类 +* SE\_FINALIZE_FUNC:包装一个 JS 对象被 GC 回收后的回调函数 +* SE\_DECLARE\_FINALIZE_FUNC:声明一个 JS 对象被 GC 回收后的回调函数 +* _SE:包装回调函数的名称,转义为每个 JS 引擎能够识别的回调函数的定义,注意,第一个字符为下划线,类似 Windows 下用的`_T("xxx")`来包装 Unicode 或者 MultiBytes 字符串 ## API -### CPP命名空间(namespace) +### CPP 命名空间(namespace) -CPP抽象层所有的类型都在`se`命名空间下,其为ScriptEngine的缩写。 +CPP 抽象层所有的类型都在 `se` 命名空间下,其为 ScriptEngine 的缩写。 ### 类型 #### se::ScriptEngine -se::ScriptEngine为JS引擎的管理员,掌管JS引擎初始化、销毁、重启、Native模块注册、加载脚本、强制垃圾回收、JS异常清理、是否启用调试器。 -它是一个单例,可通过se::ScriptEngine::getInstance()得到对应的实例。 +se::ScriptEngine 为 JS 引擎的管理员,掌管 JS 引擎初始化、销毁、重启、Native 模块注册、加载脚本、强制垃圾回收、JS 异常清理、是否启用调试器。 +它是一个单例,可通过 se::ScriptEngine::getInstance() 得到对应的实例。 #### se::Value -se::Value可以被理解为JS变量在CPP层的引用。JS变量有`object`, `number`, `string`, `boolean`, `null`, `undefined`六种类型,因此se::Value使用`union`包含`object`, `number`, `string`, `boolean`4种`有值类型`,`无值类型`: `null`, `undefined`可由`_type`直接表示。 +se::Value 可以被理解为 JS 变量在 CPP 层的引用。JS 变量有 `object`, `number`, `string`, `boolean`, `null`, `undefined` 六种类型,因此 se::Value 使用 `union` 包含 `object`, `number`, `string`, `boolean`4 种`有值类型`,`无值类型`: `null`, `undefined` 可由 `_type` 直接表示。 ```c++ namespace se { @@ -131,17 +131,17 @@ namespace se { } ``` -如果se::Value中保存基础数据类型,比如`number`,`string`,`boolean`,其内部是直接存储一份值副本。 -`object`的存储比较特殊,是通过`se::Object*`对JS对象的弱引用(weak reference)。 +如果 se::Value 中保存基础数据类型,比如 `number`,`string`,`boolean`,其内部是直接存储一份值副本。 +`object` 的存储比较特殊,是通过 `se::Object*` 对 JS 对象的弱引用(weak reference)。 #### se::Object -se::Object继承于se::RefCounter引用计数管理类。目前抽象层中只有se::Object继承于se::RefCounter。 -上一小节我们说到,se::Object是保存了对JS对象的弱引用,这里笔者有必要解释一下为什么是弱引用。 +se::Object 继承于 se::RefCounter 引用计数管理类。目前抽象层中只有 se::Object 继承于 se::RefCounter。 +上一小节我们说到,se::Object 是保存了对 JS 对象的弱引用,这里笔者有必要解释一下为什么是弱引用。 -* 原因一:JS对象控制CPP对象的生命周期的需要 +* 原因一:JS 对象控制 CPP 对象的生命周期的需要 -当在脚本层中通过`var sp = new cc.Sprite("a.png");`创建了一个Sprite后,在构造回调函数绑定中我们会创建一个se::Object并保留在一个全局的map(NativePtrToObjectMap)中,此map用于查询`cocos2d::Sprite*`指针获取对应的JS对象`se::Object*`。 +当在脚本层中通过 `var sp = new cc.Sprite("a.png");` 创建了一个 Sprite 后,在构造回调函数绑定中我们会创建一个 se::Object 并保留在一个全局的 map (NativePtrToObjectMap) 中,此 map 用于查询 `cocos2d::Sprite*` 指针获取对应的 JS 对象 `se::Object*` 。 ```c++ static bool js_cocos2d_Sprite_finalize(se::State& s) @@ -158,26 +158,26 @@ SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize) static bool js_cocos2dx_Sprite_constructor(se::State& s) { - cocos2d::Sprite* cobj = new (std::nothrow) cocos2d::Sprite(); // cobj将在finalize函数中被释放 - s.thisObject()->setPrivateData(cobj); // setPrivateData内部会去保存cobj到NativePtrToObjectMap中 + cocos2d::Sprite* cobj = new (std::nothrow) cocos2d::Sprite(); // cobj 将在 finalize 函数中被释放 + s.thisObject()->setPrivateData(cobj); // setPrivateData 内部会去保存 cobj 到 NativePtrToObjectMap 中 return true; } SE_BIND_CTOR(js_cocos2dx_Sprite_constructor, __jsb_cocos2d_Sprite_class, js_cocos2d_Sprite_finalize) ``` -设想如果强制要求se::Object为JS对象的强引用(strong reference),即让JS对象不受GC控制,由于se::Object一直存在于map中,finalize回调将永远无法被触发,从而导致内存泄露。 +设想如果强制要求 se::Object 为 JS 对象的强引用(strong reference),即让 JS 对象不受 GC 控制,由于 se::Object 一直存在于 map 中,finalize 回调将永远无法被触发,从而导致内存泄露。 -正是由于se::Object保存的是JS对象的弱引用,JS对象控制CPP对象的生命周期才能够实现。以上代码中,当JS对象被释放后,会触发finalize回调,开发者只需要在`js_cocos2d_Sprite_finalize`中释放对应的c++对象即可,se::Object的释放已经被包含在`SE_BIND_FINALIZE_FUNC`宏中自动处理,开发者无需管理在`JS对象控制CPP对象`模式中se::Object的释放,但是在`CPP对象控制JS对象`模式中,开发者需要管理对se::Object的释放,具体下一节中会举例说明。 +正是由于 se::Object 保存的是 JS 对象的弱引用,JS 对象控制 CPP 对象的生命周期才能够实现。以上代码中,当 JS 对象被释放后,会触发 finalize 回调,开发者只需要在 `js_cocos2d_Sprite_finalize` 中释放对应的 c++ 对象即可,se::Object 的释放已经被包含在 `SE_BIND_FINALIZE_FUNC` 宏中自动处理,开发者无需管理在`JS 对象控制 CPP 对象`模式中 se::Object 的释放,但是在 `CPP 对象控制 JS 对象` 模式中,开发者需要管理对 se::Object 的释放,具体下一节中会举例说明。 -* 原因二:更加灵活,手动调用root方法以支持强引用 +* 原因二:更加灵活,手动调用 root 方法以支持强引用 -se::Object中提供了root/unroot方法供开发者调用,root会把JS对象放入到不受GC扫描到的区域,调用root后,se::Object就强引用了JS对象,只有当unroot被调用,或者se::Object被释放后,JS对象才会放回到受GC扫描到的区域。 +se::Object 中提供了 root/unroot 方法供开发者调用,root 会把 JS 对象放入到不受 GC 扫描到的区域,调用 root 后,se::Object 就强引用了 JS 对象,只有当 unroot 被调用,或者 se::Object 被释放后,JS 对象才会放回到受 GC 扫描到的区域。 -一般情况下,如果对象是非`cocos2d::Ref`的子类,会采用CPP对象控制JS对象的生命周期的方式去绑定。引擎内spine, dragonbones, box2d,anysdk等第三方库的绑定就是采用此方式。当CPP对象被释放的时候,需要在NativePtrToObjectMap中查找对应的se::Object,然后手动unroot和decRef。以spine中spTrackEntry的绑定为例: +一般情况下,如果对象是非 `cocos2d::Ref` 的子类,会采用 CPP 对象控制 JS 对象的生命周期的方式去绑定。引擎内 spine, dragonbones, box2d,anysdk 等第三方库的绑定就是采用此方式。当 CPP 对象被释放的时候,需要在 NativePtrToObjectMap 中查找对应的 se::Object,然后手动 unroot 和 decRef。以 spine 中 spTrackEntry 的绑定为例: ```c++ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ - // spTrackEntry的销毁回调 + // spTrackEntry 的销毁回调 auto cleanup = [entry](){ if (!se::ScriptEngine::getInstance()->isValid()) @@ -191,13 +191,13 @@ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ { CCLOG("spTrackEntry %p was recycled!", entry); se::Object* seObj = iter->second; - seObj->clearPrivateData(); // 解除mapping关系 - seObj->unroot(); // unroot,使JS对象受GC管理 - seObj->decRef(); // 释放se::Object + seObj->clearPrivateData(); // 解除 mapping 关系 + seObj->unroot(); // unroot,使 JS 对象受 GC 管理 + seObj->decRef(); // 释放 se::Object } }; - // 确保不再垃圾回收中去操作JS引擎的API + // 确保不再垃圾回收中去操作 JS 引擎的 API if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) { cleanup(); @@ -212,18 +212,18 @@ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ __对象类型__ -绑定对象的创建已经被隐藏在对应的`SE_BIND_CTOR`和`SE_BIND_SUB_CLS_CTOR`函数中,开发者在绑定回调中如果需要用到当前对象对应的se::Object,只需要通过s.thisObject()即可获取。其中s为se::State类型,具体会在后续章节中说明。 +绑定对象的创建已经被隐藏在对应的 `SE_BIND_CTOR` 和 `SE_BIND_SUB_CLS_CTOR` 函数中,开发者在绑定回调中如果需要用到当前对象对应的 se::Object,只需要通过 s.thisObject() 即可获取。其中 s 为 se::State 类型,具体会在后续章节中说明。 -此外,se::Object目前支持以下几种对象的手动创建: +此外,se::Object 目前支持以下几种对象的手动创建: -* Plain Object : 通过se::Object::createPlainObject创建, 类似JS中的`var a = {};` -* Array Object : 通过se::Object::createArrayObject创建,类似JS中的`var a = [];` -* Uint8 Typed Array Object : 通过se::Object::createUint8TypedArray创建,类似JS中的`var a = new Uint8Array(buffer);` -* Array Buffer Object : 通过se::Object::createArrayBufferObject,类似JS中的`var a = new ArrayBuffer(len);` +* Plain Object : 通过 se::Object::createPlainObject 创建,类似 JS 中的 `var a = {};` +* Array Object : 通过 se::Object::createArrayObject 创建,类似 JS 中的 `var a = [];` +* Uint8 Typed Array Object : 通过 se::Object::createUint8TypedArray 创建,类似 JS 中的 `var a = new Uint8Array(buffer);` +* Array Buffer Object : 通过 se::Object::createArrayBufferObject,类似 JS 中的 `var a = new ArrayBuffer(len);` __手动创建对象的释放__ -se::Object::createXXX方法与cocos2d-x中的create方法不同,抽象层是完全独立的一个模块,并不依赖与cocos2d-x的autorelease机制。虽然se::Object也是继承引用计数类,但开发者需要处理**手动创建出来的对象**的释放。 +se::Object::createXXX 方法与 cocos2d-x 中的 create 方法不同,抽象层是完全独立的一个模块,并不依赖与 cocos2d-x 的 autorelease 机制。虽然 se::Object 也是继承引用计数类,但开发者需要处理**手动创建出来的对象**的释放。 ```c++ se::Object* obj = se::Object::createPlainObject(); @@ -232,19 +232,19 @@ se::Object* obj = se::Object::createPlainObject(); obj->decRef(); // 释放引用,避免内存泄露 ``` -#### se::HandleObject (推荐的管理手动创建对象的辅助类) +#### se::HandleObject (推荐的管理手动创建对象的辅助类) -* 在比较复杂的逻辑中使用手动创建对象,开发者往往会忘记在不同的逻辑中处理decRef +* 在比较复杂的逻辑中使用手动创建对象,开发者往往会忘记在不同的逻辑中处理 decRef ```c++ bool foo() { se::Object* obj = se::Object::createPlainObject(); if (var1) - return false; // 这里直接返回了,忘记做decRef释放操作 + return false; // 这里直接返回了,忘记做 decRef 释放操作 if (var2) - return false; // 这里直接返回了,忘记做decRef释放操作 + return false; // 这里直接返回了,忘记做 decRef 释放操作 ... ... obj->decRef(); @@ -252,14 +252,14 @@ bool foo() } ``` -就算在不同的返回条件分支中加上了decRef也会导致逻辑复杂,难以维护,如果后期加入另外一个返回分支,很容易忘记decRef。 +就算在不同的返回条件分支中加上了 decRef 也会导致逻辑复杂,难以维护,如果后期加入另外一个返回分支,很容易忘记 decRef。 -* JS引擎在se::Object::createXXX后,如果由于某种原因JS引擎做了GC操作,导致后续使用的se::Object内部引用了一个非法指针,引发程序崩溃 +* JS 引擎在 se::Object::createXXX 后,如果由于某种原因 JS 引擎做了 GC 操作,导致后续使用的 se::Object 内部引用了一个非法指针,引发程序崩溃 -为了解决上述两个问题,抽象层定义了一个辅助管理**手动创建对象**的类型,即`se::HandleObject`。 +为了解决上述两个问题,抽象层定义了一个辅助管理**手动创建对象**的类型,即 `se::HandleObject` 。 -`se::HandleObject`是一个辅助类,用于更加简单地管理手动创建的se::Object对象的释放、root和unroot操作。 -以下两种代码写法是等价的,使用se::HandleObject的代码量明显少很多,而且更加安全。 +`se::HandleObject` 是一个辅助类,用于更加简单地管理手动创建的 se::Object 对象的释放、root 和 unroot 操作。 +以下两种代码写法是等价的,使用 se::HandleObject 的代码量明显少很多,而且更加安全。 ```c++ { @@ -272,52 +272,52 @@ bool foo() { se::Object* obj = se::Object::createPlainObject(); - obj->root(); // 在手动创建完对象后立马root,防止对象被GC + obj->root(); // 在手动创建完对象后立马 root,防止对象被 GC obj->setProperty(...); otherObject->setProperty("foo", se::Value(obj)); - obj->unroot(); // 当对象被使用完后,调用unroot + obj->unroot(); // 当对象被使用完后,调用 unroot obj->decRef(); // 引用计数减一,避免内存泄露 } ``` 注意: -* 不要尝试使用se::HandleObject创建一个native与JS的绑定对象,在JS控制CPP的模式中,绑定对象的释放会被抽象层自动处理,在CPP控制JS的模式中,前一章节中已经有描述了。 -* se::HandleObject对象只能够在栈上被分配,而且栈上构造的时候必须传入一个se::Object指针。 +* 不要尝试使用 se::HandleObject 创建一个 native 与 JS 的绑定对象,在 JS 控制 CPP 的模式中,绑定对象的释放会被抽象层自动处理,在 CPP 控制 JS 的模式中,前一章节中已经有描述了。 +* se::HandleObject 对象只能够在栈上被分配,而且栈上构造的时候必须传入一个 se::Object 指针。 #### se::Class -se::Class用于暴露CPP类到JS中,它会在JS中创建一个对应名称的constructor function。 +se::Class 用于暴露 CPP 类到 JS 中,它会在 JS 中创建一个对应名称的 constructor function。 它有如下方法: -* `static se::Class* create(className, obj, parentProto, ctor)`: 创建一个Class,注册成功后,在JS层中可以通过`var xxx = new SomeClass();`的方式创建一个对象 -* `bool defineFunction(name, func)`: 定义Class中的成员函数 -* `bool defineProperty(name, getter, setter)`: 定义Class属性读写器 -* `bool defineStaticFunction(name, func)`: 定义Class的静态成员函数,可通过SomeClass.foo()这种非new的方式访问,与类实例对象无关 -* `bool defineStaticProperty(name, getter, setter)`: 定义Class的静态属性读写器,可通过SomeClass.propertyA直接读写,与类实例对象无关 -* `bool defineFinalizeFunction(func)`: 定义JS对象被GC后的CPP回调 -* `bool install()`: 注册此类到JS虚拟机中 -* `Object* getProto()`: 获取注册到JS中的类(其实是JS的constructor)的prototype对象,类似function Foo(){}的Foo.prototype -* `const char* getName() const`: 获取当前Class的名称 +* `static se::Class* create(className, obj, parentProto, ctor)`: 创建一个 Class,注册成功后,在 JS 层中可以通过`var xxx = new SomeClass();`的方式创建一个对象 +* `bool defineFunction(name, func)`: 定义 Class 中的成员函数 +* `bool defineProperty(name, getter, setter)`: 定义 Class 属性读写器 +* `bool defineStaticFunction(name, func)`: 定义 Class 的静态成员函数,可通过 SomeClass.foo() 这种非 new 的方式访问,与类实例对象无关 +* `bool defineStaticProperty(name, getter, setter)`: 定义 Class 的静态属性读写器,可通过 SomeClass.propertyA 直接读写,与类实例对象无关 +* `bool defineFinalizeFunction(func)`: 定义 JS 对象被 GC 后的 CPP 回调 +* `bool install()`: 注册此类到 JS 虚拟机中 +* `Object* getProto()`: 获取注册到 JS 中的类(其实是 JS 的 constructor)的 prototype 对象,类似 function Foo(){}的 Foo.prototype +* `const char* getName() const`: 获取当前 Class 的名称 **注意:** -Class类型创建后,不需要手动释放内存,它会被封装层自动处理。 +Class 类型创建后,不需要手动释放内存,它会被封装层自动处理。 -更具体API说明可以翻看API文档或者代码注释 +更具体 API 说明可以翻看 API 文档或者代码注释 #### se::AutoHandleScope -se::AutoHandleScope对象类型完全是为了解决V8的兼容问题而引入的概念。 -V8中,当有CPP函数中需要触发JS相关操作,比如调用JS函数,访问JS属性等任何调用v8::Local<>的操作,V8强制要求在调用这些操作前必须存在一个v8::HandleScope作用域,否则会引发程序崩溃。 +se::AutoHandleScope 对象类型完全是为了解决 V8 的兼容问题而引入的概念。 +V8 中,当有 CPP 函数中需要触发 JS 相关操作,比如调用 JS 函数,访问 JS 属性等任何调用 v8::Local<> 的操作,V8 强制要求在调用这些操作前必须存在一个 v8::HandleScope 作用域,否则会引发程序崩溃。 -因此抽象层中引入了se::AutoHandleScope的概念,其只在V8上有实现,其他JS引擎目前都只是空实现。 +因此抽象层中引入了 se::AutoHandleScope 的概念,其只在 V8 上有实现,其他 JS 引擎目前都只是空实现。 -开发者需要记住,在任何代码执行中,需要调用JS的逻辑前,声明一个se::AutoHandleScope即可,比如: +开发者需要记住,在任何代码执行中,需要调用 JS 的逻辑前,声明一个 se::AutoHandleScope 即可,比如: ```c++ class SomeClass { @@ -336,14 +336,14 @@ class SomeClass { #### se::State -之前章节我们有提及State类型,它是绑定回调中的一个环境,我们通过se::State可以取得当前的CPP指针、se::Object对象指针、参数列表、返回值引用。 +之前章节我们有提及 State 类型,它是绑定回调中的一个环境,我们通过 se::State 可以取得当前的 CPP 指针、se::Object 对象指针、参数列表、返回值引用。 ```c++ bool foo(se::State& s) { - // 获取native对象指针 + // 获取 native 对象指针 SomeClass* cobj = (SomeClass*)s.nativeThisObject(); - // 获取se::Object对象指针 + // 获取 se::Object 对象指针 se::Object* thisObject = s.thisObject(); // 获取参数列表 const se::ValueArray& args = s.args(); @@ -354,11 +354,11 @@ bool foo(se::State& s) SE_BIND_FUNC(foo) ``` -## 抽象层依赖Cocos引擎么? +## 抽象层依赖 Cocos 引擎么? 不依赖。 -ScriptEngine这层设计之初就将其定义为一个独立模块,完全不依赖Cocos引擎。开发者完整可以通过copy、paste把cocos/scripting/js-bindings/jswrapper下的所有抽象层源码拷贝到其他项目中直接使用。 +ScriptEngine 这层设计之初就将其定义为一个独立模块,完全不依赖 Cocos 引擎。开发者完整可以通过 copy、paste 把 cocos/scripting/js-bindings/jswrapper 下的所有抽象层源码拷贝到其他项目中直接使用。 ## 手动绑定 @@ -370,7 +370,7 @@ static bool Foo_balabala(se::State& s) const auto& args = s.args(); int argc = (int)args.size(); - if (argc >= 2) // 这里约定参数个数必须大于等于2,否则抛出错误到JS层且返回false + if (argc >= 2) // 这里约定参数个数必须大于等于 2,否则抛出错误到 JS 层且返回 false { ... ... @@ -381,27 +381,27 @@ static bool Foo_balabala(se::State& s) return false; } -// 如果是绑定函数,则用SE_BIND_FUNC,构造函数、析构函数、子类构造函数等类似 +// 如果是绑定函数,则用 SE_BIND_FUNC,构造函数、析构函数、子类构造函数等类似 SE_BIND_FUNC(Foo_balabala) ``` -### 为JS对象设置一个属性值 +### 为 JS 对象设置一个属性值 ```c++ se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // 这里为了演示方便,获取全局对象 -globalObj->setProperty("foo", se::Value(100)); // 给全局对象设置一个foo属性,值为100 +globalObj->setProperty("foo", se::Value(100)); // 给全局对象设置一个 foo 属性,值为 100 ``` -在JS中就可以直接使用foo这个全局变量了 +在 JS 中就可以直接使用 foo 这个全局变量了 ```js cc.log("foo value: " + foo); // 打印出 foo value: 100 ``` -### 为JS对象定义一个属性读写回调 +### 为 JS 对象定义一个属性读写回调 ```c++ -// 全局对象的foo属性的读回调 +// 全局对象的 foo 属性的读回调 static bool Global_get_foo(se::State& s) { NativeObj* cobj = (NativeObj*)s.nativeThisObject(); @@ -411,7 +411,7 @@ static bool Global_get_foo(se::State& s) } SE_BIND_PROP_GET(Global_get_foo) -// 全局对象的foo属性的写回调 +// 全局对象的 foo 属性的写回调 static bool Global_set_foo(se::State& s) { const auto& args = s.args(); @@ -421,7 +421,7 @@ static bool Global_set_foo(se::State& s) NativeObj* cobj = (NativeObj*)s.nativeThisObject(); int32_t arg1 = args[0].toInt32(); cobj->setValue(arg1); - // void类型的函数,无需设置s.rval,未设置默认返回undefined给JS层 + // void 类型的函数,无需设置 s.rval,未设置默认返回 undefined 给 JS 层 return true; } @@ -433,11 +433,11 @@ SE_BIND_PROP_SET(Global_set_foo) void some_func() { se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // 这里为了演示方便,获取全局对象 - globalObj->defineProperty("foo", _SE(Global_get_foo), _SE(Global_set_foo)); // 使用_SE宏包装一下具体的函数名称 + globalObj->defineProperty("foo", _SE(Global_get_foo), _SE(Global_set_foo)); // 使用_SE 宏包装一下具体的函数名称 } ``` -### 为JS对象设置一个函数 +### 为 JS 对象设置一个函数 ```c++ static bool Foo_function(se::State& s) @@ -450,12 +450,12 @@ SE_BIND_FUNC(Foo_function) void some_func() { se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // 这里为了演示方便,获取全局对象 - globalObj->defineFunction("foo", _SE(Foo_function)); // 使用_SE宏包装一下具体的函数名称 + globalObj->defineFunction("foo", _SE(Foo_function)); // 使用_SE 宏包装一下具体的函数名称 } ``` -### 注册一个CPP类到JS虚拟机中 +### 注册一个 CPP 类到 JS 虚拟机中 ```c++ static se::Object* __jsb_ns_SomeClass_proto = nullptr; @@ -557,39 +557,39 @@ SE_BIND_FUNC(js_SomeClass_static_func) bool js_register_ns_SomeClass(se::Object* global) { - // 保证namespace对象存在 + // 保证 namespace 对象存在 se::Value nsVal; if (!global->getProperty("ns", &nsVal)) { - // 不存在则创建一个JS对象,相当于 var ns = {}; + // 不存在则创建一个 JS 对象,相当于 var ns = {}; se::HandleObject jsobj(se::Object::createPlainObject()); nsVal.setObject(jsobj); - // 将ns对象挂载到global对象中,名称为ns + // 将 ns 对象挂载到 global 对象中,名称为 ns global->setProperty("ns", nsVal); } se::Object* ns = nsVal.toObject(); - // 创建一个Class对象,开发者无需考虑Class对象的释放,其交由ScriptEngine内部自动处理 - auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // 如果无构造函数,最后一个参数可传入nullptr,则这个类在JS中无法被new SomeClass()出来 + // 创建一个 Class 对象,开发者无需考虑 Class 对象的释放,其交由 ScriptEngine 内部自动处理 + auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // 如果无构造函数,最后一个参数可传入 nullptr,则这个类在 JS 中无法被 new SomeClass()出来 - // 为这个Class对象定义成员函数、属性、静态函数、析构函数 + // 为这个 Class 对象定义成员函数、属性、静态函数、析构函数 cls->defineFunction("foo", _SE(js_SomeClass_foo)); cls->defineProperty("xxx", _SE(js_SomeClass_get_xxx), _SE(js_SomeClass_set_xxx)); cls->defineFinalizeFunction(_SE(js_SomeClass_finalize)); - // 注册类型到JS VirtualMachine的操作 + // 注册类型到 JS VirtualMachine 的操作 cls->install(); - // JSBClassType为Cocos引擎绑定层封装的类型注册的辅助函数,此函数不属于ScriptEngine这层 + // JSBClassType 为 Cocos 引擎绑定层封装的类型注册的辅助函数,此函数不属于 ScriptEngine 这层 JSBClassType::registerClass(cls); // 保存注册的结果,便于其他地方使用,比如类继承 __jsb_ns_SomeClass_proto = cls->getProto(); __jsb_ns_SomeClass_class = cls; - // 为每个此Class实例化出来的对象附加一个属性 + // 为每个此 Class 实例化出来的对象附加一个属性 __jsb_ns_SomeClass_proto->setProperty("yyy", se::Value("helloyyy")); // 注册静态成员变量和静态成员函数 @@ -606,7 +606,7 @@ bool js_register_ns_SomeClass(se::Object* global) } ``` -### 如何绑定CPP接口中的回调函数? +### 如何绑定 CPP 接口中的回调函数? ```c++ static bool js_SomeClass_setCallback(se::State& s) @@ -628,21 +628,21 @@ static bool js_SomeClass_setCallback(se::State& s) { assert(jsFunc.isObject() && jsFunc.toObject()->isFunction()); - // 如果当前SomeClass是可以被new出来的类,我们 使用se::Object::attachObject把jsFunc和jsTarget关联到当前对象中 + // 如果当前 SomeClass 是可以被 new 出来的类,我们 使用 se::Object::attachObject 把 jsFunc 和 jsTarget 关联到当前对象中 s.thisObject()->attachObject(jsFunc.toObject()); s.thisObject()->attachObject(jsTarget.toObject()); - // 如果当前SomeClass类是一个单例类,或者永远只有一个实例的类,我们不能用se::Object::attachObject去关联 - // 必须使用se::Object::root,开发者无需关系unroot,unroot的操作会随着lambda的销毁触发jsFunc的析构,在se::Object的析构函数中进行unroot操作。 - // js_cocos2dx_EventDispatcher_addCustomEventListener的绑定代码就是使用此方式,因为EventDispatcher始终只有一个实例, - // 如果使用s.thisObject->attachObject(jsFunc.toObject);会导致对应的func和target永远无法被释放,引发内存泄露。 + // 如果当前 SomeClass 类是一个单例类,或者永远只有一个实例的类,我们不能用 se::Object::attachObject 去关联 + // 必须使用 se::Object::root,开发者无需关系 unroot,unroot 的操作会随着 lambda 的销毁触发 jsFunc 的析构,在 se::Object 的析构函数中进行 unroot 操作。 + // js_cocos2dx_EventDispatcher_addCustomEventListener 的绑定代码就是使用此方式,因为 EventDispatcher 始终只有一个实例, + // 如果使用 s.thisObject->attachObject(jsFunc.toObject);会导致对应的 func 和 target 永远无法被释放,引发内存泄露。 // jsFunc.toObject()->root(); // jsTarget.toObject()->root(); cobj->setCallback([jsFunc, jsTarget](int counter){ - // CPP回调函数中要传递数据给JS或者调用JS函数,在回调函数开始需要添加如下两行代码。 + // CPP 回调函数中要传递数据给 JS 或者调用 JS 函数,在回调函数开始需要添加如下两行代码。 se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; @@ -663,7 +663,7 @@ static bool js_SomeClass_setCallback(se::State& s) SE_BIND_FUNC(js_SomeClass_setCallback) ``` -SomeClass类注册后,就可以在JS中这样使用了: +SomeClass 类注册后,就可以在 JS 中这样使用了: ```js var myObj = new ns.SomeClass(); @@ -692,10 +692,10 @@ SomeClass类注册后,就可以在JS中这样使用了: setTimeout(function(){ myObj.setCallback(null); - }, 6000); // 6秒后清空callback + }, 6000); // 6 秒后清空 callback ``` -Console中会输出: +Console 中会输出: ``` SomeClass::foo @@ -714,11 +714,11 @@ Delegate obj, onCallback: 6, this.myVar: 105 setCallback(nullptr) ``` -### 如何使用cocos2d-x bindings这层的类型转换辅助函数? +### 如何使用 cocos2d-x bindings 这层的类型转换辅助函数? 类型转换辅助函数位于`cocos/scripting/js-bindings/manual/jsb_conversions.hpp/.cpp`中,其包含: -#### se::Value转换为C++类型 +#### se::Value 转换为 C++ 类型 ``` bool seval_to_int32(const se::Value& v, int32_t* ret); bool seval_to_uint32(const se::Value& v, uint32_t* ret); @@ -779,7 +779,7 @@ bool seval_to_Map_string_key(const se::Value& v, cocos2d::Map* r ``` -#### C++类型转换为se::Value +#### C++ 类型转换为 se::Value ```c++ bool int8_to_seval(int8_t v, se::Value* ret); @@ -871,8 +871,8 @@ bool b2AABB_to_seval(const b2AABB& v, se::Value* ret); ``` -辅助转换函数不属于`Script Engine Wrapper`抽象层,属于cocos2d-x绑定层,封装这些函数是为了在绑定代码中更加方便的转换。 -每个转换函数都返回`bool`类型,表示转换是否成功,开发者如果调用这些接口,需要去判断这个返回值。 +辅助转换函数不属于`Script Engine Wrapper`抽象层,属于 cocos2d-x 绑定层,封装这些函数是为了在绑定代码中更加方便的转换。 +每个转换函数都返回 `bool` 类型,表示转换是否成功,开发者如果调用这些接口,需要去判断这个返回值。 以上接口,直接根据接口名称即可知道具体的用法,接口中第一个参数为输入,第二个参数为输出参数。用法如下: @@ -886,27 +886,27 @@ int32_t v; bool ok = seval_to_int32(args[0], &v); // 第二个参数为输出参数,传入输出参数的地址 ``` -#### (IMPORTANT)理解native\_ptr\_to\_seval与native\_ptr\_to\_rooted\_seval的区别 +#### (IMPORTANT)理解 native\_ptr\_to\_seval 与 native\_ptr\_to\_rooted\_seval 的区别 -**开发者一定要理解清楚这二者的区别,才不会因为误用导致JS层内存泄露这种比较难查的bug。** +**开发者一定要理解清楚这二者的区别,才不会因为误用导致 JS 层内存泄露这种比较难查的 bug。** -* `native_ptr_to_seval`用于`JS控制CPP对象生命周期`的模式。当在绑定层需要根据一个CPP对象指针获取一个se::Value的时候,可调用此方法。引擎内大部分继承于`cocos2d::Ref`的子类都采取这种方式去获取se::Value。记住一点,当你管理的绑定对象是由JS控制生命周期,需要转换为seval的时候,请用此方法,否则考虑用`native_ptr_to_rooted_seval`。 -* `native_ptr_to_rooted_seval`用于`CPP控制JS对象生命周期`的模式。一般而言,第三方库中的对象绑定都会用到此方法。此方法会根据传入的CPP对象指针查找cache住的se::Object,如果不存在,则创建一个rooted的se::Object,即这个创建出来的JS对象将不受GC控制,并永远在内存中。开发者需要监听CPP对象的释放,并在释放的时候去做se::Object的unroot操作,具体可参照前面章节中描述的spTrackEntry_setDisposeCallback中的内容。 +* `native_ptr_to_seval` 用于 `JS 控制 CPP 对象生命周期` 的模式。当在绑定层需要根据一个 CPP 对象指针获取一个 se::Value 的时候,可调用此方法。引擎内大部分继承于 `cocos2d::Ref` 的子类都采取这种方式去获取 se::Value。记住一点,当你管理的绑定对象是由 JS 控制生命周期,需要转换为 seval 的时候,请用此方法,否则考虑用 `native_ptr_to_rooted_seval` 。 +* `native_ptr_to_rooted_seval`用于`CPP 控制 JS 对象生命周期`的模式。一般而言,第三方库中的对象绑定都会用到此方法。此方法会根据传入的 CPP 对象指针查找 cache 住的 se::Object,如果不存在,则创建一个 rooted 的 se::Object,即这个创建出来的 JS 对象将不受 GC 控制,并永远在内存中。开发者需要监听 CPP 对象的释放,并在释放的时候去做 se::Object 的 unroot 操作,具体可参照前面章节中描述的 spTrackEntry_setDisposeCallback 中的内容。 ## 自动绑定 -### 配置模块ini文件 +### 配置模块 ini 文件 -配置方法与1.6中的方法相同,主要注意的是:1.7中废弃了`script_control_cpp`,因为`script_control_cpp`字段会影响到整个模块,如果模块中需要绑定cocos2d::Ref子类和非cocos::Ref子类,原来的绑定配置则无法满足需求。1.7中取而代之的新字段为`classes_owned_by_cpp`,表示哪些类是需要由CPP来控制JS对象的生命周期。 +配置方法与 1.6 中的方法相同,主要注意的是:1.7 中废弃了 `script_control_cpp` ,因为 `script_control_cpp` 字段会影响到整个模块,如果模块中需要绑定 cocos2d::Ref 子类和非 cocos::Ref 子类,原来的绑定配置则无法满足需求。1.7 中取而代之的新字段为 `classes_owned_by_cpp` ,表示哪些类是需要由 CPP 来控制 JS 对象的生命周期。 -1.7中另外加入的一个配置字段为`persistent_classes`, 用于表示哪些类是在游戏运行中一直存在的,比如:TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler +1.7 中另外加入的一个配置字段为 `persistent_classes` , 用于表示哪些类是在游戏运行中一直存在的,比如:TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler -其他字段与1.6一致。 +其他字段与 1.6 一致。 -具体可以参考引擎目录下的tools/tojs/cocos2dx.ini等ini配置。 +具体可以参考引擎目录下的 tools/tojs/cocos2dx.ini 等 ini 配置。 -### 理解ini文件中每个字段的意义 +### 理解 ini 文件中每个字段的意义 ``` # 模块名称 @@ -915,19 +915,19 @@ bool ok = seval_to_int32(args[0], &v); // 第二个参数为输出参数,传 # 绑定回调函数的前缀,也是生成的自动绑定文件的前缀 prefix = cocos2dx -# 绑定的类挂载在JS中的哪个对象中,类似命名空间 +# 绑定的类挂载在 JS 中的哪个对象中,类似命名空间 target_namespace = cc -# 自动绑定工具基于Android编译环境,此处配置Android头文件搜索路径 +# 自动绑定工具基于 Android 编译环境,此处配置 Android 头文件搜索路径 android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/include -# 配置Android编译参数 +# 配置 Android 编译参数 android_flags = -D_SIZE_T_DEFINED_ -# 配置clang头文件搜索路径 +# 配置 clang 头文件搜索路径 clang_headers = -I%(clangllvmdir)s/%(clang_include)s -# 配置clang编译参数 +# 配置 clang 编译参数 clang_flags = -nostdinc -x c++ -std=c++11 -U __SSE__ # 配置引擎的头文件搜索路径 @@ -948,7 +948,7 @@ replace_headers=CCProtectedNode.h::2d/CCProtectedNode.h,CCAsyncTaskPool.h::base/ # 需要绑定哪些类,可以使用正则表达式,以空格为间隔 classes = -# 哪些类需要在JS层通过cc.Class.extend,以空格为间隔 +# 哪些类需要在 JS 层通过 cc.Class.extend,以空格为间隔 classes_need_extend = # 需要为哪些类绑定属性,以逗号为间隔 @@ -973,19 +973,19 @@ classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo A # 配置哪些父类需要被忽略 base_classes_to_skip = Ref Clonable -# 配置哪些类是抽象类,抽象类没有构造函数,即在js层无法通过var a = new SomeClass();的方式构造JS对象 +# 配置哪些类是抽象类,抽象类没有构造函数,即在 js 层无法通过 var a = new SomeClass();的方式构造 JS 对象 abstract_classes = Director SpriteFrameCache Set SimpleAudioEngine # 配置哪些类是始终以一个实例的方式存在的,游戏运行过程中不会被销毁 persistent_classes = TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler -# 配置哪些类是需要由CPP对象来控制JS对象生命周期的,未配置的类,默认采用JS控制CPP对象生命周期 +# 配置哪些类是需要由 CPP 对象来控制 JS 对象生命周期的,未配置的类,默认采用 JS 控制 CPP 对象生命周期 classes_owned_by_cpp = ``` -## 远程调试与Profile +## 远程调试与 Profile -默认远程调试和Profile是在debug模式中生效的,如果需要在release模式下也启用,需要手动修改cocos/scripting/js-bindings/jswrapper/config.hpp中的宏开关。 +默认远程调试和 Profile 是在 debug 模式中生效的,如果需要在 release 模式下也启用,需要手动修改 cocos/scripting/js-bindings/jswrapper/config.hpp 中的宏开关。 ```c++ #if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0 @@ -1000,7 +1000,7 @@ classes_owned_by_cpp = 改为: ```c++ -#if 1 // 这里改为1,强制启用调试 +#if 1 // 这里改为 1,强制启用调试 #define SE_ENABLE_INSPECTOR 1 #define SE_DEBUG 2 #else @@ -1009,17 +1009,17 @@ classes_owned_by_cpp = #endif ``` -### Chrome远程调试V8 +### Chrome 远程调试 V8 #### Windows -* 编译、运行游戏(或在Creator中直接使用模拟器运行) -* 用Chrome浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008) +* 编译、运行游戏(或在 Creator 中直接使用模拟器运行) +* 用 Chrome 浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008) 断点调试: ![](v8-win32-debug.jpg) -抓取JS Heap +抓取 JS Heap ![](v8-win32-memory.jpg) Profile @@ -1027,46 +1027,48 @@ Profile #### Android -* 保证Android设备与PC或者Mac在同一个局域网中 +* 保证 Android 设备与 PC 或者 Mac 在同一个局域网中 * 编译,运行游戏 -* 用Chrome浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008), 其中`xxx.xxx.xxx.xxx`为局域网中Android设备的IP地址 -* 调试界面与Windows相同 +* 用 Chrome 浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008), 其中 `xxx.xxx.xxx.xxx` 为局域网中 Android 设备的 IP 地址 +* 调试界面与 Windows 相同 -### Safari远程调试JavaScriptCore +### Safari 远程调试 JavaScriptCore #### macOS -1. 打开Mac上的Safari,偏好设置 -> 高级 -> 显示开发者选项 -2. 为Xcode工程添加entitlements文件,如果entitlements存在则跳过此步骤。如果不存在,则到工程的Capabilities设置中打开App Sandbox,然后再关闭,这时.entitlements文件会自动被添加进工程。![](jsc-entitlements.png),还需要确保Build Setting里面Code Signing Entitlemenets选项中包含entitlements文件。 ![](jsc-entitlements-check.png) -3. 打开entitlements文件,添加com.apple.security.get-task-allow,值类型为Boolean,值为YES. ![](jsc-security-key.png) -4. 编译、运行游戏 -5. 如果是直接在Creator的模拟器中运行,则可以跳过第2,3,4步骤 -6. Safari菜单中选择Develop -> 你的Mac设备名称 -> Cocos2d-x JSB 会自动打开Web Inspector页面,然后即可进行设置断点、Timeline profile、console等操作。![](jsc-mac-debug.png) ![](jsc-breakpoint.png) ![](jsc-timeline.png) +1. 打开 Mac 上的 Safari,偏好设置 -> 高级 -> 显示开发者选项 +2. 为 Xcode 工程添加 entitlements 文件,如果 entitlements 存在则跳过此步骤。如果不存在,则到工程的 Capabilities 设置中打开 App Sandbox,然后再关闭,这时 .entitlements 文件会自动被添加进工程。![](jsc-entitlements.png),还需要确保 Build Setting 里面 Code Signing Entitlemenets 选项中包含 entitlements 文件。 ![](jsc-entitlements-check.png) +3. 打开 entitlements 文件,添加 com.apple.security.get-task-allow,值类型为 Boolean,值为 YES. ![](jsc-security-key.png) +4. 签名 : General -> 选择你的 Mac 工程 -> Signing -> 选择你的开发者证书 +5. 编译、运行游戏 +6. 如果是直接在 Creator 的模拟器中运行,则可以跳过第 2,3,4,5 步骤 +7. Safari 菜单中选择 Develop -> 你的 Mac 设备名称 -> Cocos2d-x JSB 会自动打开 Web Inspector 页面,然后即可进行设置断点、Timeline profile、console 等操作。![](jsc-mac-debug.png) ![](jsc-breakpoint.png) ![](jsc-timeline.png) **注意** -如果开发者有修改引擎源码或者自己合并了一些Patch,需要重新编译模拟器,记得重新设置一下模拟器工程的证书。 +如果开发者有修改引擎源码或者自己合并了一些 Patch,需要重新编译模拟器,记得重新设置一下模拟器工程的证书。 ![](jsc-mac-simulator-sign.png) -然后再调用`gulp gen-simulator`生成模拟器。 +然后再调用 `gulp gen-simulator` 生成模拟器。 #### iOS -1. 先打开iPhone的设置 -> Safari -> 高级 -> Web检查器 -2. 为Xcode工程添加entitlements文件,如果entitlements存在则跳过此步骤。如果不存在,则到工程的Capabilities设置中打开App Sandbox,然后再关闭,这时.entitlements文件会自动被添加进工程。 (图示与macOS的第2步类似) -3. 打开entitlements文件,添加com.apple.security.get-task-allow,值类型为Boolean,值为YES。(图示与macOS的第3步类似) -4. 编译、运行游戏 -5. Safari菜单中选择Develop -> 你的iPhone设备名称 -> Cocos2d-x JSB 会自动打开Web Inspector页面,然后即可进行设置断点、Timeline profile、console等操作。(图示与macOS的第6步类似) +1. 先打开 iPhone 的设置 -> Safari -> 高级 -> Web 检查器 +2. 为 Xcode 工程添加 entitlements 文件,如果 entitlements 存在则跳过此步骤。如果不存在,则到工程的 Capabilities 设置中打开 App Sandbox,然后再关闭,这时 .entitlements 文件会自动被添加进工程。 (图示与 macOS 的第 2 步类似) +3. 打开 entitlements 文件,添加 com.apple.security.get-task-allow,值类型为 Boolean,值为 YES。(图示与 macOS 的第 3 步类似) +4. 签名 : General -> 选择你的 iOS 工程 -> Signing -> 选择你的开发者证书 +5. 编译、运行游戏 +6. Safari 菜单中选择 Develop -> 你的 iPhone 设备名称 -> Cocos2d-x JSB 会自动打开 Web Inspector 页面,然后即可进行设置断点、Timeline profile、console 等操作。(图示与 macOS 的第 6 步类似) ## Q & A -### se::ScriptEngine与ScriptingCore的区别,为什么还要保留ScriptingCore? +### se::ScriptEngine 与 ScriptingCore 的区别,为什么还要保留 ScriptingCore? -在1.7中,抽象层被设计为一个与引擎没有关系的独立模块,对JS引擎的管理从ScriptingCore被移动到了se::ScriptEngine类中,ScriptingCore被保留下来是希望通过它把引擎的一些事件传递给封装层,充当适配器的角色。 +在 1.7 中,抽象层被设计为一个与引擎没有关系的独立模块,对 JS 引擎的管理从 ScriptingCore 被移动到了 se::ScriptEngine 类中,ScriptingCore 被保留下来是希望通过它把引擎的一些事件传递给封装层,充当适配器的角色。 -ScriptingCore只需要在AppDelegate中被使用一次即可, 之后的所有操作都只需要用到se::ScriptEngine。 +ScriptingCore 只需要在 AppDelegate 中被使用一次即可,之后的所有操作都只需要用到 se::ScriptEngine。 ```c++ bool AppDelegate::applicationDidFinishLaunching() @@ -1075,8 +1077,8 @@ bool AppDelegate::applicationDidFinishLaunching() ... director->setAnimationInterval(1.0 / 60); - // 这两行把ScriptingCore这个适配器设置给引擎,用于传递引擎的一些事件, - // 比如Node的onEnter, onExit, Action的update,JS对象的持有与解除持有 + // 这两行把 ScriptingCore 这个适配器设置给引擎,用于传递引擎的一些事件, + // 比如 Node 的 onEnter, onExit, Action 的 update,JS 对象的持有与解除持有 ScriptingCore* sc = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(sc); @@ -1085,34 +1087,34 @@ bool AppDelegate::applicationDidFinishLaunching() ... } ``` -### se::Object::root/unroot 与 se::Object::incRef/decRef的区别? +### se::Object::root/unroot 与 se::Object::incRef/decRef 的区别? -root/unroot用于控制JS对象是否受GC控制,root表示不受GC控制,unroot则相反,表示交由GC控制,对一个se::Object来说,root和unroot可以被调用多次,se::Object内部有_rootCount变量用于表示root的次数。当unroot被调用,且_rootCount为0时,se::Object关联的JS对象将交由GC管理。还有一种情况,即如果se::Object的析构被触发了,如果_rootCount > 0,则强制把JS对象交由GC控制。 +root/unroot 用于控制 JS 对象是否受 GC 控制,root 表示不受 GC 控制,unroot 则相反,表示交由 GC 控制,对一个 se::Object 来说,root 和 unroot 可以被调用多次,se::Object 内部有_rootCount 变量用于表示 root 的次数。当 unroot 被调用,且_rootCount 为 0 时,se::Object 关联的 JS 对象将交由 GC 管理。还有一种情况,即如果 se::Object 的析构被触发了,如果_rootCount > 0,则强制把 JS 对象交由 GC 控制。 -incRef/decRef用于控制se::Object这个`cpp`对象的生命周期,前面章节已经提及,建议用户使用se::HandleObject来控制`手动创建非绑定对象`的方式控制se::Object的生命周期。因此,一般情况下,开发者不需要接触到incRef/decRef。 +incRef/decRef 用于控制 se::Object 这个 `cpp` 对象的生命周期,前面章节已经提及,建议用户使用 se::HandleObject 来控制`手动创建非绑定对象`的方式控制 se::Object 的生命周期。因此,一般情况下,开发者不需要接触到 incRef/decRef。 ### 对象生命周期的关联与解除关联 se::Object::attachObject/dettachObject -`objA->attachObject(objB);`类似于JS中执行`objA.__nativeRefs[index] = objB`,只有当objA被GC后,objB才有可能被GC -`objA->dettachObject(objB);`类似于JS中执行`delete objA.__nativeRefs[index];`,这样objB的生命周期就不受objA控制了 +`objA->attachObject(objB);`类似于 JS 中执行`objA.__nativeRefs[index] = objB`,只有当 objA 被 GC 后,objB 才有可能被 GC +`objA->dettachObject(objB);`类似于 JS 中执行`delete objA.__nativeRefs[index];`,这样 objB 的生命周期就不受 objA 控制了 -### cocos2d::Ref子类与非cocos2d::Ref子类JS/CPP对象生命周期管理有何不同? +### cocos2d::Ref 子类与非 cocos2d::Ref 子类 JS/CPP 对象生命周期管理有何不同? -目前引擎中cocos2d::Ref子类的绑定采用JS对象控制CPP对象生命周期的方式,这样做的好处是,解决了一直以来被诟病的需要在JS层retain,release对象的烦恼。 +目前引擎中 cocos2d::Ref 子类的绑定采用 JS 对象控制 CPP 对象生命周期的方式,这样做的好处是,解决了一直以来被诟病的需要在 JS 层 retain,release 对象的烦恼。 -非cocos2d::Ref子类采用CPP对象控制JS对象生命周期的方式。此方式要求,CPP对象销毁后需要通知绑定层去调用对应se::Object的clearPrivateData, unroot, decRef的方法。JS代码中一定要慎重操作对象,当有可能出现非法对象的逻辑中,使用cc.sys.isObjectValid来判断CPP对象是否被释放了。 +非 cocos2d::Ref 子类采用 CPP 对象控制 JS 对象生命周期的方式。此方式要求,CPP 对象销毁后需要通知绑定层去调用对应 se::Object 的 clearPrivateData, unroot, decRef 的方法。JS 代码中一定要慎重操作对象,当有可能出现非法对象的逻辑中,使用 cc.sys.isObjectValid 来判断 CPP 对象是否被释放了。 -### 绑定cocos2d::Ref子类的析构函数需要注意的事项 +### 绑定 cocos2d::Ref 子类的析构函数需要注意的事项 -如果在JS对象的finalize回调中调用任何JS引擎的API,可能导致崩溃。因为当前引擎正在进行垃圾回收的流程,无法被打断处理其他操作。 -finalize回调中是告诉CPP层是否对应的CPP对象的内存,不能在CPP对象的析构中又去操作JS引擎API。 +如果在 JS 对象的 finalize 回调中调用任何 JS 引擎的 API,可能导致崩溃。因为当前引擎正在进行垃圾回收的流程,无法被打断处理其他操作。 +finalize 回调中是告诉 CPP 层是否对应的 CPP 对象的内存,不能在 CPP 对象的析构中又去操作 JS 引擎 API。 那如果必须调用,应该如何处理? -cocos2d-x的绑定中,如果引用计数为1了,我们不使用release,而是使用autorelease延时CPP类的析构到帧结束去执行。 +cocos2d-x 的绑定中,如果引用计数为 1 了,我们不使用 release,而是使用 autorelease 延时 CPP 类的析构到帧结束去执行。 ```c++ static bool js_cocos2d_Sprite_finalize(se::State& s) @@ -1128,9 +1130,9 @@ static bool js_cocos2d_Sprite_finalize(se::State& s) SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize) ``` -### 请不要在栈(Stack)上分配cocos2d::Ref的子类对象 +### 请不要在栈(Stack)上分配 cocos2d::Ref 的子类对象 -Ref的子类必须在堆(Heap)上分配,即通过`new`,然后通过`release`来释放。当JS对象的finalize回调函数中统一使用`autorelease`或`release`来释放。如果是在栈上的对象,reference count很有可能为0,而这时调用`release`,其内部会调用`delete`,从而导致程序崩溃。所以为了防止这个行为的出现,开发者可以在继承于cocos2d::Ref的绑定类中,标识析构函数为`protected`或者`private`,保证在编译阶段就能发现这个问题。 +Ref 的子类必须在堆(Heap)上分配,即通过 `new` ,然后通过 `release` 来释放。当 JS 对象的 finalize 回调函数中统一使用 `autorelease` 或 `release` 来释放。如果是在栈上的对象,reference count 很有可能为 0,而这时调用 `release` ,其内部会调用 `delete` ,从而导致程序崩溃。所以为了防止这个行为的出现,开发者可以在继承于 cocos2d::Ref 的绑定类中,标识析构函数为 `protected` 或者 `private` ,保证在编译阶段就能发现这个问题。 例如: @@ -1160,7 +1162,7 @@ event->release(); ### 如何监听脚本错误 -在AppDelegate.cpp中通过se::ScriptEngine::getInstance()->setExceptionCallback(...)设置JS层异常回调。 +在 AppDelegate.cpp 中通过 se::ScriptEngine::getInstance()->setExceptionCallback(...)设置 JS 层异常回调。 ```c++ bool AppDelegate::applicationDidFinishLaunching() diff --git a/native/cocos/scripting/js-bindings/jswrapper/HandleObject.cpp b/native/cocos/scripting/js-bindings/jswrapper/HandleObject.cpp index 86c54e812a..af1c2e8116 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/HandleObject.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/HandleObject.cpp @@ -1,11 +1,26 @@ -// -// HandleObject.cpp -// cocos2d_js_bindings -// -// Created by James Chen on 7/31/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "HandleObject.hpp" #include "Object.hpp" @@ -16,6 +31,8 @@ HandleObject::HandleObject(Object* obj) { if (_obj != nullptr) { + // se::HandleObject could not be used for native binding object. + assert(!_obj->_getClass()); _obj->root(); } } diff --git a/native/cocos/scripting/js-bindings/jswrapper/HandleObject.hpp b/native/cocos/scripting/js-bindings/jswrapper/HandleObject.hpp index 8469fe534d..3271383b65 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/HandleObject.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/HandleObject.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include diff --git a/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.cpp b/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.cpp index 6894ff7b6e..38c2d87e8d 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.cpp @@ -1,11 +1,26 @@ -// -// MappingUtils.cpp -// cocos2d_js_bindings -// -// Created by James Chen on 8/17/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "MappingUtils.hpp" namespace se { diff --git a/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.hpp b/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.hpp index d5f8edd680..b0e92b84ce 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/MappingUtils.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include diff --git a/native/cocos/scripting/js-bindings/jswrapper/Object.hpp b/native/cocos/scripting/js-bindings/jswrapper/Object.hpp index 401fc2e413..7c7ddc1073 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/Object.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/Object.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "config.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/RefCounter.cpp b/native/cocos/scripting/js-bindings/jswrapper/RefCounter.cpp index 3e09f18d00..74225ae287 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/RefCounter.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/RefCounter.cpp @@ -1,11 +1,26 @@ -// -// Ref.cpp -// cocos2d_js_bindings -// -// Created by James Chen on 4/27/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "RefCounter.hpp" namespace se { diff --git a/native/cocos/scripting/js-bindings/jswrapper/RefCounter.hpp b/native/cocos/scripting/js-bindings/jswrapper/RefCounter.hpp index 09a52ed911..2796c98e41 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/RefCounter.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/RefCounter.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once namespace se { diff --git a/native/cocos/scripting/js-bindings/jswrapper/SeApi.h b/native/cocos/scripting/js-bindings/jswrapper/SeApi.h index 0d4742397b..334ece4f80 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/SeApi.h +++ b/native/cocos/scripting/js-bindings/jswrapper/SeApi.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "config.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/State.cpp b/native/cocos/scripting/js-bindings/jswrapper/State.cpp index 35eff86cc2..482d3d46d0 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/State.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/State.cpp @@ -1,11 +1,26 @@ -// -// State.cpp -// cocos2d_js_bindings -// -// Created by guanghui on 5/27/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "State.hpp" #include "Object.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/State.hpp b/native/cocos/scripting/js-bindings/jswrapper/State.hpp index 16a7798919..0be6c5415f 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/State.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/State.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "Value.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/Value.cpp b/native/cocos/scripting/js-bindings/jswrapper/Value.cpp index b8d0ecbb30..7a1bb6d3fd 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/Value.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/Value.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Value.hpp" #include "Object.hpp" @@ -496,14 +519,7 @@ namespace se { } else if (_type == Type::Object) { - if (toObject()->isFunction()) - { - ret = "[Object function]"; - } - else - { - ret = "[Object object]"; - } + ret = toObject()->toString(); } else if (_type == Type::Null) { @@ -513,6 +529,10 @@ namespace se { { ret = "undefined"; } + else + { + assert(false); + } return ret; } diff --git a/native/cocos/scripting/js-bindings/jswrapper/Value.hpp b/native/cocos/scripting/js-bindings/jswrapper/Value.hpp index 78ece40579..5980fd9cb7 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/Value.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/Value.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Base.h b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Base.h index c80b0eef08..6dd12b3abd 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Base.h +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Base.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.cpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.cpp index 09db1b8945..7116fb9986 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Class.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.hpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.hpp index 947cb97af8..eec2ccf90e 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Class.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -10,27 +33,88 @@ namespace se { class Object; + /** + * se::Class represents a definition of how to create a native binding object. + */ class Class final { - private: - Class(); - ~Class(); public: - + /** + * @brief Creates a class used for creating relevant native binding objects. + * @param[in] className A null-terminated UTF8 string containing the class's name. + * @param[in] obj The object that current class proto object attaches to. Should not be nullptr. + * @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent. + * @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor. + * @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 std::string& className, Object* obj, Object* parentProto, JsNativeFunction ctor); - bool install(); - Object* getProto(); - + /** + * @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. + * @return true if succeed, otherwise false. + */ bool defineFunction(const char *name, JsNativeFunction func); + + /** + * @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. + * @return true if succeed, otherwise false. + */ bool defineProperty(const char *name, JsNativeFunction getter, JsNativeFunction setter); + + /** + * @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. + * @return true if succeed, otherwise false. + */ bool defineStaticFunction(const char *name, JsNativeFunction func); + + /** + * @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. + * @return true if succeed, otherwise false. + */ bool defineStaticProperty(const char *name, JsNativeFunction getter, JsNativeFunction setter); + + /** + * @brief Defines the finalize function with a callback. + * @param[in] func The callback to invoke when a JavaScript object is garbage collected. + * @return true if succeed, otherwise false. + */ bool defineFinalizeFunction(JsFinalizeCallback func); + /** + * @brief Installs class to JavaScript VM. + * @return true if succeed, otherwise false. + * @note After this method, an object could be created by `var foo = new Foo();`. + */ + bool install(); + + /** + * @brief Gets the proto object of this class. + * @return The proto object of this class. + * @note Don't need to be released in user code. + */ + Object* getProto(); + + /** + * @brief Gets the class name. + * @return The class name. + */ const char* getName() const { return _name.c_str(); } private: + Class(); + ~Class(); + bool init(const std::string& clsName, Object* obj, Object* parentProto, JsNativeFunction ctor); void destroy(); diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h index 1f53080b69..36338d791a 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -31,6 +54,9 @@ void* nativeThisObject = se::internal::getPrivate(_argv[0]); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::seToJsValue(state.rval(), &_jsRet); \ return _jsRet; \ } @@ -47,6 +73,9 @@ se::Object* _thisObject = state.thisObject(); \ if (_thisObject) _thisObject->_cleanup(nativeThisObject); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ SAFE_DEC_REF(_thisObject); \ se->_setGarbageCollecting(false); \ } \ @@ -75,6 +104,10 @@ _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return _jsRet; \ } @@ -98,6 +131,10 @@ _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return _jsRet; \ } @@ -107,10 +144,13 @@ { \ assert(_argc == 1); \ JsValueRef _jsRet = JS_INVALID_REFERENCE; \ - SE_UNUSED bool ret = true; \ + bool ret = true; \ void* nativeThisObject = se::internal::getPrivate(_argv[0]); \ se::State state(nativeThisObject); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::seToJsValue(state.rval(), &_jsRet); \ return _jsRet; \ } @@ -120,7 +160,7 @@ JsValueRef funcName##Registry(JsValueRef _callee, bool _isConstructCall, JsValueRef* _argv, unsigned short _argc, void* _callbackState) \ { \ assert(_argc == 2); \ - SE_UNUSED bool ret = true; \ + bool ret = true; \ void* nativeThisObject = se::internal::getPrivate(_argv[0]); \ se::Value data; \ se::internal::jsToSeValue(_argv[1], &data); \ @@ -128,6 +168,9 @@ args.push_back(std::move(data)); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return JS_INVALID_REFERENCE; \ } @@ -138,7 +181,7 @@ #define SE_QUOTEME(x) SE_QUOTEME_(x) //FIXME: implement this macro -#define SE_REPORT_ERROR(fmt, ...) LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) +#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) #if COCOS2D_DEBUG > 0 @@ -147,7 +190,7 @@ { \ if (!(cond)) \ { \ - LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ + SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ assert(false); \ } \ } while(false) @@ -164,7 +207,7 @@ JsErrorCode _errCode = cmd; \ if (_errCode != JsNoError) \ { \ - LOGD("Error 0x%x at '%s, %s, %d'\n", \ + SE_LOGE("Error 0x%x at '%s, %s, %d'\n", \ _errCode, #cmd, __FILE__, __LINE__); \ assert(false); \ } \ diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.cpp index afb432b1f8..7efe2dfa3e 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Object.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE @@ -57,11 +80,64 @@ namespace se { return obj; } - Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength) + Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength) { + if (type == TypedArrayType::NONE) + { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + if (type == TypedArrayType::UINT8_CLAMPED) + { + SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!"); + return nullptr; + } + + JsTypedArrayType typedArrayType; + size_t elementLength = 0; + + switch (type) { + case TypedArrayType::INT8: + typedArrayType = JsArrayTypeInt8; + elementLength = byteLength; + break; + case TypedArrayType::INT16: + typedArrayType = JsArrayTypeInt16; + elementLength = byteLength / 2; + break; + case TypedArrayType::INT32: + typedArrayType = JsArrayTypeInt32; + elementLength = byteLength / 4; + break; + case TypedArrayType::UINT8: + typedArrayType = JsArrayTypeUint8; + elementLength = byteLength; + break; + case TypedArrayType::UINT16: + typedArrayType = JsArrayTypeUint16; + elementLength = byteLength / 2; + break; + case TypedArrayType::UINT32: + typedArrayType = JsArrayTypeUint32; + elementLength = byteLength / 4; + break; + case TypedArrayType::FLOAT32: + typedArrayType = JsArrayTypeFloat32; + elementLength = byteLength / 4; + break; + case TypedArrayType::FLOAT64: + typedArrayType = JsArrayTypeFloat64; + elementLength = byteLength / 8; + break; + default: + assert(false); // Should never go here. + break; + } + Object* obj = nullptr; JsValueRef jsobj; - _CHECK(JsCreateTypedArray(JsArrayTypeUint8, JS_INVALID_REFERENCE, 0, (unsigned int)byteLength, &jsobj)); + _CHECK(JsCreateTypedArray(typedArrayType, JS_INVALID_REFERENCE, 0, (unsigned int)elementLength, &jsobj)); ChakraBytePtr buffer = nullptr; unsigned int bufferLength = 0; JsTypedArrayType arrType; @@ -75,6 +151,11 @@ namespace se { return obj; } + Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount) + { + return createTypedArray(TypedArrayType::UINT8, data, dataCount); + } + Object* Object::createJSONObject(const std::string& jsonStr) { bool ok = false; @@ -179,7 +260,7 @@ namespace se { } else { - LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); + SE_LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); } _isCleanup = true; @@ -455,8 +536,7 @@ namespace se { { if (isFunction()) { - std::string info; - internal::forceConvertJsValueToStdString(_obj, &info); + std::string info = toString(); if (info.find("[native code]") != std::string::npos) { return true; @@ -475,6 +555,42 @@ namespace se { return false; } + Object::TypedArrayType Object::getTypedArrayType() const + { + TypedArrayType ret = TypedArrayType::NONE; + if (!isTypedArray()) + return ret; + + JsTypedArrayType type; + JsValueRef arrayBuffer = JS_INVALID_REFERENCE; + unsigned int byteOffset = 0; + unsigned int byteLength = 0; + + if (JsNoError == JsGetTypedArrayInfo(_obj, &type, &arrayBuffer, &byteOffset, &byteLength)) + { + if (type == JsArrayTypeInt8) + ret = TypedArrayType::INT8; + else if (type == JsArrayTypeInt16) + ret = TypedArrayType::INT16; + else if (type == JsArrayTypeInt32) + ret = TypedArrayType::INT32; + else if (type == JsArrayTypeUint8) + ret = TypedArrayType::UINT8; + else if (type == JsArrayTypeUint8Clamped) + ret = TypedArrayType::UINT8_CLAMPED; + else if (type == JsArrayTypeUint16) + ret = TypedArrayType::UINT16; + else if (type == JsArrayTypeUint32) + ret = TypedArrayType::UINT32; + else if (type == JsArrayTypeFloat32) + ret = TypedArrayType::FLOAT32; + else if (type == JsArrayTypeFloat64) + ret = TypedArrayType::FLOAT64; + } + + return ret; + } + bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const { assert(isTypedArray()); @@ -595,7 +711,7 @@ namespace se { } else { - LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); + SE_LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); } } } @@ -656,6 +772,24 @@ namespace se { return true; } + std::string Object::toString() const + { + std::string ret; + if (isFunction() || isArray() || isTypedArray()) + { + internal::forceConvertJsValueToStdString(_obj, &ret); + } + else if (isArrayBuffer()) + { + ret = "[object ArrayBuffer]"; + } + else + { + ret = "[object Object]"; + } + return ret; + } + } // namespace se { #endif // #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.hpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.hpp index 9ffc6dff15..4c747910e3 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Object.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -12,51 +35,323 @@ namespace se { class Class; + /** + * se::Object represents JavaScript Object. + */ class Object final : public RefCounter { public: + /** + * @brief Creates a JavaScript Object like `{} or new Object()`. + * @return A JavaScript Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createPlainObject(); + + /** + * @brief Creates a JavaScript Array Object like `[] or new Array()`. + * @param[in] length The initical length of array. + * @return A JavaScript Array Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createArrayObject(size_t length); - static Object* createUint8TypedArray(uint8_t* data, size_t byteLength); - static Object* createArrayBufferObject(void* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength); + + enum class TypedArrayType + { + NONE, + INT8, + INT16, + INT32, + UINT8, + UINT8_CLAMPED, + UINT16, + UINT32, + FLOAT32, + FLOAT64 + }; + + /** + * @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer. + * @param[in] type The format of typed array. + * @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Array Buffer object from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createArrayBufferObject(void* bytes, size_t byteLength); + + /** + * @brief Creates a JavaScript Object from a JSON formatted string. + * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. + * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. + * @note The return value (non-null) has to be released manually. + */ static Object* createJSONObject(const std::string& jsonStr); - static Object* getObjectWithPtr(void* ptr); + + /** + * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. + * @param[in] cls The se::Class instance which stores native callback informations. + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createObjectWithClass(Class* cls); - bool getProperty(const char* name, Value* data); - bool setProperty(const char* name, const Value& v); + /** + * @brief Gets a se::Object from an existing native object pointer. + * @param[in] ptr The native object pointer associated with the se::Object + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* getObjectWithPtr(void* ptr); + + /** + * @brief Gets a property from an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[out] value The property's value if object has the property, otherwise the undefined value. + * @return true if object has the property, otherwise false. + */ + bool getProperty(const char* name, Value* value); + + /** + * @brief Sets a property to an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] value A value to be used as the property's value. + * @return true if the property is set successfully, otherwise false. + */ + bool setProperty(const char* name, const Value& value); + + /** + * @brief Defines a property with native accessor callbacks for an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] getter The native callback for getter. + * @param[in] setter The native callback for setter. + * @return true if succeed, otherwise false. + */ bool defineProperty(const char *name, JsNativeFunction getter, JsNativeFunction setter); - bool isFunction() const; - bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr); - + /** + * @brief Defines a function with a native callback for an object. + * @param[in] funcName A utf-8 string containing the function name. + * @param[in] func The native callback triggered by JavaScript code. + * @return true if succeed, otherwise false. + */ bool defineFunction(const char *funcName, JsNativeFunction func); - bool isTypedArray() const; - bool getTypedArrayData(uint8_t** ptr, size_t* length) const; + /** + * @brief Tests whether an object can be called as a function. + * @return true if object can be called as a function, otherwise false. + */ + bool isFunction() const; + /** + * @brief Calls an object as a function. + * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. + * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." + * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. + * @return true if object is a function and there isn't any errors, otherwise false. + */ + bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr); + + /** + * @brief Tests whether an object is an array. + * @return true if object is an array, otherwise false. + */ bool isArray() const; + + /** + * @brief Gets array length of an array object. + * @param[out] length The array length to be stored. It's set to 0 if there is an error. + * @return true if succeed, otherwise false. + */ bool getArrayLength(uint32_t* length) const; + + /** + * @brief Gets an element from an array object by numeric index. + * @param[in] index An integer value for index. + * @param[out] data The se::Value to be stored for the element in certain index. + * @return true if succeed, otherwise false. + */ bool getArrayElement(uint32_t index, Value* data) const; + + /** + * @brief Sets an element to an array object by numeric index. + * @param[in] index An integer value for index. + * @param[in] data The se::Value to be set to array with certain index. + * @return true if succeed, otherwise false. + */ bool setArrayElement(uint32_t index, const Value& data); + /** @brief Tests whether an object is a typed array. + * @return true if object is a typed array, otherwise false. + */ + bool isTypedArray() const; + + /** + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ + TypedArrayType getTypedArrayType() const; + + /** + * @brief Gets backing store of a typed array object. + * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. + * @param[out] length The byte length of a JavaScript Typed Array object. + * @return true if succeed, otherwise false. + */ + bool getTypedArrayData(uint8_t** ptr, size_t* length) const; + + /** + * @brief Tests whether an object is an array buffer object. + * @return true if object is an array buffer object, otherwise false. + */ bool isArrayBuffer() const; + + /** + * @brief Gets buffer data of an array buffer object. + * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. + * @param[out] length The number of bytes in a JavaScript data object. + * @return true if succeed, otherwise false. + */ bool getArrayBufferData(uint8_t** ptr, size_t* length) const; + /** + * @brief Gets all property names of an object. + * @param[out] allKeys A string vector to store all property names. + * @return true if succeed, otherwise false. + */ bool getAllKeys(std::vector* allKeys) const; + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by std::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ void setPrivateData(void* data); + + /** + * @brief Gets an object's private data. + * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. + */ void* getPrivateData() const; + + /** + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void clearPrivateData(); + /** + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void root(); + + /** + * @brief Unroots an object from garbage collection. + * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void unroot(); + + /** + * @brief Tests whether an object is rooted. + * @return true if it has been already rooted, otherwise false. + */ bool isRooted() const; + /** + * @brief Tests whether two objects are strict equal, as compared by the JS === operator. + * @param[in] o The object to be tested with this object. + * @return true if the two values are strict equal, otherwise false. + */ bool strictEquals(Object* obj) const; + + /** + * @brief Attaches an object to current object. + * @param[in] obj The object to be attached. + * @return true if succeed, otherwise false. + * @note This method will set `obj` as a property of current object, therefore the lifecycle of child object will depend on current object, + * which means `obj` may be garbage collected only after current object is garbage collected. + * It's normally used in binding a native callback method. For example: + + ```javascript + var self = this; + someObject.setCallback(function(){}, self); + ``` + + ```c++ + static bool SomeObject_setCallback(se::State& s) + { + SomeObject* cobj = (SomeObject*)s.nativeThisObject(); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 2) { + std::function arg0; + do { + if (args[0].isObject() && args[0].toObject()->isFunction()) + { + se::Value jsThis(args[1]); + se::Value jsFunc(args[0]); + + jsThis.toObject()->attachObject(jsFunc.toObject()); + + auto lambda = [=]() -> void { + ... + // Call jsFunc stuff... + ... + }; + arg0 = lambda; + } + else + { + arg0 = nullptr; + } + } while(false); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setCallback(arg0); + return true; + } + + return false; + } + ``` + */ bool attachObject(Object* obj); + + /** + * @brief Detaches an object from current object. + * @param[in] obj The object to be detached. + * @return true if succeed, otherwise false. + * @note The attached object will not be released if current object is not garbage collected. + */ bool detachObject(Object* obj); + /** + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ + std::string toString() const; + // Private API used in wrapper static Object* _createJSObject(Class* cls, JsValueRef obj); JsValueRef _getJSObject() const; @@ -65,7 +360,6 @@ namespace se { void _setFinalizeCallback(JsFinalizeCallback finalizeCb); bool _isNativeFunction() const; // - private: static void cleanup(); diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.cpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.cpp index c9b8a90617..3590650116 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "ScriptEngine.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE @@ -27,14 +50,14 @@ namespace se { { std::string str; internal::forceConvertJsValueToStdString(arguments[1], &str); - LOGD("JS: %s\n", str.c_str()); + SE_LOGD("JS: %s\n", str.c_str()); } return JS_INVALID_REFERENCE; } void myJsBeforeCollectCallback(void *callbackState) { - LOGD("GC start ...\n"); + SE_LOGD("GC start ...\n"); } JsValueRef privateDataContructor(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) @@ -61,7 +84,7 @@ namespace se { if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { @@ -80,7 +103,7 @@ namespace se { } } - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } return true; @@ -170,7 +193,7 @@ namespace se { bool ScriptEngine::init() { cleanup(); - LOGD("Initializing ChakraCore, version: %d.%d.%d\n", CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION); + SE_LOGD("Initializing ChakraCore, version: %d.%d.%d\n", CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION); ++_vmId; for (const auto& hook : _beforeInitHookArray) @@ -289,7 +312,7 @@ namespace se { Value tmp; if (exceptionObj->getProperty(key.c_str(), &tmp)) { -// LOGD("[%s]=%s\n", key.c_str(), tmp.toStringForce().c_str()); +// SE_LOGD("[%s]=%s\n", key.c_str(), tmp.toStringForce().c_str()); if (key == "message") { ret.message = tmp.toString(); @@ -372,9 +395,9 @@ namespace se { void ScriptEngine::garbageCollect() { - LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); + SE_LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); _CHECK(JsCollectGarbage(_rt)); - LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); + SE_LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); } void ScriptEngine::clearException() @@ -388,7 +411,7 @@ namespace se { _CHECK(JsGetAndClearException(&exception)); ExceptionInfo exceptionInfo = formatException(exception); - LOGD("ERROR: %s, %s, \nSTACK:\n%s\n", exceptionInfo.message.c_str(), exceptionInfo.location.c_str(), exceptionInfo.stack.c_str()); + SE_LOGD("ERROR: %s, location: %s, \nSTACK:\n%s\n", exceptionInfo.message.c_str(), exceptionInfo.location.c_str(), exceptionInfo.stack.c_str()); if (_exceptionCallback != nullptr) { @@ -414,7 +437,7 @@ namespace se { } else { - LOGE("ERROR: __errorHandler has exception\n"); + SE_LOGE("ERROR: __errorHandler has exception\n"); } } } @@ -483,46 +506,10 @@ namespace se { return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str()); } - LOGE("ScriptEngine::runScript script buffer is empty!\n"); + SE_LOGE("ScriptEngine::runScript script buffer is empty!\n"); return false; } - void ScriptEngine::_retainScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - iterOwner->second->attachObject(iterTarget->second); - } - - void ScriptEngine::_releaseScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - iterOwner->second->detachObject(iterTarget->second); - } - void ScriptEngine::enableDebugger(const std::string& serverAddr, uint32_t port) { //FIXME: diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.hpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.hpp index 5292692fc3..d4a96a5289 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/ScriptEngine.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -14,6 +37,12 @@ namespace se { extern Class* __jsb_CCPrivateData_class; + /** + * A stack-allocated class that governs a number of local handles. + * It's only implemented for v8 wrapper now. + * Other script engine wrappers have empty implementation for this class. + * It's used at the beginning of executing any wrapper API. + */ class AutoHandleScope { public: @@ -21,24 +50,51 @@ namespace se { ~AutoHandleScope() {} }; + /** + * ScriptEngine is a sington which represents a context of JavaScript VM. + */ class ScriptEngine final { - private: - ScriptEngine(); - ~ScriptEngine(); - public: + /** + * @brief Gets or creates the instance of script engine. + * @return The script engine instance. + */ static ScriptEngine* getInstance(); + + /** + * @brief Destroys the instance of script engine. + */ static void destroyInstance(); + /** + * @brief Gets the global object of JavaScript VM. + * @return The se::Object stores the global JavaScript object. + */ Object* getGlobalObject(); typedef bool (*RegisterCallback)(Object*); + + /** + * @brief Adds a callback for registering a native binding module. + * @param[in] cb A callback for registering a native binding module. + * @note This method just add a callback to a vector, callbacks is invoked in `start` method. + */ void addRegisterCallback(RegisterCallback cb); + + /** + * @brief Starts the script engine. + * @return true if succeed, otherwise false. + * @note This method will invoke all callbacks of native binding modules by the order of registration. + */ bool start(); + /** + * @brief Initializes script engine. + * @return true if succeed, otherwise false. + * @note This method will create JavaScript context and global object. + */ bool init(); - void cleanup(); /** * @brief Adds a hook function before initializing script engine. @@ -54,10 +110,35 @@ namespace se { */ void addAfterInitHook(const std::function& hook); + /** + * @brief Cleanups script engine. + * @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf. + */ + void cleanup(); + + /** + * @brief Adds a hook function before cleanuping script engine. + * @param[in] hook A hook function to be invoked before cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ void addBeforeCleanupHook(const std::function& hook); + + /** + * @brief Adds a hook function after cleanuping script engine. + * @param[in] hook A hook function to be invoked after cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ void addAfterCleanupHook(const std::function& hook); - bool evalString(const char* script, ssize_t length = -1, Value* ret = nullptr, const char* fileName = nullptr); + /** + * @brief Executes a utf-8 string buffer which contains JavaScript code. + * @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. + * @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated. + * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. + * @return true if succeed, otherwise false. + */ + bool evalString(const char* scriptStr, ssize_t length = -1, Value* rval = nullptr, const char* fileName = nullptr); /** * Delegate class for file operation @@ -103,32 +184,82 @@ namespace se { * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. * @return true if succeed, otherwise false. */ - bool runScript(const std::string& path, Value* ret = nullptr); + bool runScript(const std::string& path, Value* rval = nullptr); + /** + * @brief Tests whether script engine is doing garbage collection. + * @return true if it's in garbage collection, otherwise false. + */ bool isGarbageCollecting(); - void _setGarbageCollecting(bool isGarbageCollecting); + + /** + * @brief Performs a JavaScript garbage collection. + */ void garbageCollect(); - bool isValid() { return _isValid; } + /** + * @brief Tests whether script engine is being cleaned up. + * @return true if it's in cleaning up, otherwise false. + */ bool isInCleanup() { return _isInCleanup; } + /** + * @brief Tests whether script engine is valid. + * @return true if it's valid, otherwise false. + */ + bool isValid() { return _isValid; } + + /** + * @brief Clears all exceptions. + */ void clearException(); using ExceptionCallback = std::function; // location, message, stack + /** + * @brief Sets the callback function while an exception is fired. + * @param[in] cb The callback function to notify that an exception is fired. + */ void setExceptionCallback(const ExceptionCallback& cb); + /** + * @brief Gets the start time of script engine. + * @return The start time of script engine. + */ const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; } + + /** + * @brief Enables JavaScript debugger + * @param[in] serverAddr The address of debugger server. + * @param[in] port The port of debugger server will use. + */ void enableDebugger(const std::string& serverAddr, uint32_t port); + + /** + * @brief Tests whether JavaScript debugger is enabled + * @return true if JavaScript debugger is enabled, otherwise false. + */ bool isDebuggerEnabled() const; + + /** + * @brief Main loop update trigger, it's need to invoked in main thread every frame. + */ void mainLoopUpdate(); + /** + * @brief Gets script virtual machine instance ID. Default value is 1, increase by 1 if `init` is invoked. + */ uint32_t getVMId() const { return _vmId; } + // Private API used in wrapper + void _setGarbageCollecting(bool isGarbageCollecting); void _retainScriptObject(void* owner, void* target); void _releaseScriptObject(void* owner, void* target); - + // private: + ScriptEngine(); + ~ScriptEngine(); + struct ExceptionInfo { std::string location; diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/SeApi.h b/native/cocos/scripting/js-bindings/jswrapper/chakracore/SeApi.h index 10a43c6eba..15100c1197 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/SeApi.h +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/SeApi.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "ScriptEngine.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.cpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.cpp index a229655f6b..aa130ed37c 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.cpp @@ -1,11 +1,26 @@ -// -// Utils.cpp -// cocos2d_js_bindings -// -// Created by James Chen on 4/26/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Utils.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE @@ -224,16 +239,21 @@ namespace se { } assert(finalizeCb); - HandleObject privateObj(Object::createObjectWithClass(__jsb_CCPrivateData_class)); + Object* privateObj = Object::createObjectWithClass(__jsb_CCPrivateData_class); + privateObj->root(); + internal::PrivateData* privateData = (internal::PrivateData*)malloc(sizeof(internal::PrivateData)); privateData->data = data; privateData->finalizeCb = finalizeCb; _CHECK(JsSetExternalData(privateObj->_getJSObject(), privateData)); -// LOGD("setPrivate: %p\n", data); +// SE_LOGD("setPrivate: %p\n", data); JsPropertyIdRef propertyId = JS_INVALID_REFERENCE; JsCreatePropertyId(KEY_PRIVATE_DATA, strlen(KEY_PRIVATE_DATA), &propertyId); _CHECK(JsSetProperty(obj, propertyId, privateObj->_getJSObject(), true)); + + privateObj->unroot(); + privateObj->decRef(); } void* getPrivate(JsValueRef obj) @@ -270,7 +290,7 @@ namespace se { assert(privateData); data = privateData->data; } -// LOGD("getPrivate: %p\n", data); +// SE_LOGD("getPrivate: %p\n", data); return data; } diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.hpp b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.hpp index ec8be6ae40..16b9a47618 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/Utils.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/config.hpp b/native/cocos/scripting/js-bindings/jswrapper/config.hpp index 5597958570..1d7ba8c3e3 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/config.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/config.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #define SCRIPT_ENGINE_NONE 0 @@ -27,8 +50,8 @@ #include #define LOG_TAG "jswrapper" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#define SE_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) +#define SE_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #elif defined(_WIN32) && defined(_WINDOWS) @@ -43,13 +66,13 @@ void seLog(const char * format, ...); #define LOG_TAG "jswrapper" -#define LOGD(fmt, ...) seLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) -#define LOGE(fmt, ...) seLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) +#define SE_LOGD(fmt, ...) seLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) +#define SE_LOGE(fmt, ...) seLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) #else -#define LOGD(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false) -#define LOGE(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false) +#define SE_LOGD(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false) +#define SE_LOGE(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false) #endif @@ -68,5 +91,16 @@ typedef SSIZE_T ssize_t; #define _SSIZE_T_DEFINED // libuv also defines ssize_t, use the one defined here. #endif // __SSIZE_T -#endif +#endif // #if defined(_WIN32) && defined(_WINDOWS) + +/** @def SE_DEPRECATED_ATTRIBUTE + * Only certain compilers support __attribute__((deprecated)). + */ +#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) +#define SE_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#elif _MSC_VER >= 1400 //vs 2005 or higher +#define SE_DEPRECATED_ATTRIBUTE __declspec(deprecated) +#else +#define SE_DEPRECATED_ATTRIBUTE +#endif // SE_DEPRECATED_ATTRIBUTE diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Base.h b/native/cocos/scripting/js-bindings/jswrapper/jsc/Base.h index 8153e17df7..df24f957a2 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Base.h +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Base.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.cpp index cdefc7d840..1d627d3b62 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Class.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC @@ -103,7 +126,7 @@ namespace se { _jsCls = JSClassCreate(&_jsClsDef); JSObjectRef jsCtor = JSObjectMakeConstructor(__cx, _jsCls, _ctor); - HandleObject ctorObj(Object::_createJSObject(this, jsCtor)); + HandleObject ctorObj(Object::_createJSObject(nullptr, jsCtor)); Value functionCtor; ScriptEngine::getInstance()->getGlobalObject()->getProperty("Function", &functionCtor); diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.hpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.hpp index 58bf23cc9d..03be05e3f9 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Class.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h index 83dc79cb2a..ccf1f01450 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -32,6 +55,9 @@ se::internal::jsToSeArgs(_cx, argc, _argv, &args); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::seToJsValue(_cx, state.rval(), &_jsRet); \ } \ return _jsRet; \ @@ -50,6 +76,9 @@ se::Object* _thisObject = state.thisObject(); \ if (_thisObject) _thisObject->_cleanup(nativeThisObject); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ JSObjectSetPrivate(_obj, nullptr); \ SAFE_DEC_REF(_thisObject); \ } \ @@ -78,6 +107,10 @@ _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return JSValueToObject(_cx, _jsRet, nullptr); \ } @@ -85,7 +118,7 @@ #define SE_BIND_SUB_CLS_CTOR(funcName, cls, finalizeCb) \ JSValueRef funcName##Registry(JSContextRef _cx, JSObjectRef _function, JSObjectRef _thisObject, size_t argc, const JSValueRef _argv[], JSValueRef* _exception) \ { \ - SE_UNUSED bool ret = true; \ + bool ret = true; \ JSValueRef _jsRet = JSValueMakeUndefined(_cx); \ se::ValueArray args; \ se::internal::jsToSeArgs(_cx, argc, _argv, &args); \ @@ -100,6 +133,10 @@ _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return _jsRet; \ } @@ -117,6 +154,10 @@ { \ se::internal::seToJsValue(_cx, state.rval(), &_jsRet); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ } \ return _jsRet; \ } @@ -137,6 +178,9 @@ args.push_back(std::move(data)); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ } \ return _jsRet; \ } @@ -149,7 +193,7 @@ #define SE_QUOTEME(x) SE_QUOTEME_(x) //FIXME: implement this macro -#define SE_REPORT_ERROR(fmt, ...) LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) +#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) #if COCOS2D_DEBUG > 0 @@ -158,7 +202,7 @@ { \ if (!(cond)) \ { \ - LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ + SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ assert(false); \ } \ } while(false) diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp index f461d9fc08..8a9cddcb55 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Object.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC @@ -15,6 +38,20 @@ namespace se { #if SE_DEBUG > 0 uint32_t __id = 0; #endif + + bool isInstanceOfConstructor(JSContextRef ctx, JSValueRef value, const char* ctorName) + { + if (ctorName == nullptr) + return false; + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value ctorVal; + bool ret = false; + if (global->getProperty(ctorName, &ctorVal), ctorVal.isObject()) + { + ret = JSValueIsInstanceOfConstructor(ctx, value, ctorVal.toObject()->_getJSObject(), nullptr); + } + return ret; + } } Object::Object() @@ -125,15 +162,71 @@ namespace se { return nullptr; } - Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength) + template + static bool _setArrayElement(Object* arr, void* data, size_t byteLength) { + T* p = (T*)data; + size_t count = byteLength / sizeof(T); + for (size_t i = 0; i < count; ++i) + { + if (!arr->setArrayElement((uint32_t)i, se::Value(p[i]))) + { + return false; + } + } + return true; + } + + Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength) + { + if (type == TypedArrayType::NONE) + { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + if (type == TypedArrayType::UINT8_CLAMPED) + { + SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!"); + return nullptr; + } + #if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000) if (isSupportTypedArrayAPI()) { void* copiedData = malloc(byteLength); memcpy(copiedData, data, byteLength); JSValueRef exception = nullptr; - JSObjectRef jsobj = JSObjectMakeTypedArrayWithBytesNoCopy(__cx, kJSTypedArrayTypeUint8Array, copiedData, byteLength, myJSTypedArrayBytesDeallocator, nullptr, &exception); + JSTypedArrayType jscTypedArrayType = kJSTypedArrayTypeNone; + switch (type) { + case TypedArrayType::INT8: + jscTypedArrayType = kJSTypedArrayTypeInt8Array; + break; + case TypedArrayType::INT16: + jscTypedArrayType = kJSTypedArrayTypeInt16Array; + break; + case TypedArrayType::INT32: + jscTypedArrayType = kJSTypedArrayTypeInt32Array; + break; + case TypedArrayType::UINT8: + jscTypedArrayType = kJSTypedArrayTypeUint8Array; + break; + case TypedArrayType::UINT16: + jscTypedArrayType = kJSTypedArrayTypeUint16Array; + break; + case TypedArrayType::UINT32: + jscTypedArrayType = kJSTypedArrayTypeUint32Array; + break; + case TypedArrayType::FLOAT32: + jscTypedArrayType = kJSTypedArrayTypeFloat32Array; + break; + case TypedArrayType::FLOAT64: + jscTypedArrayType = kJSTypedArrayTypeFloat64Array; + break; + default: + break; + } + JSObjectRef jsobj = JSObjectMakeTypedArrayWithBytesNoCopy(__cx, jscTypedArrayType, copiedData, byteLength, myJSTypedArrayBytesDeallocator, nullptr, &exception); if (exception != nullptr) { ScriptEngine::getInstance()->_clearException(exception); @@ -146,30 +239,75 @@ namespace se { #endif { HandleObject arr(Object::createArrayObject(byteLength)); + Type objectType = Type::UNKNOWN; + if (!arr.isEmpty()) { - uint8_t* p = (uint8_t*)data; - for (size_t i = 0; i < byteLength; ++i) - { - arr->setArrayElement((uint32_t)i, se::Value(p[i])); + const char* typedArrayCtor = nullptr; + switch (type) { + case TypedArrayType::INT8: + typedArrayCtor = "Int8Array"; + objectType = Type::TYPED_ARRAY_INT8; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::INT16: + typedArrayCtor = "Int16Array"; + objectType = Type::TYPED_ARRAY_INT16; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::INT32: + typedArrayCtor = "Int32Array"; + objectType = Type::TYPED_ARRAY_INT32; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::UINT8: + typedArrayCtor = "Uint8Array"; + objectType = Type::TYPED_ARRAY_UINT8; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::UINT16: + typedArrayCtor = "Uint16Array"; + objectType = Type::TYPED_ARRAY_UINT16; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::UINT32: + typedArrayCtor = "Uint32Array"; + objectType = Type::TYPED_ARRAY_UINT32; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::FLOAT32: + typedArrayCtor = "Float32Array"; + objectType = Type::TYPED_ARRAY_FLOAT32; + _setArrayElement(arr.get(), data, byteLength); + break; + case TypedArrayType::FLOAT64: + typedArrayCtor = "Float64Array"; + objectType = Type::TYPED_ARRAY_FLOAT64; + _setArrayElement(arr.get(), data, byteLength); + break; + default: + assert(false); // Should never go here. + break; } - ValueArray args; - args.push_back(Value(arr)); Value func; - bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_createUint8TypedArray", &func); + bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty(typedArrayCtor, &func); if (ok && func.isObject() && func.toObject()->isFunction()) { - Value ret; - ok = func.toObject()->call(args, nullptr, &ret); - if (ok && ret.isObject()) + JSValueRef exception = nullptr; + JSObjectRef ret = JSObjectCallAsConstructor(__cx, func.toObject()->_obj, 1, &arr->_obj, &exception); + if (exception == nullptr) { - Object* obj = Object::_createJSObject(nullptr, ret.toObject()->_obj); + Object* obj = Object::_createJSObject(nullptr, ret); if (obj != nullptr) - obj->_type = Type::TYPED_ARRAY; + obj->_type = objectType; return obj; } + else + { + ScriptEngine::getInstance()->_clearException(exception); + } } } } @@ -177,6 +315,11 @@ namespace se { return nullptr; } + Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount) + { + return createTypedArray(TypedArrayType::UINT8, data, dataCount); + } + Object* Object::createJSONObject(const std::string& jsonStr) { Object* obj = nullptr; @@ -268,7 +411,7 @@ namespace se { if (_rootCount > 0) { - // LOGD("Object::_cleanup, (%p) rootCount: %u\n", this, _rootCount); + // SE_LOGD("Object::_cleanup, (%p) rootCount: %u\n", this, _rootCount); // Don't unprotect if it's in cleanup, otherwise, it will trigger crash. if (!se->isInCleanup() && !se->isGarbageCollecting()) JSValueUnprotect(__cx, _obj); @@ -278,7 +421,7 @@ namespace se { } else { - LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); + SE_LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); } _isCleanup = true; @@ -446,7 +589,7 @@ namespace se { return true; } - bool Object::getArrayElement(uint32_t index, Value* data) const + bool Object::getArrayElement(uint32_t index, Value* data) const { assert(isArray()); assert(data != nullptr); @@ -505,8 +648,19 @@ namespace se { bool Object::isTypedArray() const { - if (_type == Type::TYPED_ARRAY) + if (_type == Type::TYPED_ARRAY_INT8 + || _type == Type::TYPED_ARRAY_INT16 + || _type == Type::TYPED_ARRAY_INT32 + || _type == Type::TYPED_ARRAY_UINT8 + || _type == Type::TYPED_ARRAY_UINT8_CLAMPED + || _type == Type::TYPED_ARRAY_UINT16 + || _type == Type::TYPED_ARRAY_UINT32 + || _type == Type::TYPED_ARRAY_FLOAT32 + || _type == Type::TYPED_ARRAY_FLOAT64 + ) + { return true; + } #if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000) if (isSupportTypedArrayAPI()) @@ -514,29 +668,166 @@ namespace se { JSTypedArrayType type = JSValueGetTypedArrayType(__cx, _obj, nullptr); bool ret = (type != kJSTypedArrayTypeNone && type != kJSTypedArrayTypeArrayBuffer); if (ret) - _type = Type::TYPED_ARRAY; + { + switch (type) { + case kJSTypedArrayTypeInt8Array: + _type = Type::TYPED_ARRAY_INT8; + break; + case kJSTypedArrayTypeInt16Array: + _type = Type::TYPED_ARRAY_INT16; + break; + case kJSTypedArrayTypeInt32Array: + _type = Type::TYPED_ARRAY_INT32; + break; + case kJSTypedArrayTypeUint8Array: + _type = Type::TYPED_ARRAY_UINT8; + break; + case kJSTypedArrayTypeUint8ClampedArray: + _type = Type::TYPED_ARRAY_UINT8_CLAMPED; + break; + case kJSTypedArrayTypeUint16Array: + _type = Type::TYPED_ARRAY_UINT16; + break; + case kJSTypedArrayTypeUint32Array: + _type = Type::TYPED_ARRAY_UINT32; + break; + case kJSTypedArrayTypeFloat32Array: + _type = Type::TYPED_ARRAY_FLOAT32; + break; + case kJSTypedArrayTypeFloat64Array: + _type = Type::TYPED_ARRAY_FLOAT64; + break; + default: + break; + } + } return ret; } #endif - Value func; - bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_isTypedArray", &func); - if (ok && func.isObject() && func.toObject()->isFunction()) - { - ValueArray args; - args.push_back(Value((Object*)this)); + return isInstanceOfConstructor(__cx, _obj, "__jscTypedArrayConstructor"); + } - Value rval; - ok = func.toObject()->call(args, nullptr, &rval); - if (ok && rval.isBoolean()) + Object::TypedArrayType Object::getTypedArrayType() const + { + if (_type == Type::TYPED_ARRAY_INT8) + return TypedArrayType::INT8; + else if (_type == Type::TYPED_ARRAY_INT16) + return TypedArrayType::INT16; + else if (_type == Type::TYPED_ARRAY_INT32) + return TypedArrayType::INT32; + else if (_type == Type::TYPED_ARRAY_UINT8) + return TypedArrayType::UINT8; + else if (_type == Type::TYPED_ARRAY_UINT8_CLAMPED) + return TypedArrayType::UINT8_CLAMPED; + else if (_type == Type::TYPED_ARRAY_UINT16) + return TypedArrayType::UINT16; + else if (_type == Type::TYPED_ARRAY_UINT32) + return TypedArrayType::UINT32; + else if (_type == Type::TYPED_ARRAY_FLOAT32) + return TypedArrayType::FLOAT32; + else if (_type == Type::TYPED_ARRAY_FLOAT64) + return TypedArrayType::FLOAT64; + + TypedArrayType typedArrayType = TypedArrayType::NONE; + +#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000) + if (isSupportTypedArrayAPI()) + { + JSTypedArrayType type = JSValueGetTypedArrayType(__cx, _obj, nullptr); + bool ret = (type != kJSTypedArrayTypeNone && type != kJSTypedArrayTypeArrayBuffer); + if (ret) { - bool ret = rval.toBoolean(); - if (ret) - _type = Type::TYPED_ARRAY; - return ret; + switch (type) { + case kJSTypedArrayTypeInt8Array: + _type = Type::TYPED_ARRAY_INT8; + typedArrayType = TypedArrayType::INT8; + break; + case kJSTypedArrayTypeInt16Array: + _type = Type::TYPED_ARRAY_INT16; + typedArrayType = TypedArrayType::INT16; + break; + case kJSTypedArrayTypeInt32Array: + _type = Type::TYPED_ARRAY_INT32; + typedArrayType = TypedArrayType::INT32; + break; + case kJSTypedArrayTypeUint8Array: + _type = Type::TYPED_ARRAY_UINT8; + typedArrayType = TypedArrayType::UINT8; + break; + case kJSTypedArrayTypeUint8ClampedArray: + _type = Type::TYPED_ARRAY_UINT8_CLAMPED; + typedArrayType = TypedArrayType::UINT8_CLAMPED; + break; + case kJSTypedArrayTypeUint16Array: + _type = Type::TYPED_ARRAY_UINT16; + typedArrayType = TypedArrayType::UINT16; + break; + case kJSTypedArrayTypeUint32Array: + _type = Type::TYPED_ARRAY_UINT32; + typedArrayType = TypedArrayType::UINT32; + break; + case kJSTypedArrayTypeFloat32Array: + _type = Type::TYPED_ARRAY_FLOAT32; + typedArrayType = TypedArrayType::FLOAT32; + break; + case kJSTypedArrayTypeFloat64Array: + _type = Type::TYPED_ARRAY_FLOAT64; + typedArrayType = TypedArrayType::FLOAT64; + break; + default: + break; + } } + return typedArrayType; + } +#endif + if (isInstanceOfConstructor(__cx, _obj, "Int8Array")) + { + _type = Type::TYPED_ARRAY_INT8; + typedArrayType = TypedArrayType::INT8; + } + else if (isInstanceOfConstructor(__cx, _obj, "Int16Array")) + { + _type = Type::TYPED_ARRAY_INT16; + typedArrayType = TypedArrayType::INT16; + } + else if (isInstanceOfConstructor(__cx, _obj, "Int32Array")) + { + _type = Type::TYPED_ARRAY_INT32; + typedArrayType = TypedArrayType::INT32; + } + else if (isInstanceOfConstructor(__cx, _obj, "Uint8Array")) + { + _type = Type::TYPED_ARRAY_UINT8; + typedArrayType = TypedArrayType::UINT8; + } + else if (isInstanceOfConstructor(__cx, _obj, "Uint8ClampedArray")) + { + _type = Type::TYPED_ARRAY_UINT8_CLAMPED; + typedArrayType = TypedArrayType::UINT8_CLAMPED; + } + else if (isInstanceOfConstructor(__cx, _obj, "Uint16Array")) + { + _type = Type::TYPED_ARRAY_UINT16; + typedArrayType = TypedArrayType::UINT16; + } + else if (isInstanceOfConstructor(__cx, _obj, "Uint32Array")) + { + _type = Type::TYPED_ARRAY_UINT32; + typedArrayType = TypedArrayType::UINT32; + } + else if (isInstanceOfConstructor(__cx, _obj, "Float32Array")) + { + _type = Type::TYPED_ARRAY_FLOAT32; + typedArrayType = TypedArrayType::FLOAT32; + } + else if (isInstanceOfConstructor(__cx, _obj, "Float64Array")) + { + _type = Type::TYPED_ARRAY_FLOAT64; + typedArrayType = TypedArrayType::FLOAT64; } - return false; + return typedArrayType; } bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const @@ -545,28 +836,44 @@ namespace se { #if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000) if (isSupportTypedArrayAPI()) { + bool succeed = false; JSValueRef exception = nullptr; - *length = JSObjectGetTypedArrayByteLength(__cx, _obj, &exception); - if (exception != nullptr) + do { + *length = JSObjectGetTypedArrayByteLength(__cx, _obj, &exception); + if (exception != nullptr) + break; + + size_t offset = JSObjectGetTypedArrayByteOffset(__cx, _obj, &exception); + if (exception != nullptr) + break; + + uint8_t* buf = (uint8_t*)JSObjectGetTypedArrayBytesPtr(__cx, _obj, &exception); + if (exception != nullptr) + break; + + if (buf == nullptr) + break; + + *ptr = buf + offset; + succeed = true; + } while (false); + + if (!succeed) + { + *ptr = nullptr; + *length = 0; ScriptEngine::getInstance()->_clearException(exception); return false; } - *ptr = (uint8_t*)JSObjectGetTypedArrayBytesPtr(__cx, _obj, &exception); - if (exception != nullptr) - { - ScriptEngine::getInstance()->_clearException(exception); - return false; - } - - return (*ptr != nullptr); + return true; } else #endif { Value func; - bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_getUint8ArrayData", &func); + bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_getTypedArrayData", &func); if (ok && func.isObject() && func.toObject()->isFunction()) { ValueArray args; @@ -615,8 +922,7 @@ namespace se { { if (isFunction()) { - std::string info; - internal::forceConvertJsValueToStdString(__cx, _obj, &info); + std::string info = toString(); if (info.find("[native code]") != std::string::npos) { return true; @@ -627,7 +933,19 @@ namespace se { bool Object::isArray() const { - return JSValueIsArray(__cx, _obj); + if (_type == Type::ARRAY) + return true; + +#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000) + if (isSupportArrayTestAPI()) + { + return JSValueIsArray(__cx, _obj); + } +#endif + bool ret = isInstanceOfConstructor(__cx, _obj, "Array"); + if (ret) + _type = Type::ARRAY; + return ret; } bool Object::isArrayBuffer() const @@ -653,25 +971,10 @@ namespace se { } #endif - Value func; - bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_isArrayBuffer", &func); - if (ok && func.isObject() && func.toObject()->isFunction()) - { - ValueArray args; - args.push_back(Value((Object*)this)); - - Value rval; - ok = func.toObject()->call(args, nullptr, &rval); - if (ok && rval.isBoolean()) - { - bool ret = rval.toBoolean(); - if (ret) - _type = Type::ARRAY_BUFFER; - return ret; - } - } - - return false; + bool ret = isInstanceOfConstructor(__cx, _obj, "ArrayBuffer"); + if (ret) + _type = Type::ARRAY_BUFFER; + return ret; } bool Object::getArrayBufferData(uint8_t** ptr, size_t* length) const @@ -834,12 +1137,12 @@ namespace se { } else { - LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); + SE_LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId()); } } } } - + bool Object::isRooted() const { return _rootCount > 0; @@ -893,6 +1196,25 @@ namespace se { return true; } + std::string Object::toString() const + { + std::string ret; + if (isFunction() || isArray() || isTypedArray()) + { + internal::forceConvertJsValueToStdString(__cx, _obj, &ret); + } + else if (isArrayBuffer()) + { + ret = "[object ArrayBuffer]"; + } + else + { + ret = "[object Object]"; + } + return ret; + } + } // namespace se { #endif // #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC + diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.hpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.hpp index 1a5b2ba6c8..3c79b0f443 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -39,8 +62,33 @@ namespace se { * @param[in] byteLength The number of bytes pointed to by the parameter bytes. * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. * @note The return value (non-null) has to be released manually. + * @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead. */ - static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength); + SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength); + + enum class TypedArrayType + { + NONE, + INT8, + INT16, + INT32, + UINT8, + UINT8_CLAMPED, + UINT16, + UINT32, + FLOAT32, + FLOAT64 + }; + + /** + * @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer. + * @param[in] type The format of typed array. + * @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength); /** * @brief Creates a JavaScript Array Buffer object from an existing pointer. @@ -107,6 +155,7 @@ namespace se { * @return true if succeed, otherwise false. */ bool defineFunction(const char *funcName, JSObjectCallAsFunctionCallback func); + /** * @brief Tests whether an object can be called as a function. * @return true if object can be called as a function, otherwise false. @@ -156,6 +205,12 @@ namespace se { */ bool isTypedArray() const; + /** + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ + TypedArrayType getTypedArrayType() const; + /** * @brief Gets backing store of a typed array object. * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. @@ -290,6 +345,12 @@ namespace se { */ bool detachObject(Object* obj); + /** + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ + std::string toString() const; + // Private API used in wrapper static Object* _createJSObject(Class* cls, JSObjectRef obj); JSObjectRef _getJSObject() const; @@ -315,7 +376,15 @@ namespace se { PLAIN, ARRAY, ARRAY_BUFFER, - TYPED_ARRAY, + TYPED_ARRAY_INT8, + TYPED_ARRAY_INT16, + TYPED_ARRAY_INT32, + TYPED_ARRAY_UINT8, + TYPED_ARRAY_UINT8_CLAMPED, + TYPED_ARRAY_UINT16, + TYPED_ARRAY_UINT32, + TYPED_ARRAY_FLOAT32, + TYPED_ARRAY_FLOAT64, FUNCTION }; diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.h b/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.h index 2bec6267b4..216c2606ef 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.h +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.h @@ -1,7 +1,31 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once namespace se { bool isSupportTypedArrayAPI(); + bool isSupportArrayTestAPI(); } // namespace se diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.mm b/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.mm index 8a66a73a68..f6f65f5d13 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.mm +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/PlatformUtils.mm @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "PlatformUtils.h" #include "../config.hpp" @@ -15,18 +38,42 @@ namespace se { bool isSupportTypedArrayAPI() { + static bool isSupported = false; + static bool isInited = false; + if (!isInited) + { #if TARGET_OS_IPHONE - float version = [[UIDevice currentDevice].systemVersion floatValue]; - if (version >= 10.0) - return true; + float version = [[UIDevice currentDevice].systemVersion floatValue]; + isSupported = (version >= 10.0f); #elif TARGET_OS_MAC - NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 12, .patchVersion = 0 }; - return [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion] ? true : false; + NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 12, .patchVersion = 0 }; + isSupported = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion] ? true : false; #else - LOGE("isSupportTypedArrayAPI: Unknown system!"); + SE_LOGE("isSupportTypedArrayAPI: Unknown system!"); #endif + isInited = true; + } + return isSupported; + } - return false; + bool isSupportArrayTestAPI() + { + static bool isSupported = false; + static bool isInited = false; + if (!isInited) + { +#if TARGET_OS_IPHONE + float version = [[UIDevice currentDevice].systemVersion floatValue]; + isSupported = (version >= 9.0f); +#elif TARGET_OS_MAC + NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 11, .patchVersion = 0 }; + isSupported = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion] ? true : false; +#else + SE_LOGE("isSupportArrayTestAPI: Unknown system!"); +#endif + isInited = true; + } + return isSupported; } } // namespace se diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp index d2cf82a520..56f1b3bd84 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "ScriptEngine.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC @@ -8,7 +31,9 @@ #include "../State.hpp" #include "../MappingUtils.hpp" +#if SE_DEBUG > 0 extern "C" JS_EXPORT void JSSynchronousGarbageCollectForDebugging(JSContextRef); +#endif namespace se { @@ -31,10 +56,10 @@ namespace se { JSValueRef __forceGC(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { - LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); -// JSGarbageCollect(ctx); - JSSynchronousGarbageCollectForDebugging(ctx); - LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); + if (__instance != nullptr) + { + __instance->garbageCollect(); + } return JSValueMakeUndefined(ctx); } @@ -45,7 +70,7 @@ namespace se { { std::string ret; internal::forceConvertJsValueToStdString(ctx, arguments[0], &ret); - LOGD("JS: %s\n", ret.c_str()); + SE_LOGD("JS: %s\n", ret.c_str()); } return JSValueMakeUndefined(ctx); } @@ -64,6 +89,7 @@ namespace se { free(p); } + Value __consoleVal; Value __oldConsoleLog; Value __oldConsoleDebug; Value __oldConsoleInfo; @@ -81,7 +107,7 @@ namespace se { if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { @@ -100,7 +126,7 @@ namespace se { } } - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } return true; @@ -109,7 +135,7 @@ namespace se { bool JSB_console_log(State& s) { JSB_console_format_log(s, ""); - __oldConsoleLog.toObject()->call(s.args(), s.thisObject()); + __oldConsoleLog.toObject()->call(s.args(), __consoleVal.toObject()); return true; } SE_BIND_FUNC(JSB_console_log) @@ -117,7 +143,7 @@ namespace se { bool JSB_console_debug(State& s) { JSB_console_format_log(s, "[DEBUG]: "); - __oldConsoleDebug.toObject()->call(s.args(), s.thisObject()); + __oldConsoleDebug.toObject()->call(s.args(), __consoleVal.toObject()); return true; } SE_BIND_FUNC(JSB_console_debug) @@ -125,7 +151,7 @@ namespace se { bool JSB_console_info(State& s) { JSB_console_format_log(s, "[INFO]: "); - __oldConsoleInfo.toObject()->call(s.args(), s.thisObject()); + __oldConsoleInfo.toObject()->call(s.args(), __consoleVal.toObject()); return true; } SE_BIND_FUNC(JSB_console_info) @@ -133,7 +159,7 @@ namespace se { bool JSB_console_warn(State& s) { JSB_console_format_log(s, "[WARN]: "); - __oldConsoleWarn.toObject()->call(s.args(), s.thisObject()); + __oldConsoleWarn.toObject()->call(s.args(), __consoleVal.toObject()); return true; } SE_BIND_FUNC(JSB_console_warn) @@ -141,7 +167,7 @@ namespace se { bool JSB_console_error(State& s) { JSB_console_format_log(s, "[ERROR]: "); - __oldConsoleError.toObject()->call(s.args(), s.thisObject()); + __oldConsoleError.toObject()->call(s.args(), __consoleVal.toObject()); return true; } SE_BIND_FUNC(JSB_console_error) @@ -154,7 +180,7 @@ namespace se { if (args[0].isBoolean() && !args[0].toBoolean()) { JSB_console_format_log(s, "[ASSERT]: ", 1); - __oldConsoleAssert.toObject()->call(s.args(), s.thisObject()); + __oldConsoleAssert.toObject()->call(s.args(), __consoleVal.toObject()); } } return true; @@ -194,7 +220,7 @@ namespace se { bool ScriptEngine::init() { cleanup(); - LOGD("Initializing JavaScriptCore \n"); + SE_LOGD("Initializing JavaScriptCore \n"); ++_vmId; for (const auto& hook : _beforeInitHookArray) @@ -228,26 +254,25 @@ namespace se { _globalObj->root(); _globalObj->setProperty("window", Value(_globalObj)); - Value consoleVal; - if (_globalObj->getProperty("console", &consoleVal) && consoleVal.isObject()) + if (_globalObj->getProperty("console", &__consoleVal) && __consoleVal.isObject()) { - consoleVal.toObject()->getProperty("log", &__oldConsoleLog); - consoleVal.toObject()->defineFunction("log", _SE(JSB_console_log)); + __consoleVal.toObject()->getProperty("log", &__oldConsoleLog); + __consoleVal.toObject()->defineFunction("log", _SE(JSB_console_log)); - consoleVal.toObject()->getProperty("debug", &__oldConsoleDebug); - consoleVal.toObject()->defineFunction("debug", _SE(JSB_console_debug)); + __consoleVal.toObject()->getProperty("debug", &__oldConsoleDebug); + __consoleVal.toObject()->defineFunction("debug", _SE(JSB_console_debug)); - consoleVal.toObject()->getProperty("info", &__oldConsoleInfo); - consoleVal.toObject()->defineFunction("info", _SE(JSB_console_info)); + __consoleVal.toObject()->getProperty("info", &__oldConsoleInfo); + __consoleVal.toObject()->defineFunction("info", _SE(JSB_console_info)); - consoleVal.toObject()->getProperty("warn", &__oldConsoleWarn); - consoleVal.toObject()->defineFunction("warn", _SE(JSB_console_warn)); + __consoleVal.toObject()->getProperty("warn", &__oldConsoleWarn); + __consoleVal.toObject()->defineFunction("warn", _SE(JSB_console_warn)); - consoleVal.toObject()->getProperty("error", &__oldConsoleError); - consoleVal.toObject()->defineFunction("error", _SE(JSB_console_error)); + __consoleVal.toObject()->getProperty("error", &__oldConsoleError); + __consoleVal.toObject()->defineFunction("error", _SE(JSB_console_error)); - consoleVal.toObject()->getProperty("assert", &__oldConsoleAssert); - consoleVal.toObject()->defineFunction("assert", _SE(JSB_console_assert)); + __consoleVal.toObject()->getProperty("assert", &__oldConsoleAssert); + __consoleVal.toObject()->defineFunction("assert", _SE(JSB_console_assert)); } _globalObj->setProperty("scriptEngineType", Value("JavaScriptCore")); @@ -285,7 +310,7 @@ namespace se { if (!_isValid) return; - LOGD("ScriptEngine::cleanup begin ...\n"); + SE_LOGD("ScriptEngine::cleanup begin ...\n"); _isInCleanup = true; for (const auto& hook : _beforeCleanupHookArray) { @@ -298,6 +323,7 @@ namespace se { Class::cleanup(); garbageCollect(); + __consoleVal.setUndefined(); __oldConsoleLog.setUndefined(); __oldConsoleDebug.setUndefined(); __oldConsoleInfo.setUndefined(); @@ -322,7 +348,7 @@ namespace se { NativePtrToObjectMap::destroy(); NonRefNativePtrCreatedByCtorMap::destroy(); - LOGD("ScriptEngine::cleanup end ...\n"); + SE_LOGD("ScriptEngine::cleanup end ...\n"); } ScriptEngine::ExceptionInfo ScriptEngine::_formatException(JSValueRef exception) @@ -403,7 +429,7 @@ namespace se { { exceptionStr += "\nSTACK:\n" + exceptionInfo.stack; } - LOGD("ERROR: %s\n", exceptionStr.c_str()); + SE_LOGD("ERROR: %s\n", exceptionStr.c_str()); if (_exceptionCallback != nullptr) { @@ -429,7 +455,7 @@ namespace se { } else { - LOGE("ERROR: __errorHandler has exception\n"); + SE_LOGE("ERROR: __errorHandler has exception\n"); } } } @@ -504,10 +530,18 @@ namespace se { void ScriptEngine::garbageCollect() { - LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); - // JSGarbageCollect(_cx); + // JSSynchronousGarbageCollectForDebugging is private API in JavaScriptCore framework. + // AppStore will reject the apps reference non-public symbols. + // Therefore, we use JSSynchronousGarbageCollectForDebugging for easily debugging memory + // problems in debug mode, and use public API JSGarbageCollect in release mode to pass + // the AppStore's verify check. +#if SE_DEBUG > 0 + SE_LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); JSSynchronousGarbageCollectForDebugging(_cx); - LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); + SE_LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size()); +#else + JSGarbageCollect(_cx); +#endif } bool ScriptEngine::evalString(const char* script, ssize_t length/* = -1 */, Value* ret/* = nullptr */, const char* fileName/* = nullptr */) @@ -550,7 +584,7 @@ namespace se { { if (exception == nullptr) { - LOGD("Unknown syntax error parsing file %s\n", fileName); + SE_LOGD("Unknown syntax error parsing file %s\n", fileName); } } @@ -585,46 +619,10 @@ namespace se { return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str()); } - LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str()); + SE_LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str()); return false; } - void ScriptEngine::_retainScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - iterOwner->second->attachObject(iterTarget->second); - } - - void ScriptEngine::_releaseScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - iterOwner->second->detachObject(iterTarget->second); - } - void ScriptEngine::clearException() { //FIXME: diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.hpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.hpp index 4eedded9df..9aa5870654 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -41,7 +64,6 @@ namespace se { /** * @brief Destroys the instance of script engine. - * @return */ static void destroyInstance(); @@ -162,7 +184,7 @@ namespace se { * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. * @return true if succeed, otherwise false. */ - bool runScript(const std::string& path, Value* ret = nullptr); + bool runScript(const std::string& path, Value* rval = nullptr); /** * @brief Tests whether script engine is doing garbage collection. @@ -208,6 +230,7 @@ namespace se { /** * @brief Enables JavaScript debugger + * @param[in] serverAddr The address of debugger server. * @param[in] port The port of debugger server will use. */ void enableDebugger(const std::string& serverAddr, uint32_t port); @@ -229,12 +252,8 @@ namespace se { uint32_t getVMId() const { return _vmId; } // Private API used in wrapper - void _retainScriptObject(void* owner, void* target); - void _releaseScriptObject(void* owner, void* target); - void _clearException(JSValueRef exception); JSContextRef _getContext() const { return _cx; } - void _setGarbageCollecting(bool isGarbageCollecting); // private: diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/SeApi.h b/native/cocos/scripting/js-bindings/jswrapper/jsc/SeApi.h index 839c93a930..e1f652e67c 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/SeApi.h +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/SeApi.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "ScriptEngine.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp index fa169385f9..d68a3fe0f1 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp @@ -1,11 +1,26 @@ -// -// Utils.cpp -// cocos2d_js_bindings -// -// Created by James Chen on 4/26/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Utils.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC @@ -35,7 +50,7 @@ namespace se { ok = globalObject->getProperty("Object", &v); if (!ok || !v.isObject()) { - LOGD("ERROR: couldn't find Object\n"); + SE_LOGD("ERROR: couldn't find Object\n"); return false; } @@ -43,7 +58,7 @@ namespace se { ok = v.toObject()->getProperty("defineProperty", &definePropertyFunc); if (!ok || !v.isObject()) { - LOGD("ERROR: couldn't find Object.defineProperty\n"); + SE_LOGD("ERROR: couldn't find Object.defineProperty\n"); return false; } @@ -253,7 +268,9 @@ namespace se { } assert(finalizeCb); - HandleObject privateObj(Object::createObjectWithClass(__jsb_CCPrivateData_class)); + Object* privateObj = Object::createObjectWithClass(__jsb_CCPrivateData_class); + privateObj->root(); + internal::PrivateData* privateData = (internal::PrivateData*)malloc(sizeof(internal::PrivateData)); privateData->data = data; privateData->finalizeCb = finalizeCb; @@ -268,6 +285,9 @@ namespace se { ScriptEngine::getInstance()->_clearException(exception); } JSStringRelease(key); + + privateObj->unroot(); + privateObj->decRef(); } void* getPrivate(JSObjectRef obj) diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp index 43c3f8ef8f..90b87308fb 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Base.h b/native/cocos/scripting/js-bindings/jswrapper/sm/Base.h index 0acc0c8e48..d22ed3ab4d 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Base.h +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Base.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #ifndef UINT64_C diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Class.cpp b/native/cocos/scripting/js-bindings/jswrapper/sm/Class.cpp index d0e0b4b1fa..044226d676 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Class.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Class.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Class.hpp" #include "Object.hpp" #include "Utils.hpp" @@ -69,7 +92,7 @@ namespace se { _ctor = empty_constructor; } -// LOGD("Class init ( %s ) ...\n", clsName); +// SE_LOGD("Class init ( %s ) ...\n", clsName); return true; } @@ -112,7 +135,7 @@ namespace se { if (jsobj != nullptr) { _proto = Object::_createJSObject(nullptr, jsobj); -// LOGD("_proto: %p, name: %s\n", _proto, _name); +// SE_LOGD("_proto: %p, name: %s\n", _proto, _name); _proto->root(); return true; } diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Class.hpp b/native/cocos/scripting/js-bindings/jswrapper/sm/Class.hpp index af87e580fa..679503ced5 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Class.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Class.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -10,28 +33,91 @@ namespace se { class Object; + /** + * se::Class represents a definition of how to create a native binding object. + */ class Class final { + public: + /** + * @brief Creates a class used for creating relevant native binding objects. + * @param[in] className A null-terminated UTF8 string containing the class's name. + * @param[in] obj The object that current class proto object attaches to. Should not be nullptr. + * @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent. + * @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor. + * @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 char* className, Object* obj, Object* parentProto, JSNative ctor); + + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineFunction(const char *name, JSNative func); + + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineProperty(const char *name, JSNative getter, JSNative setter); + + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineStaticFunction(const char *name, JSNative func); + + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineStaticProperty(const char *name, JSNative getter, JSNative setter); + + /** + * @brief Defines the finalize function with a callback. + * @param[in] func The callback to invoke when a JavaScript object is garbage collected. + * @return true if succeed, otherwise false. + */ + bool defineFinalizeFunction(JSFinalizeOp func); + + /** + * @brief Installs class to JavaScript VM. + * @return true if succeed, otherwise false. + * @note After this method, an object could be created by `var foo = new Foo();`. + */ + bool install(); + + /** + * @brief Gets the proto object of this class. + * @return The proto object of this class. + * @note Don't need to be released in user code. + */ + Object* getProto(); + + /** + * @brief Gets the class name. + * @return The class name. + */ + const char* getName() const { return _name; } + + // Private API used in wrapper + JSFinalizeOp _getFinalizeCb() const; + // private: Class(); ~Class(); - public: - static Class* create(const char* className, Object* obj, Object* parentProto, JSNative ctor); - - bool install(); - Object* getProto(); - JSFinalizeOp _getFinalizeCb() const; - - bool defineFunction(const char *name, JSNative func); - bool defineProperty(const char *name, JSNative getter, JSNative setter); - bool defineStaticFunction(const char *name, JSNative func); - bool defineStaticProperty(const char *name, JSNative getter, JSNative setter); - bool defineFinalizeFunction(JSFinalizeOp func); - - const char* getName() const { return _name; } - - private: bool init(const char* clsName, Object* obj, Object* parentProto, JSNative ctor); void destroy(); diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/sm/HelperMacros.h index 8b5066976f..584b52b7b6 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/HelperMacros.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -25,6 +48,9 @@ void* nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::setReturnValue(_cx, state.rval(), _argv); \ return ret; \ } @@ -36,11 +62,14 @@ void funcName##Registry(JSFreeOp* _fop, JSObject* _obj) \ { \ void* nativeThisObject = JS_GetPrivate(_obj); \ - bool ok = false; \ + bool ret = false; \ if (nativeThisObject == nullptr) \ return;\ se::State state(nativeThisObject); \ - ok = funcName(state); \ + ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ } @@ -62,6 +91,10 @@ _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return ret; \ } @@ -85,6 +118,10 @@ _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } \ + else \ + { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return ret; \ } @@ -99,6 +136,9 @@ void* nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \ se::State state(nativeThisObject); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::setReturnValue(_cx, state.rval(), _argv); \ return ret; \ } @@ -118,6 +158,9 @@ args.push_back(std::move(data)); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ return ret; \ } @@ -128,7 +171,7 @@ #define SE_QUOTEME(x) SE_QUOTEME_(x) #define SE_REPORT_ERROR(fmt, ...) \ - LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ + SE_LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ JS_ReportErrorUTF8(se::ScriptEngine::getInstance()->_getContext(), fmt, ##__VA_ARGS__) #if COCOS2D_DEBUG > 0 @@ -138,7 +181,7 @@ { \ if (!(cond)) \ { \ - LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ + SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ assert(false); \ } \ } while(false) diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/sm/Object.cpp index 9ab8dd148a..5e1759015b 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Object.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Object.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM @@ -118,17 +141,74 @@ namespace se { return obj; } - Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength) + Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength) { - JS::RootedObject jsobj(__cx, JS_NewUint8Array(__cx, (uint32_t)byteLength)); + if (type == TypedArrayType::NONE) + { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + if (type == TypedArrayType::UINT8_CLAMPED) + { + SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!"); + return nullptr; + } + + JSObject* arr = nullptr; + void* tmpData = nullptr; bool isShared = false; JS::AutoCheckCannotGC nogc; - uint8_t* tmpData = JS_GetUint8ArrayData(jsobj, &isShared, nogc); - memcpy((void*)tmpData, (const void*)data, byteLength); - Object* obj = Object::_createJSObject(nullptr, jsobj); + + switch (type) { + case TypedArrayType::INT8: + arr = JS_NewInt8Array(__cx, (uint32_t)byteLength); + tmpData = JS_GetInt8ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::INT16: + arr = JS_NewInt16Array(__cx, (uint32_t)byteLength/2); + tmpData = JS_GetInt16ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::INT32: + arr = JS_NewInt32Array(__cx, (uint32_t)byteLength/4); + tmpData = JS_GetInt32ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::UINT8: + arr = JS_NewUint8Array(__cx, (uint32_t)byteLength); + tmpData = JS_GetUint8ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::UINT16: + arr = JS_NewUint16Array(__cx, (uint32_t)byteLength/2); + tmpData = JS_GetUint16ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::UINT32: + arr = JS_NewUint32Array(__cx, (uint32_t)byteLength/4); + tmpData = JS_GetUint32ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::FLOAT32: + arr = JS_NewFloat32Array(__cx, (uint32_t)byteLength/4); + tmpData = JS_GetFloat32ArrayData(arr, &isShared, nogc); + break; + case TypedArrayType::FLOAT64: + arr = JS_NewFloat64Array(__cx, (uint32_t)byteLength/8); + tmpData = JS_GetFloat64ArrayData(arr, &isShared, nogc); + break; + default: + assert(false); // Should never go here. + break; + } + + memcpy(tmpData, (const void*)data, byteLength); + + Object* obj = Object::_createJSObject(nullptr, arr); return obj; } + Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount) + { + return createTypedArray(TypedArrayType::UINT8, data, dataCount); + } + Object* Object::createJSONObject(const std::string& jsonStr) { Value strVal(jsonStr); @@ -224,10 +304,10 @@ namespace se { return ok; } - bool Object::defineFunction(const char *funcName, JSNative func, int minArgs) + bool Object::defineFunction(const char *funcName, JSNative func) { JS::RootedObject object(__cx, _getJSObject()); - bool ok = JS_DefineFunction(__cx, object, funcName, func, minArgs, 0); + bool ok = JS_DefineFunction(__cx, object, funcName, func, 0, 0); return ok; } @@ -287,7 +367,33 @@ namespace se { bool Object::isTypedArray() const { - return JS_IsTypedArrayObject( _getJSObject()); + return JS_IsTypedArrayObject(_getJSObject()); + } + + Object::TypedArrayType Object::getTypedArrayType() const + { + TypedArrayType ret = TypedArrayType::NONE; + JSObject* obj = _getJSObject(); + if (JS_IsInt8Array(obj)) + ret = TypedArrayType::INT8; + else if (JS_IsInt16Array(obj)) + ret = TypedArrayType::INT16; + else if (JS_IsInt32Array(obj)) + ret = TypedArrayType::INT32; + else if (JS_IsUint8Array(obj)) + ret = TypedArrayType::UINT8; + else if (JS_IsUint8ClampedArray(obj)) + ret = TypedArrayType::UINT8_CLAMPED; + else if (JS_IsUint16Array(obj)) + ret = TypedArrayType::UINT16; + else if (JS_IsUint32Array(obj)) + ret = TypedArrayType::UINT32; + else if (JS_IsFloat32Array(obj)) + ret = TypedArrayType::FLOAT32; + else if (JS_IsFloat64Array(obj)) + ret = TypedArrayType::FLOAT64; + + return ret; } bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const @@ -536,54 +642,63 @@ namespace se { bool Object::attachObject(Object* obj) { assert(obj); - JSObject* ownerObj = _getJSObject(); - JSObject* targetObj = obj->_getJSObject(); - if (ownerObj == nullptr || targetObj == nullptr) + + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value jsbVal; + if (!global->getProperty("jsb", &jsbVal)) + return false; + Object* jsbObj = jsbVal.toObject(); + + Value func; + + if (!jsbObj->getProperty("registerNativeRef", &func)) return false; - JS::RootedValue valOwner(__cx, JS::ObjectValue(*ownerObj)); - JS::RootedValue valTarget(__cx, JS::ObjectValue(*targetObj)); - - JS::RootedObject jsbObj(__cx); - JS::RootedObject globalObj(__cx, ScriptEngine::getInstance()->getGlobalObject()->_getJSObject()); - get_or_create_js_obj(__cx, globalObj, "jsb", &jsbObj); - - JS::AutoValueVector args(__cx); - args.resize(2); - args[0].set(valOwner); - args[1].set(valTarget); - - JS::RootedValue rval(__cx); - - return JS_CallFunctionName(__cx, jsbObj, "registerNativeRef", args, &rval); + ValueArray args; + args.push_back(Value(this)); + args.push_back(Value(obj)); + func.toObject()->call(args, global); + return true; } bool Object::detachObject(Object* obj) { assert(obj); - JSObject* ownerObj = _getJSObject(); - JSObject* targetObj = obj->_getJSObject(); - if (ownerObj == nullptr || targetObj == nullptr) - { - LOGD("%s: try to detach on invalid object, owner: %p, target: %p\n", __FUNCTION__, ownerObj, targetObj); + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value jsbVal; + if (!global->getProperty("jsb", &jsbVal)) return false; + Object* jsbObj = jsbVal.toObject(); + + Value func; + + if (!jsbObj->getProperty("unregisterNativeRef", &func)) + return false; + + ValueArray args; + args.push_back(Value(this)); + args.push_back(Value(obj)); + func.toObject()->call(args, global); + return true; + } + + std::string Object::toString() const + { + std::string ret; + if (isFunction() || isArray() || isTypedArray()) + { + JS::RootedValue val(__cx, JS::ObjectOrNullValue(_getJSObject())); + internal::forceConvertJsValueToStdString(__cx, val, &ret); } - - JS::RootedValue valOwner(__cx, JS::ObjectValue(*ownerObj)); - JS::RootedValue valTarget(__cx, JS::ObjectValue(*targetObj)); - - JS::RootedObject jsbObj(__cx); - JS::RootedObject globalObj(__cx, ScriptEngine::getInstance()->getGlobalObject()->_getJSObject()); - get_or_create_js_obj(__cx, globalObj, "jsb", &jsbObj); - - JS::AutoValueVector args(__cx); - args.resize(2); - args[0].set(valOwner); - args[1].set(valTarget); - - JS::RootedValue rval(__cx); - - return JS_CallFunctionName(__cx, jsbObj, "unregisterNativeRef", args, &rval); + else if (isArrayBuffer()) + { + ret = "[object ArrayBuffer]"; + } + else + { + ret = "[object Object]"; + } + return ret; } } // namespace se { diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Object.hpp b/native/cocos/scripting/js-bindings/jswrapper/sm/Object.hpp index ef64affc3e..6edf7781a0 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Object.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Object.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -12,51 +35,322 @@ namespace se { class Class; + /** + * se::Object represents JavaScript Object. + */ class Object final : public RefCounter { public: + /** + * @brief Creates a JavaScript Object like `{} or new Object()`. + * @return A JavaScript Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createPlainObject(); - static Object* createObjectWithClass(Class* cls); + + /** + * @brief Creates a JavaScript Array Object like `[] or new Array()`. + * @param[in] length The initical length of array. + * @return A JavaScript Array Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createArrayObject(size_t length); - static Object* createUint8TypedArray(uint8_t* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + * @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead. + */ + SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* data, size_t byteLength); + + enum class TypedArrayType + { + NONE, + INT8, + INT16, + INT32, + UINT8, + UINT8_CLAMPED, + UINT16, + UINT32, + FLOAT32, + FLOAT64 + }; + + /** + * @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer. + * @param[in] type The format of typed array. + * @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Array Buffer object from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createArrayBufferObject(void* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Object from a JSON formatted string. + * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. + * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. + * @note The return value (non-null) has to be released manually. + */ static Object* createJSONObject(const std::string& jsonStr); + + /** + * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. + * @param[in] cls The se::Class instance which stores native callback informations. + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createObjectWithClass(Class* cls); + + /** + * @brief Gets a se::Object from an existing native object pointer. + * @param[in] ptr The native object pointer associated with the se::Object + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* getObjectWithPtr(void* ptr); - bool getProperty(const char* name, Value* data); - bool setProperty(const char* name, const Value& v); + /** + * @brief Gets a property from an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[out] value The property's value if object has the property, otherwise the undefined value. + * @return true if object has the property, otherwise false. + */ + bool getProperty(const char* name, Value* value); + + /** + * @brief Sets a property to an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] value A value to be used as the property's value. + * @return true if the property is set successfully, otherwise false. + */ + bool setProperty(const char* name, const Value& value); + + /** + * @brief Defines a property with native accessor callbacks for an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] getter The native callback for getter. + * @param[in] setter The native callback for setter. + * @return true if succeed, otherwise false. + */ bool defineProperty(const char *name, JSNative getter, JSNative setter); + /** + * @brief Defines a function with a native callback for an object. + * @param[in] funcName A utf-8 string containing the function name. + * @param[in] func The native callback triggered by JavaScript code. + * @return true if succeed, otherwise false. + */ + bool defineFunction(const char *funcName, JSNative func); + + /** + * @brief Tests whether an object can be called as a function. + * @return true if object can be called as a function, otherwise false. + */ bool isFunction() const; + + /** + * @brief Calls an object as a function. + * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. + * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." + * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. + * @return true if object is a function and there isn't any errors, otherwise false. + */ bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr); - bool defineFunction(const char *funcName, JSNative func, int minArgs = 0); - - bool isTypedArray() const; - bool getTypedArrayData(uint8_t** ptr, size_t* length) const; - + /** + * @brief Tests whether an object is an array. + * @return true if object is an array, otherwise false. + */ bool isArray() const; + + /** + * @brief Gets array length of an array object. + * @param[out] length The array length to be stored. It's set to 0 if there is an error. + * @return true if succeed, otherwise false. + */ bool getArrayLength(uint32_t* length) const; + + /** + * @brief Gets an element from an array object by numeric index. + * @param[in] index An integer value for index. + * @param[out] data The se::Value to be stored for the element in certain index. + * @return true if succeed, otherwise false. + */ bool getArrayElement(uint32_t index, Value* data) const; + + /** + * @brief Sets an element to an array object by numeric index. + * @param[in] index An integer value for index. + * @param[in] data The se::Value to be set to array with certain index. + * @return true if succeed, otherwise false. + */ bool setArrayElement(uint32_t index, const Value& data); + /** @brief Tests whether an object is a typed array. + * @return true if object is a typed array, otherwise false. + */ + bool isTypedArray() const; + + /** + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ + TypedArrayType getTypedArrayType() const; + + /** + * @brief Gets backing store of a typed array object. + * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. + * @param[out] length The byte length of a JavaScript Typed Array object. + * @return true if succeed, otherwise false. + */ + bool getTypedArrayData(uint8_t** ptr, size_t* length) const; + + /** + * @brief Tests whether an object is an array buffer object. + * @return true if object is an array buffer object, otherwise false. + */ bool isArrayBuffer() const; + + /** + * @brief Gets buffer data of an array buffer object. + * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. + * @param[out] length The number of bytes in a JavaScript data object. + * @return true if succeed, otherwise false. + */ bool getArrayBufferData(uint8_t** ptr, size_t* length) const; + /** + * @brief Gets all property names of an object. + * @param[out] allKeys A string vector to store all property names. + * @return true if succeed, otherwise false. + */ bool getAllKeys(std::vector* allKeys) const; + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by std::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ void setPrivateData(void* data); + + /** + * @brief Gets an object's private data. + * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. + */ void* getPrivateData() const; + + /** + * @brief Clears private data of an object. + */ void clearPrivateData(); + /** + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void root(); + + /** + * @brief Unroots an object from garbage collection. + * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void unroot(); + + /** + * @brief Tests whether an object is rooted. + * @return true if it has been already rooted, otherwise false. + */ bool isRooted() const; + /** + * @brief Tests whether two objects are strict equal, as compared by the JS === operator. + * @param[in] o The object to be tested with this object. + * @return true if the two values are strict equal, otherwise false. + */ bool strictEquals(Object* o) const; + + /** + * @brief Attaches an object to current object. + * @param[in] obj The object to be attached. + * @return true if succeed, otherwise false. + * @note This method will set `obj` as a property of current object, therefore the lifecycle of child object will depend on current object, + * which means `obj` may be garbage collected only after current object is garbage collected. + * It's normally used in binding a native callback method. For example: + + ```javascript + var self = this; + someObject.setCallback(function(){}, self); + ``` + + ```c++ + static bool SomeObject_setCallback(se::State& s) + { + SomeObject* cobj = (SomeObject*)s.nativeThisObject(); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 2) { + std::function arg0; + do { + if (args[0].isObject() && args[0].toObject()->isFunction()) + { + se::Value jsThis(args[1]); + se::Value jsFunc(args[0]); + + jsThis.toObject()->attachObject(jsFunc.toObject()); + + auto lambda = [=]() -> void { + ... + // Call jsFunc stuff... + ... + }; + arg0 = lambda; + } + else + { + arg0 = nullptr; + } + } while(false); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setCallback(arg0); + return true; + } + + return false; + } + ``` + */ bool attachObject(Object* obj); + + /** + * @brief Detaches an object from current object. + * @param[in] obj The object to be detached. + * @return true if succeed, otherwise false. + * @note The attached object will not be released if current object is not garbage collected. + */ bool detachObject(Object* obj); + /** + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ + std::string toString() const; + // Private API used in wrapper static Object* _createJSObject(Class* cls, JSObject* obj); void _setFinalizeCallback(JSFinalizeOp finalizeCb); diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.cpp b/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.cpp index 88bf8631f3..1b7e126fbc 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "ScriptEngine.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM @@ -23,7 +46,7 @@ #include #if SE_DEBUG -#define TRACE_DEBUGGER_SERVER(...) LOGD(__VA_ARGS__) +#define TRACE_DEBUGGER_SERVER(...) SE_LOGD(__VA_ARGS__) #else #define TRACE_DEBUGGER_SERVER(...) #endif // #if COCOS2D_DEBUG @@ -57,7 +80,7 @@ namespace se { MOZ_RELEASE_ASSERT(report); MOZ_RELEASE_ASSERT(JSREPORT_IS_WARNING(report->flags)); - LOGE("%s:%u:%s\n", report->filename ? report->filename : "", + SE_LOGE("%s:%u:%s\n", report->filename ? report->filename : "", (unsigned int) report->lineno, report->message().c_str()); } @@ -85,7 +108,7 @@ namespace se { JS::RootedString jsstr(cx, string); char* buffer = JS_EncodeStringToUTF8(cx, jsstr); - LOGD("JS: %s\n", buffer); + SE_LOGD("JS: %s\n", buffer); JS_free(cx, buffer); } @@ -123,11 +146,11 @@ namespace se { if (status == JSGC_BEGIN) { ScriptEngine::getInstance()->_setGarbageCollecting(true); - LOGD("on_garbage_collect: begin, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); + SE_LOGD("on_garbage_collect: begin, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); } else if (status == JSGC_END) { - LOGD("on_garbage_collect: end, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); + SE_LOGD("on_garbage_collect: end, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); ScriptEngine::getInstance()->_setGarbageCollecting(false); } } @@ -227,7 +250,7 @@ namespace se { if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { @@ -246,7 +269,7 @@ namespace se { } } - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } return true; @@ -387,7 +410,7 @@ namespace se { bool ScriptEngine::init() { cleanup(); - LOGD("Initializing SpiderMonkey, version: %s\n", JS_GetImplementationVersion()); + SE_LOGD("Initializing SpiderMonkey, version: %s\n", JS_GetImplementationVersion()); ++_vmId; for (const auto& hook : _beforeInitHookArray) @@ -766,7 +789,7 @@ namespace se { #endif if ((err = getaddrinfo(NULL, portstr.str().c_str(), &hints, &result)) != 0) { - LOGD("getaddrinfo error : %s\n", gai_strerror(err)); + SE_LOGD("getaddrinfo error : %s\n", gai_strerror(err)); } for (rp = result; rp != NULL; rp = rp->ai_next) { @@ -940,21 +963,30 @@ namespace se { bool ScriptEngine::getScript(const std::string& path, JS::MutableHandleScript script) { - // a) check jsc file first - std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; - if (_filenameScriptMap.find(byteCodePath) != _filenameScriptMap.end()) + std::string fullPath = _fileOperationDelegate.onGetFullPath(path); + auto iter = _filenameScriptMap.find(fullPath); + if (iter != _filenameScriptMap.end()) { - script.set(_filenameScriptMap[byteCodePath]->get()); + JS::PersistentRootedScript* rootedScript = iter->second; + script.set(rootedScript->get()); return true; } - // b) no jsc file, check js file - if (_filenameScriptMap.find(path) != _filenameScriptMap.end()) - { - script.set(_filenameScriptMap[path]->get()); - return true; - } - +// // a) check jsc file first +// std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; +// if (_filenameScriptMap.find(byteCodePath) != _filenameScriptMap.end()) +// { +// script.set(_filenameScriptMap[byteCodePath]->get()); +// return true; +// } +// +// // b) no jsc file, check js file +// if (_filenameScriptMap.find(path) != _filenameScriptMap.end()) +// { +// script.set(_filenameScriptMap[path]->get()); +// return true; +// } + return false; } @@ -971,28 +1003,31 @@ namespace se { bool compileSucceed = false; - // a) check jsc file first - std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; - - // Check whether '.jsc' files exist to avoid outputting log which says 'couldn't find .jsc file'. - if (_fileOperationDelegate.onCheckFileExist(byteCodePath)) - { - _fileOperationDelegate.onGetDataFromFile(byteCodePath, [&](const uint8_t* data, size_t dataLen) { - if (data != nullptr && dataLen > 0) - { - JS::TranscodeBuffer buffer; - bool appended = buffer.append(data, dataLen); - JS::TranscodeResult result = JS::DecodeScript(_cx, buffer, script); - if (appended && result == JS::TranscodeResult::TranscodeResult_Ok) - { - compileSucceed = true; - _filenameScriptMap[byteCodePath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get()); - } - assert(compileSucceed); - } - }); - - } + // Creator v1.7 supports v8, spidermonkey, javascriptcore and chakracore as its script engine, + // jsc file isn't bytecode format anymore, it's a xxtea encrpted binary format instead. + // Therefore, for unifying the flow, ScriptEngine class will not support spidermonkey bytecode. +// // a) check jsc file first +// std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; +// +// // Check whether '.jsc' files exist to avoid outputting log which says 'couldn't find .jsc file'. +// if (_fileOperationDelegate.onCheckFileExist(byteCodePath)) +// { +// _fileOperationDelegate.onGetDataFromFile(byteCodePath, [&](const uint8_t* data, size_t dataLen) { +// if (data != nullptr && dataLen > 0) +// { +// JS::TranscodeBuffer buffer; +// bool appended = buffer.append(data, dataLen); +// JS::TranscodeResult result = JS::DecodeScript(_cx, buffer, script); +// if (appended && result == JS::TranscodeResult::TranscodeResult_Ok) +// { +// compileSucceed = true; +// _filenameScriptMap[byteCodePath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get()); +// } +// assert(compileSucceed); +// } +// }); +// +// } // b) no jsc file, check js file if (!compileSucceed) @@ -1006,12 +1041,12 @@ namespace se { { JS::CompileOptions op(_cx); op.setUTF8(true); - std::string fullPath = _fileOperationDelegate.onGetFullPath(path); - op.setFileAndLine(fullPath.c_str(), 1); + op.setFileAndLine(path.c_str(), 1); ok = JS::Compile(_cx, op, jsFileContent.c_str(), jsFileContent.size(), script); if (ok) { compileSucceed = true; + std::string fullPath = _fileOperationDelegate.onGetFullPath(path); _filenameScriptMap[fullPath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get()); } assert(compileSucceed); @@ -1022,7 +1057,7 @@ namespace se { if (!compileSucceed) { - LOGD("ScriptEngine::compileScript fail:%s\n", path.c_str()); + SE_LOGD("ScriptEngine::compileScript fail:%s\n", path.c_str()); } return compileSucceed; @@ -1075,12 +1110,10 @@ namespace se { ok = JS_ExecuteScript(_cx, script, &rval); if (!ok) { - LOGE("Evaluating %s failed (evaluatedOK == JS_FALSE)\n", path.c_str()); + SE_LOGE("Evaluating %s failed (evaluatedOK == JS_FALSE)\n", path.c_str()); clearException(); } - assert(ok); - if (ok && ret != nullptr && !rval.isNullOrUndefined()) { internal::jsToSeValue(_cx, rval, ret); @@ -1090,42 +1123,6 @@ namespace se { return ok; } - void ScriptEngine::_retainScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - iterOwner->second->attachObject(iterTarget->second); - } - - void ScriptEngine::_releaseScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - iterOwner->second->detachObject(iterTarget->second); - } - void ScriptEngine::clearException() { if (_cx == nullptr) @@ -1165,7 +1162,7 @@ namespace se { exceptionStr += stack; } - LOGE("ERROR: %s\n", exceptionStr.c_str()); + SE_LOGE("ERROR: %s\n", exceptionStr.c_str()); if (_exceptionCallback != nullptr) { _exceptionCallback(location.c_str(), message, stack); @@ -1190,7 +1187,7 @@ namespace se { } else { - LOGE("ERROR: __errorHandler has exception\n"); + SE_LOGE("ERROR: __errorHandler has exception\n"); } if (stack != nullptr) diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.hpp b/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.hpp index ddd7ac5d23..f068690a7b 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/ScriptEngine.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -13,7 +36,13 @@ namespace se { class Value; extern Class* __jsb_CCPrivateData_class; - + + /** + * A stack-allocated class that governs a number of local handles. + * It's only implemented for v8 wrapper now. + * Other script engine wrappers have empty implementation for this class. + * It's used at the beginning of executing any wrapper API. + */ class AutoHandleScope { public: @@ -21,24 +50,52 @@ namespace se { ~AutoHandleScope(); }; + /** + * ScriptEngine is a sington which represents a context of JavaScript VM. + */ class ScriptEngine final { - private: - ScriptEngine(); - ~ScriptEngine(); - public: + /** + * @brief Gets or creates the instance of script engine. + * @return The script engine instance. + */ static ScriptEngine* getInstance(); + + /** + * @brief Destroys the instance of script engine. + */ static void destroyInstance(); + /** + * @brief Gets the global object of JavaScript VM. + * @return The se::Object stores the global JavaScript object. + */ Object* getGlobalObject(); typedef bool (*RegisterCallback)(Object*); + + /** + * @brief Adds a callback for registering a native binding module. + * @param[in] cb A callback for registering a native binding module. + * @note This method just add a callback to a vector, callbacks is invoked in `start` method. + */ void addRegisterCallback(RegisterCallback cb); + + /** + * @brief Starts the script engine. + * @return true if succeed, otherwise false. + * @note This method will invoke all callbacks of native binding modules by the order of registration. + */ bool start(); + /** + * @brief Initializes script engine. + * @return true if succeed, otherwise false. + * @note This method will create JavaScript context and global object. + */ bool init(); - void cleanup(); + /** * @brief Adds a hook function before initializing script engine. * @param[in] hook A hook function to be invoked before initializing script engine. @@ -53,11 +110,39 @@ namespace se { */ void addAfterInitHook(const std::function& hook); + /** + * @brief Cleanups script engine. + * @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf. + */ + void cleanup(); + + /** + * @brief Adds a hook function before cleanuping script engine. + * @param[in] hook A hook function to be invoked before cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ void addBeforeCleanupHook(const std::function& hook); + + /** + * @brief Adds a hook function after cleanuping script engine. + * @param[in] hook A hook function to be invoked after cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ void addAfterCleanupHook(const std::function& hook); - bool evalString(const char* string, ssize_t length = -1, Value* ret = nullptr, const char* fileName = nullptr); + /** + * @brief Executes a utf-8 string buffer which contains JavaScript code. + * @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. + * @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated. + * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. + * @return true if succeed, otherwise false. + */ + bool evalString(const char* scriptStr, ssize_t length = -1, Value* rval = nullptr, const char* fileName = nullptr); + /** + * Delegate class for file operation + */ class FileOperationDelegate { public: @@ -84,38 +169,94 @@ namespace se { std::function onGetFullPath; }; + /** + * @brief Sets the delegate for file operation. + * @param delegate[in] The delegate instance for file operation. + */ void setFileOperationDelegate(const FileOperationDelegate& delegate); - bool runScript(const std::string& fullPath, Value* ret = nullptr); - - JSContext* _getContext() { return _cx; } + /** + * @brief Executes a file which contains JavaScript code. + * @param[in] path Script file path. + * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @return true if succeed, otherwise false. + */ + bool runScript(const std::string& path, Value* rval = nullptr); + /** + * @brief Tests whether script engine is doing garbage collection. + * @return true if it's in garbage collection, otherwise false. + */ bool isGarbageCollecting(); - void _setGarbageCollecting(bool isGarbageCollecting); + + /** + * @brief Performs a JavaScript garbage collection. + */ void garbageCollect() { JS_GC( _cx ); } - bool isValid() { return _isValid; } + /** + * @brief Tests whether script engine is being cleaned up. + * @return true if it's in cleaning up, otherwise false. + */ bool isInCleanup() { return _isInCleanup; } + /** + * @brief Tests whether script engine is valid. + * @return true if it's valid, otherwise false. + */ + bool isValid() { return _isValid; } + + /** + * @brief Clears all exceptions. + */ void clearException(); using ExceptionCallback = std::function; // location, message, stack + + /** + * @brief Sets the callback function while an exception is fired. + * @param[in] cb The callback function to notify that an exception is fired. + */ void setExceptionCallback(const ExceptionCallback& cb); + /** + * @brief Gets the start time of script engine. + * @return The start time of script engine. + */ const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; } + /** + * @brief Enables JavaScript debugger + * @param[in] serverAddr The address of debugger server. + * @param[in] port The port of debugger server will use. + */ void enableDebugger(const std::string& serverAddr, uint32_t port); + + /** + * @brief Tests whether JavaScript debugger is enabled + * @return true if JavaScript debugger is enabled, otherwise false. + */ bool isDebuggerEnabled() const; + + /** + * @brief Main loop update trigger, it's need to invoked in main thread every frame. + */ void mainLoopUpdate(); + /** + * @brief Gets script virtual machine instance ID. Default value is 1, increase by 1 if `init` is invoked. + */ uint32_t getVMId() const { return _vmId; } - void _retainScriptObject(void* owner, void* target); - void _releaseScriptObject(void* owner, void* target); - + // Private API used in wrapper + JSContext* _getContext() { return _cx; } + void _setGarbageCollecting(bool isGarbageCollecting); void _debugProcessInput(const std::string& str); - + // private: + ScriptEngine(); + ~ScriptEngine(); + static void onWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data); static void onWeakPointerZoneGroupCallback(JSContext* cx, void* data); diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/SeApi.h b/native/cocos/scripting/js-bindings/jswrapper/sm/SeApi.h index 839c93a930..e1f652e67c 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/SeApi.h +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/SeApi.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "ScriptEngine.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.cpp b/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.cpp index da17808dce..fd30284664 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.cpp @@ -1,11 +1,26 @@ -// -// Utils.cpp -// cocos2d_js_bindings -// -// Created by James Chen on 4/26/17. -// -// +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Utils.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM @@ -18,6 +33,13 @@ namespace se { namespace internal { + void forceConvertJsValueToStdString(JSContext* cx, JS::HandleValue jsval, std::string* ret) + { + assert(ret != nullptr); + JS::RootedString jsStr(cx, JS::ToString(cx, jsval)); + *ret = jsToStdString(cx, jsStr); + } + std::string jsToStdString(JSContext* cx, JS::HandleString jsStr) { char* str = JS_EncodeStringToUTF8(cx, jsStr); diff --git a/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.hpp b/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.hpp index 3fdb565988..c07b270b0c 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/sm/Utils.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -20,6 +43,7 @@ namespace se { JSFinalizeOp finalizeCb; }; + void forceConvertJsValueToStdString(JSContext* cx, JS::HandleValue jsval, std::string* ret); std::string jsToStdString(JSContext* cx, JS::HandleString jsStr); void jsToSeArgs(JSContext* cx, int argc, const JS::CallArgs& argv, ValueArray* outArr); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Base.h b/native/cocos/scripting/js-bindings/jswrapper/v8/Base.h index 150aebb816..71126068f1 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Base.h +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Base.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "libplatform/libplatform.h" diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Class.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Class.cpp index e4a3d06cdf..7249ba451a 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Class.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Class.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Class.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Class.hpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Class.hpp index 2cf8248ec5..51fc98235e 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Class.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Class.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -10,34 +33,95 @@ namespace se { class Object; + /** + * se::Class represents a definition of how to create a native binding object. + */ class Class final { - private: - Class(); - ~Class(); public: + /** + * @brief Creates a class used for creating relevant native binding objects. + * @param[in] className A null-terminated UTF8 string containing the class's name. + * @param[in] obj The object that current class proto object attaches to. Should not be nullptr. + * @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent. + * @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor. + * @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 std::string& className, Object* obj, Object* parentProto, v8::FunctionCallback ctor); - static Class* create(const std::string& clsName, Object* parent, Object* parentProto, v8::FunctionCallback ctor); - - bool install(); - void destroy(); - + /** + * @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. + * @return true if succeed, otherwise false. + */ bool defineFunction(const char *name, v8::FunctionCallback func); - bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); - bool defineStaticFunction(const char *name, v8::FunctionCallback func); - bool defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); - bool defineFinalizeFunction(V8FinalizeFunc finalizeFunc); + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); + + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineStaticFunction(const char *name, v8::FunctionCallback func); + + /** + * @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. + * @return true if succeed, otherwise false. + */ + bool defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); + + /** + * @brief Defines the finalize function with a callback. + * @param[in] func The callback to invoke when a JavaScript object is garbage collected. + * @return true if succeed, otherwise false. + */ + bool defineFinalizeFunction(V8FinalizeFunc func); + + /** + * @brief Installs class to JavaScript VM. + * @return true if succeed, otherwise false. + * @note After this method, an object could be created by `var foo = new Foo();`. + */ + bool install(); + + /** + * @brief Gets the proto object of this class. + * @return The proto object of this class. + * @note Don't need to be released in user code. + */ Object* getProto() const; - V8FinalizeFunc _getFinalizeFunction() const; - + /** + * @brief Gets the class name. + * @return The class name. + */ const char* getName() const { return _name.c_str(); } + // Private API used in wrapper + V8FinalizeFunc _getFinalizeFunction() const; private: + Class(); + ~Class(); + void setCreateProto(bool createProto); bool init(const std::string& clsName, Object* parent, Object* parentProto, v8::FunctionCallback ctor); + void destroy(); + static void cleanup(); // static v8::Local _createJSObject(const std::string &clsName, Class** outCls); static v8::Local _createJSObjectWithClass(Class* cls); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/v8/HelperMacros.h index 6656543188..a136402888 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/HelperMacros.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -31,6 +54,9 @@ void* nativeThisObject = se::internal::getPrivate(_isolate, _v8args.This()); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::setReturnValue(state.rval(), _v8args); \ } @@ -42,7 +68,10 @@ auto se = se::ScriptEngine::getInstance(); \ se->_setGarbageCollecting(true); \ se::State state(nativeThisObject); \ - SE_UNUSED bool ok = funcName(state); \ + bool ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se->_setGarbageCollecting(false); \ } @@ -55,13 +84,16 @@ { \ v8::Isolate* _isolate = _v8args.GetIsolate(); \ v8::HandleScope _hs(_isolate); \ - SE_UNUSED bool ret = true; \ + bool ret = true; \ se::ValueArray args; \ se::internal::jsToSeArgs(_v8args, &args); \ se::Object* thisObject = se::Object::_createJSObject(cls, _v8args.This()); \ thisObject->_setFinalizeCallback(_SE(finalizeCb)); \ se::State state(thisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::Value _property; \ bool _found = false; \ _found = thisObject->getProperty("_ctor", &_property); \ @@ -80,6 +112,9 @@ void* nativeThisObject = se::internal::getPrivate(_isolate, _v8args.This()); \ se::State state(nativeThisObject); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ se::internal::setReturnValue(state.rval(), _v8args); \ } @@ -97,6 +132,9 @@ args.push_back(std::move(data)); \ se::State state(nativeThisObject, args); \ ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ } @@ -107,7 +145,7 @@ #define SE_QUOTEME(x) SE_QUOTEME_(x) //FIXME: implement this macro -#define SE_REPORT_ERROR(fmt, ...) LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) +#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) #if COCOS2D_DEBUG > 0 @@ -116,7 +154,7 @@ { \ if (!(cond)) \ { \ - LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ + SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \ assert(false); \ } \ } while(false) diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp index 00c4557eb3..2ed6e97604 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Object.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 @@ -186,15 +209,62 @@ namespace se { return obj; } - Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength) + Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength) { + if (type == TypedArrayType::NONE) + { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + if (type == TypedArrayType::UINT8_CLAMPED) + { + SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!"); + return nullptr; + } + v8::Local jsobj = v8::ArrayBuffer::New(__isolate, byteLength); memcpy(jsobj->GetContents().Data(), data, byteLength); - v8::Local arr = v8::Uint8Array::New(jsobj, 0, byteLength); + v8::Local arr; + switch (type) { + case TypedArrayType::INT8: + arr = v8::Int8Array::New(jsobj, 0, byteLength); + break; + case TypedArrayType::INT16: + arr = v8::Int16Array::New(jsobj, 0, byteLength / 2); + break; + case TypedArrayType::INT32: + arr = v8::Int32Array::New(jsobj, 0, byteLength / 4); + break; + case TypedArrayType::UINT8: + arr = v8::Uint8Array::New(jsobj, 0, byteLength); + break; + case TypedArrayType::UINT16: + arr = v8::Uint16Array::New(jsobj, 0, byteLength / 2); + break; + case TypedArrayType::UINT32: + arr = v8::Uint32Array::New(jsobj, 0, byteLength / 4); + break; + case TypedArrayType::FLOAT32: + arr = v8::Float32Array::New(jsobj, 0, byteLength / 4); + break; + case TypedArrayType::FLOAT64: + arr = v8::Float64Array::New(jsobj, 0, byteLength / 8); + break; + default: + assert(false); // Should never go here. + break; + } + Object* obj = Object::_createJSObject(nullptr, arr); return obj; } + Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount) + { + return createTypedArray(TypedArrayType::UINT8, data, dataCount); + } + Object* Object::createJSONObject(const std::string& jsonStr) { v8::Local context = __isolate->GetCurrentContext(); @@ -267,7 +337,7 @@ namespace se { v8::Maybe ret = _obj.handle(__isolate)->Set(__isolate->GetCurrentContext(), nameValue.ToLocalChecked(), value); if (ret.IsNothing()) { - LOGD("ERROR: %s, Set return nothing ...\n", __FUNCTION__); + SE_LOGD("ERROR: %s, Set return nothing ...\n", __FUNCTION__); return false; } return true; @@ -294,8 +364,7 @@ namespace se { { if (isFunction()) { - v8::String::Utf8Value utf8(const_cast(this)->_obj.handle(__isolate)); - std::string info = *utf8; + std::string info = toString(); if (info.find("[native code]") != std::string::npos) { return true; @@ -309,14 +378,40 @@ namespace se { return const_cast(this)->_obj.handle(__isolate)->IsTypedArray(); } + Object::TypedArrayType Object::getTypedArrayType() const + { + v8::Local value = const_cast(this)->_obj.handle(__isolate); + TypedArrayType ret = TypedArrayType::NONE; + if (value->IsInt8Array()) + ret = TypedArrayType::INT8; + else if (value->IsInt16Array()) + ret = TypedArrayType::INT16; + else if (value->IsInt32Array()) + ret = TypedArrayType::INT32; + else if (value->IsUint8Array()) + ret = TypedArrayType::UINT8; + else if (value->IsUint8ClampedArray()) + ret = TypedArrayType::UINT8_CLAMPED; + else if (value->IsUint16Array()) + ret = TypedArrayType::UINT16; + else if (value->IsUint32Array()) + ret = TypedArrayType::UINT32; + else if (value->IsFloat32Array()) + ret = TypedArrayType::FLOAT32; + else if (value->IsFloat64Array()) + ret = TypedArrayType::FLOAT64; + + return ret; + } + bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const { assert(isTypedArray()); v8::Local obj = const_cast(this)->_obj.handle(__isolate); - v8::Local arr = v8::Local::Cast(obj); + v8::Local arr = v8::Local::Cast(obj); v8::ArrayBuffer::Contents content = arr->Buffer()->GetContents(); - *ptr = (uint8_t*)content.Data(); - *length = content.ByteLength(); + *ptr = (uint8_t*)content.Data() + arr->ByteOffset(); + *length = arr->ByteLength(); return true; } @@ -380,7 +475,7 @@ namespace se { { if (_obj.persistent().IsEmpty()) { - LOGD("Function object is released!\n"); + SE_LOGD("Function object is released!\n"); return false; } size_t argc = 0; @@ -393,7 +488,7 @@ namespace se { { if (thisObject->_obj.persistent().IsEmpty()) { - LOGD("This object is released!\n"); + SE_LOGD("This object is released!\n"); return false; } thiz = thisObject->_obj.handle(__isolate); @@ -403,7 +498,7 @@ namespace se { { if (argv[i].IsEmpty()) { - LOGD("%s argv[%d] is released!\n", __FUNCTION__, (int)i); + SE_LOGD("%s argv[%d] is released!\n", __FUNCTION__, (int)i); return false; } } @@ -694,6 +789,24 @@ namespace se { return true; } + std::string Object::toString() const + { + std::string ret; + if (isFunction() || isArray() || isTypedArray()) + { + v8::String::Utf8Value utf8(const_cast(this)->_obj.handle(__isolate)); + ret = *utf8; + } + else if (isArrayBuffer()) + { + ret = "[object ArrayBuffer]"; + } + else + { + ret = "[object Object]"; + } + return ret; + } } // namespace se { diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.hpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.hpp index 3324d33cc7..1d397461bb 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -17,53 +40,322 @@ namespace se { struct PrivateData; } + /** + * se::Object represents JavaScript Object. + */ class Object final : public RefCounter { public: + /** + * @brief Creates a JavaScript Object like `{} or new Object()`. + * @return A JavaScript Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createPlainObject(); + + /** + * @brief Creates a JavaScript Array Object like `[] or new Array()`. + * @param[in] length The initical length of array. + * @return A JavaScript Array Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createArrayObject(size_t length); - static Object* createUint8TypedArray(uint8_t* data, size_t byteLength); - static Object* createArrayBufferObject(void* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + * @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead. + */ + SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength); + + enum class TypedArrayType + { + NONE, + INT8, + INT16, + INT32, + UINT8, + UINT8_CLAMPED, + UINT16, + UINT32, + FLOAT32, + FLOAT64 + }; + + /** + * @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer. + * @param[in] type The format of typed array. + * @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength); + + /** + * @brief Creates a JavaScript Array Buffer object from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* createArrayBufferObject(void* bytes, size_t byteLength); + + /** + * @brief Creates a JavaScript Object from a JSON formatted string. + * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. + * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. + * @note The return value (non-null) has to be released manually. + */ static Object* createJSONObject(const std::string& jsonStr); - static Object* getObjectWithPtr(void* ptr); + + /** + * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. + * @param[in] cls The se::Class instance which stores native callback informations. + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object* createObjectWithClass(Class* cls); + /** + * @brief Gets a se::Object from an existing native object pointer. + * @param[in] ptr The native object pointer associated with the se::Object + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object* getObjectWithPtr(void* ptr); - bool getProperty(const char *name, Value* data); - bool setProperty(const char *name, const Value& data); + /** + * @brief Gets a property from an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[out] value The property's value if object has the property, otherwise the undefined value. + * @return true if object has the property, otherwise false. + */ + bool getProperty(const char *name, Value* value); + + /** + * @brief Sets a property to an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] value A value to be used as the property's value. + * @return true if the property is set successfully, otherwise false. + */ + bool setProperty(const char *name, const Value& value); + + /** + * @brief Defines a property with native accessor callbacks for an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] getter The native callback for getter. + * @param[in] setter The native callback for setter. + * @return true if succeed, otherwise false. + */ bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); - bool isFunction() const; - - bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr); - + /** + * @brief Defines a function with a native callback for an object. + * @param[in] funcName A utf-8 string containing the function name. + * @param[in] func The native callback triggered by JavaScript code. + * @return true if succeed, otherwise false. + */ bool defineFunction(const char *funcName, v8::FunctionCallback func); - bool isTypedArray() const; - bool getTypedArrayData(uint8_t** ptr, size_t* length) const; + /** + * @brief Tests whether an object can be called as a function. + * @return true if object can be called as a function, otherwise false. + */ + bool isFunction() const; + /** + * @brief Calls an object as a function. + * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. + * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." + * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. + * @return true if object is a function and there isn't any errors, otherwise false. + */ + bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr); + + /** + * @brief Tests whether an object is an array. + * @return true if object is an array, otherwise false. + */ bool isArray() const; + + /** + * @brief Gets array length of an array object. + * @param[out] length The array length to be stored. It's set to 0 if there is an error. + * @return true if succeed, otherwise false. + */ bool getArrayLength(uint32_t* length) const; + + /** + * @brief Gets an element from an array object by numeric index. + * @param[in] index An integer value for index. + * @param[out] data The se::Value to be stored for the element in certain index. + * @return true if succeed, otherwise false. + */ bool getArrayElement(uint32_t index, Value* data) const; + + /** + * @brief Sets an element to an array object by numeric index. + * @param[in] index An integer value for index. + * @param[in] data The se::Value to be set to array with certain index. + * @return true if succeed, otherwise false. + */ bool setArrayElement(uint32_t index, const Value& data); + /** @brief Tests whether an object is a typed array. + * @return true if object is a typed array, otherwise false. + */ + bool isTypedArray() const; + + /** + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ + TypedArrayType getTypedArrayType() const; + + /** + * @brief Gets backing store of a typed array object. + * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. + * @param[out] length The byte length of a JavaScript Typed Array object. + * @return true if succeed, otherwise false. + */ + bool getTypedArrayData(uint8_t** ptr, size_t* length) const; + + /** + * @brief Tests whether an object is an array buffer object. + * @return true if object is an array buffer object, otherwise false. + */ bool isArrayBuffer() const; + + /** + * @brief Gets buffer data of an array buffer object. + * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. + * @param[out] length The number of bytes in a JavaScript data object. + * @return true if succeed, otherwise false. + */ bool getArrayBufferData(uint8_t** ptr, size_t* length) const; + /** + * @brief Gets all property names of an object. + * @param[out] allKeys A string vector to store all property names. + * @return true if succeed, otherwise false. + */ bool getAllKeys(std::vector* allKeys) const; + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by std::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ void setPrivateData(void* data); + + /** + * @brief Gets an object's private data. + * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. + */ void* getPrivateData() const; + + /** + * @brief Clears private data of an object. + */ void clearPrivateData(); + /** + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void root(); + + /** + * @brief Unroots an object from garbage collection. + * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void unroot(); + + /** + * @brief Tests whether an object is rooted. + * @return true if it has been already rooted, otherwise false. + */ bool isRooted() const; + /** + * @brief Tests whether two objects are strict equal, as compared by the JS === operator. + * @param[in] o The object to be tested with this object. + * @return true if the two values are strict equal, otherwise false. + */ bool strictEquals(Object* o) const; + + /** + * @brief Attaches an object to current object. + * @param[in] obj The object to be attached. + * @return true if succeed, otherwise false. + * @note This method will set `obj` as a property of current object, therefore the lifecycle of child object will depend on current object, + * which means `obj` may be garbage collected only after current object is garbage collected. + * It's normally used in binding a native callback method. For example: + + ```javascript + var self = this; + someObject.setCallback(function(){}, self); + ``` + + ```c++ + static bool SomeObject_setCallback(se::State& s) + { + SomeObject* cobj = (SomeObject*)s.nativeThisObject(); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 2) { + std::function arg0; + do { + if (args[0].isObject() && args[0].toObject()->isFunction()) + { + se::Value jsThis(args[1]); + se::Value jsFunc(args[0]); + + jsThis.toObject()->attachObject(jsFunc.toObject()); + + auto lambda = [=]() -> void { + ... + // Call jsFunc stuff... + ... + }; + arg0 = lambda; + } + else + { + arg0 = nullptr; + } + } while(false); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setCallback(arg0); + return true; + } + + return false; + } + ``` + */ bool attachObject(Object* obj); + + /** + * @brief Detaches an object from current object. + * @param[in] obj The object to be detached. + * @return true if succeed, otherwise false. + * @note The attached object will not be released if current object is not garbage collected. + */ bool detachObject(Object* obj); + /** + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ + std::string toString() const; + // Private API used in wrapper static Object* _createJSObject(Class* cls, v8::Local obj); v8::Local _getJSObject() const; diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/ObjectWrap.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/ObjectWrap.cpp index 5e63a5ce03..39948d5b9f 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/ObjectWrap.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/ObjectWrap.cpp @@ -1,3 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. #include "ObjectWrap.h" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 @@ -81,7 +101,7 @@ namespace se { /*static*/ void ObjectWrap::weakCallback(const v8::WeakCallbackInfo &data) { ObjectWrap *wrap = data.GetParameter(); -// LOGD("weakCallback: %p, nativeObj = %p, finalize: %p\n", wrap, wrap->_nativeObj, wrap->_finalizeCb); +// SE_LOGD("weakCallback: %p, nativeObj = %p, finalize: %p\n", wrap, wrap->_nativeObj, wrap->_finalizeCb); assert(wrap->refs_ == 0); wrap->handle_.Reset(); if (wrap->_finalizeCb != nullptr) diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.cpp index 4669dbff7f..f8a95a2d6e 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "ScriptEngine.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 @@ -29,7 +52,7 @@ namespace se { if (info[0]->IsString()) { v8::String::Utf8Value utf8(info[0]); - LOGD("JS: %s\n", *utf8); + SE_LOGD("JS: %s\n", *utf8); } } @@ -41,6 +64,9 @@ namespace se { std::string stackTraceToString(v8::Local stack) { std::string stackStr; + if (stack.IsEmpty()) + return stackStr; + char tmp[100] = {0}; for (int i = 0, e = stack->GetFrameCount(); i < e; ++i) { @@ -96,7 +122,7 @@ namespace se { if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { @@ -115,7 +141,7 @@ namespace se { } } - LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } return true; @@ -185,7 +211,7 @@ namespace se { errorStr += ", message: "; errorStr += message; - LOGE("%s\n", errorStr.c_str()); + SE_LOGE("%s\n", errorStr.c_str()); if (getInstance()->_exceptionCallback != nullptr) { getInstance()->_exceptionCallback(location, message, "(no stack information)"); @@ -204,7 +230,7 @@ namespace se { message += "false"; errorStr += ", " + message; - LOGE("%s\n", errorStr.c_str()); + SE_LOGE("%s\n", errorStr.c_str()); if (getInstance()->_exceptionCallback != nullptr) { getInstance()->_exceptionCallback(location, message.c_str(), "(no stack information)"); @@ -226,9 +252,9 @@ namespace se { Value column; internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceColumnOffset(), &column); - std::string location = resouceNameVal.toString() + ":" + line.toStringForce() + ":" + column.toStringForce(); + std::string location = resouceNameVal.toStringForce() + ":" + line.toStringForce() + ":" + column.toStringForce(); - std::string errorStr = msgVal.toString() + ", " + location; + std::string errorStr = msgVal.toString() + ", location: " + location; std::string stackStr = stackTraceToString(message->GetStackTrace()); if (!stackStr.empty()) { @@ -238,7 +264,7 @@ namespace se { } errorStr += "\nSTACK:\n" + stackStr; } - LOGE("ERROR: %s\n", errorStr.c_str()); + SE_LOGE("ERROR: %s\n", errorStr.c_str()); if (thiz->_exceptionCallback != nullptr) { @@ -264,7 +290,7 @@ namespace se { } else { - LOGE("ERROR: __errorHandler has exception\n"); + SE_LOGE("ERROR: __errorHandler has exception\n"); } } @@ -306,6 +332,7 @@ namespace se { , _exceptionCallback(nullptr) #if SE_ENABLE_INSPECTOR , _env(nullptr) + , _isolateData(nullptr) #endif , _debuggerServerPort(0) , _vmId(0) @@ -334,7 +361,7 @@ namespace se { bool ScriptEngine::init() { cleanup(); - LOGD("Initializing V8, version: %s\n", v8::V8::GetVersion()); + SE_LOGD("Initializing V8, version: %s\n", v8::V8::GetVersion()); ++_vmId; for (const auto& hook : _beforeInitHookArray) @@ -417,7 +444,7 @@ namespace se { if (!_isValid) return; - LOGD("ScriptEngine::cleanup begin ...\n"); + SE_LOGD("ScriptEngine::cleanup begin ...\n"); _isInCleanup = true; { @@ -441,11 +468,19 @@ namespace se { __oldConsoleAssert.setUndefined(); #if SE_ENABLE_INSPECTOR - _env->inspector_agent()->Stop(); + if (_isolateData != nullptr) + { + node::FreeIsolateData(_isolateData); + _isolateData = nullptr; + } - node::FreeIsolateData(_isolateData); - _env->CleanupHandles(); - node::FreeEnvironment(_env); + if (_env != nullptr) + { + _env->inspector_agent()->Stop(); + _env->CleanupHandles(); + node::FreeEnvironment(_env); + _env = nullptr; + } #endif _context.Get(_isolate)->Exit(); @@ -472,7 +507,7 @@ namespace se { NativePtrToObjectMap::destroy(); NonRefNativePtrCreatedByCtorMap::destroy(); - LOGD("ScriptEngine::cleanup end ...\n"); + SE_LOGD("ScriptEngine::cleanup end ...\n"); } Object* ScriptEngine::getGlobalObject() const @@ -526,7 +561,8 @@ namespace se { options.set_inspector_enabled(true); options.set_port((int)_debuggerServerPort); options.set_host_name(_debuggerServerAddr.c_str()); - _env->inspector_agent()->Start(_platform, "", options); + bool ok = _env->inspector_agent()->Start(_platform, "", options); + assert(ok); #endif } // @@ -549,7 +585,7 @@ namespace se { void ScriptEngine::garbageCollect() { - LOGD("GC begin ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); + SE_LOGD("GC begin ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); const double kLongIdlePauseInSeconds = 1.0; _isolate->ContextDisposedNotification(); _isolate->IdleNotificationDeadline(_platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds); @@ -557,7 +593,7 @@ namespace se { // garbage and will therefore also invoke all weak callbacks of actually // unreachable persistent handles. _isolate->LowMemoryNotification(); - LOGD("GC end ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); + SE_LOGD("GC end ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size()); } bool ScriptEngine::isGarbageCollecting() @@ -647,48 +683,10 @@ namespace se { return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str()); } - LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str()); + SE_LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str()); return false; } - void ScriptEngine::_retainScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - AutoHandleScope hs; - iterOwner->second->attachObject(iterTarget->second); - } - - void ScriptEngine::_releaseScriptObject(void* owner, void* target) - { - auto iterOwner = NativePtrToObjectMap::find(owner); - if (iterOwner == NativePtrToObjectMap::end()) - { - return; - } - - auto iterTarget = NativePtrToObjectMap::find(target); - if (iterTarget == NativePtrToObjectMap::end()) - { - return; - } - - clearException(); - AutoHandleScope hs; - iterOwner->second->detachObject(iterTarget->second); - } - void ScriptEngine::clearException() { //FIXME: diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.hpp b/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.hpp index a09ccd7397..b1c454f58a 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/ScriptEngine.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" @@ -26,6 +49,12 @@ namespace se { extern Class* __jsb_CCPrivateData_class; + /** + * A stack-allocated class that governs a number of local handles. + * It's only implemented for v8 wrapper now. + * Other script engine wrappers have empty implementation for this class. + * It's used at the beginning of executing any wrapper API. + */ class AutoHandleScope { public: @@ -40,24 +69,51 @@ namespace se { v8::HandleScope _handleScope; }; + /** + * ScriptEngine is a sington which represents a context of JavaScript VM. + */ class ScriptEngine final { - private: - ScriptEngine(); - ~ScriptEngine(); public: - + /** + * @brief Gets or creates the instance of script engine. + * @return The script engine instance. + */ static ScriptEngine* getInstance(); + + /** + * @brief Destroys the instance of script engine. + */ static void destroyInstance(); + /** + * @brief Gets the global object of JavaScript VM. + * @return The se::Object stores the global JavaScript object. + */ Object* getGlobalObject() const; typedef bool (*RegisterCallback)(Object*); + + /** + * @brief Adds a callback for registering a native binding module. + * @param[in] cb A callback for registering a native binding module. + * @note This method just add a callback to a vector, callbacks is invoked in `start` method. + */ void addRegisterCallback(RegisterCallback cb); + + /** + * @brief Starts the script engine. + * @return true if succeed, otherwise false. + * @note This method will invoke all callbacks of native binding modules by the order of registration. + */ bool start(); + /** + * @brief Initializes script engine. + * @return true if succeed, otherwise false. + * @note This method will create JavaScript context and global object. + */ bool init(); - void cleanup(); /** * @brief Adds a hook function before initializing script engine. @@ -73,10 +129,35 @@ namespace se { */ void addAfterInitHook(const std::function& hook); + /** + * @brief Cleanups script engine. + * @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf. + */ + void cleanup(); + + /** + * @brief Adds a hook function before cleanuping script engine. + * @param[in] hook A hook function to be invoked before cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ void addBeforeCleanupHook(const std::function& hook); + + /** + * @brief Adds a hook function after cleanuping script engine. + * @param[in] hook A hook function to be invoked after cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ void addAfterCleanupHook(const std::function& hook); - bool evalString(const char* script, ssize_t length = -1, Value* ret = nullptr, const char* fileName = nullptr); + /** + * @brief Executes a utf-8 string buffer which contains JavaScript code. + * @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. + * @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated. + * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. + * @return true if succeed, otherwise false. + */ + bool evalString(const char* scriptStr, ssize_t length = -1, Value* rval = nullptr, const char* fileName = nullptr); /** * Delegate class for file operation @@ -122,33 +203,83 @@ namespace se { * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. * @return true if succeed, otherwise false. */ - bool runScript(const std::string& path, Value* ret = nullptr); + bool runScript(const std::string& path, Value* rval = nullptr); + /** + * @brief Tests whether script engine is doing garbage collection. + * @return true if it's in garbage collection, otherwise false. + */ bool isGarbageCollecting(); - void _setGarbageCollecting(bool isGarbageCollecting); + + /** + * @brief Performs a JavaScript garbage collection. + */ void garbageCollect(); - bool isValid() const; + /** + * @brief Tests whether script engine is being cleaned up. + * @return true if it's in cleaning up, otherwise false. + */ bool isInCleanup() { return _isInCleanup; } + /** + * @brief Tests whether script engine is valid. + * @return true if it's valid, otherwise false. + */ + bool isValid() const; + + /** + * @brief Clears all exceptions. + */ void clearException(); using ExceptionCallback = std::function; // location, message, stack + + /** + * @brief Sets the callback function while an exception is fired. + * @param[in] cb The callback function to notify that an exception is fired. + */ void setExceptionCallback(const ExceptionCallback& cb); + /** + * @brief Gets the start time of script engine. + * @return The start time of script engine. + */ const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; } + /** + * @brief Enables JavaScript debugger + * @param[in] serverAddr The address of debugger server. + * @param[in] port The port of debugger server will use. + */ void enableDebugger(const std::string& serverAddr, uint32_t port); + + /** + * @brief Tests whether JavaScript debugger is enabled + * @return true if JavaScript debugger is enabled, otherwise false. + */ bool isDebuggerEnabled() const; + + /** + * @brief Main loop update trigger, it's need to invoked in main thread every frame. + */ void mainLoopUpdate(); + /** + * @brief Gets script virtual machine instance ID. Default value is 1, increase by 1 if `init` is invoked. + */ uint32_t getVMId() const { return _vmId; } + // Private API used in wrapper void _retainScriptObject(void* owner, void* target); void _releaseScriptObject(void* owner, void* target); - v8::Local _getContext() const; + void _setGarbageCollecting(bool isGarbageCollecting); + // private: + ScriptEngine(); + ~ScriptEngine(); + static void privateDataFinalize(void* nativeObj); static void onFatalErrorCallback(const char* location, const char* message); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/SeApi.h b/native/cocos/scripting/js-bindings/jswrapper/v8/SeApi.h index aed8fb8d7b..22ffb9fb4a 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/SeApi.h +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/SeApi.h @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "ScriptEngine.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.cpp index 36e2daad6a..e18bf80c9f 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.cpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "Utils.hpp" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 @@ -173,7 +196,7 @@ namespace se { if (c > 0) { wrap.wrap(data); -// LOGD("setPrivate1: %p\n", data); +// SE_LOGD("setPrivate1: %p\n", data); if (outInternalData != nullptr) *outInternalData = nullptr; } @@ -191,7 +214,7 @@ namespace se { assert(!key.IsEmpty()); v8::Maybe ret = obj->Set(isolate->GetCurrentContext(), key.ToLocalChecked(), privateObj->_getJSObject()); assert(!ret.IsNothing()); -// LOGD("setPrivate: native data: %p\n", privateData); +// SE_LOGD("setPrivate: native data: %p\n", privateData); // privateObj->decRef(); // NOTE: it's released in ScriptEngine::privateDataFinalize if (outInternalData != nullptr) @@ -211,7 +234,7 @@ namespace se { if (c > 0) { void* nativeObj = ObjectWrap::unwrap(objChecked); -// LOGD("getPrivate1: %p\n", nativeObj); +// SE_LOGD("getPrivate1: %p\n", nativeObj); return nativeObj; } @@ -233,7 +256,7 @@ namespace se { if (privateObj.IsEmpty()) return nullptr; PrivateData* privateData = (PrivateData*)ObjectWrap::unwrap(privateObj.ToLocalChecked()); -// LOGD("getPrivate: native data: %p\n", privateData); +// SE_LOGD("getPrivate: native data: %p\n", privateData); return privateData->data; } diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.hpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.hpp index 28d7c76dd7..16de049b2e 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Utils.hpp @@ -1,3 +1,26 @@ +/**************************************************************************** + Copyright (c) 2017 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #pragma once #include "../config.hpp" diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_agent.cc b/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_agent.cc index 1e3e23e6ed..655e61c3f6 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_agent.cc +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_agent.cc @@ -115,7 +115,7 @@ static int StartDebugSignalHandler() { CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr)); CHECK_EQ(0, pthread_attr_destroy(&attr)); if (err != 0) { - LOGE("node[%d]: pthread_create: %s\n", getpid(), strerror(err)); + SE_LOGE("node[%d]: pthread_create: %s\n", getpid(), strerror(err)); // Leave SIGUSR1 blocked. We don't install a signal handler, // receiving the signal would terminate the process. diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_io.cc b/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_io.cc index 3f9c35f739..d65870f803 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_io.cc +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_io.cc @@ -275,7 +275,7 @@ void InspectorIo::WaitForDisconnect() { if (state_ == State::kConnected) { state_ = State::kShutDown; Write(TransportAction::kStop, 0, StringView()); - LOGD("Waiting for the debugger to disconnect...\n"); + SE_LOGD("Waiting for the debugger to disconnect...\n"); parent_env_->inspector_agent()->RunMessageLoop(); } } @@ -415,7 +415,7 @@ void InspectorIo::DispatchMessages() { CHECK_EQ(session_delegate_, nullptr); session_id_ = std::get<1>(task); state_ = State::kConnected; - LOGD("Debugger attached.\n"); + SE_LOGD("Debugger attached.\n"); session_delegate_ = std::unique_ptr( new IoSessionDelegate(this)); parent_env_->inspector_agent()->Connect(session_delegate_.get()); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_socket_server.cc b/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_socket_server.cc index cec096f409..835fd805a1 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_socket_server.cc +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/inspector_socket_server.cc @@ -108,10 +108,10 @@ void PrintDebuggerReadyMessage(const std::string& host, return; } for (const std::string& id : ids) { - LOGD("Debugger listening..., visit [ chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=%s ] in chrome browser to debug!\n", + SE_LOGD("Debugger listening..., visit [ chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=%s ] in chrome browser to debug!\n", FormatWsAddress(host, port, id, false).c_str()); } - LOGD("For help see %s\n", + SE_LOGD("For help see %s\n", "https://nodejs.org/en/docs/inspector"); } @@ -407,7 +407,7 @@ bool InspectorSocketServer::Start() { int err = uv_getaddrinfo(loop_, &req, nullptr, host_.c_str(), port_string.c_str(), &hints); if (err < 0) { - LOGE("Unable to resolve \"%s\": %s\n", host_.c_str(), + SE_LOGE("Unable to resolve \"%s\": %s\n", host_.c_str(), uv_strerror(err)); return false; } @@ -423,7 +423,7 @@ bool InspectorSocketServer::Start() { // We only show error if we failed to start server on all addresses. We only // show one error, for the last address. if (server_sockets_.empty()) { - LOGE("Starting inspector on %s:%d failed: %s\n", + SE_LOGE("Starting inspector on %s:%d failed: %s\n", host_.c_str(), port_, uv_strerror(err)); return false; } diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/node.cc b/native/cocos/scripting/js-bindings/jswrapper/v8/node.cc index 77f3365e09..71c8637b6f 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/node.cc +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/node.cc @@ -711,7 +711,7 @@ NO_RETURN void Assert(const char* const (*args)[4]) { snprintf(pid, sizeof(pid), "[%u]", getpid()); #endif - LOGE("%s%s: %s:%s:%s%s Assertion `%s' failed.\n", + SE_LOGE("%s%s: %s:%s:%s%s Assertion `%s' failed.\n", exepath, pid, filename, linenum, function, *function ? ":" : "", message); @@ -810,7 +810,7 @@ void SetupProcessObject(Environment* env, "uv", OneByteString(env->isolate(), uv_version_string())); - LOGD("libuv version: %s\n", uv_version_string()); + SE_LOGD("libuv version: %s\n", uv_version_string()); // READONLY_PROPERTY(versions, // "zlib", // FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION)); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/node_debug_options.cc b/native/cocos/scripting/js-bindings/jswrapper/v8/node_debug_options.cc index 103435a5d0..86e0c5935b 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/node_debug_options.cc +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/node_debug_options.cc @@ -25,7 +25,7 @@ int parse_and_validate_port(const std::string& port) { const long result = strtol(port.c_str(), &endptr, 10); // NOLINT(runtime/int) if (errno != 0 || *endptr != '\0'|| (result != 0 && result < 1024) || result > 65535) { - LOGE("Debug port must be 0 or in range 1024 to 65535.\n"); + SE_LOGE("Debug port must be 0 or in range 1024 to 65535.\n"); exit(12); } return static_cast(result); @@ -98,7 +98,7 @@ bool DebugOptions::ParseOption(const char* argv0, const std::string& option) { } else if (option_name == "--debug-port" || option_name == "--inspect-port") { if (!has_argument) { - LOGE("%s: %s requires an argument\n", + SE_LOGE("%s: %s requires an argument\n", argv0, option.c_str()); exit(9); } @@ -108,7 +108,7 @@ bool DebugOptions::ParseOption(const char* argv0, const std::string& option) { #if !HAVE_INSPECTOR if (inspector_enabled_) { - LOGE("Inspector support is not available with this Node.js build\n"); + SE_LOGE("Inspector support is not available with this Node.js build\n"); } inspector_enabled_ = false; return false; diff --git a/native/cocos/scripting/js-bindings/manual/JavaScriptJavaBridge.cpp b/native/cocos/scripting/js-bindings/manual/JavaScriptJavaBridge.cpp index b9a4730b18..a6132b5163 100644 --- a/native/cocos/scripting/js-bindings/manual/JavaScriptJavaBridge.cpp +++ b/native/cocos/scripting/js-bindings/manual/JavaScriptJavaBridge.cpp @@ -213,7 +213,7 @@ bool JavaScriptJavaBridge::CallInfo::execute() default: m_error = JSJ_ERR_TYPE_NOT_SUPPORT; - LOGD("Return type '%d' is not supported", static_cast(m_returnType)); + SE_LOGD("Return type '%d' is not supported", static_cast(m_returnType)); return false; } @@ -263,7 +263,7 @@ bool JavaScriptJavaBridge::CallInfo::executeWithArgs(jvalue *args) default: m_error = JSJ_ERR_TYPE_NOT_SUPPORT; - LOGD("Return type '%d' is not supported", static_cast(m_returnType)); + SE_LOGD("Return type '%d' is not supported", static_cast(m_returnType)); return false; } @@ -368,7 +368,7 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() case JNI_EDETACHED : if (jvm->AttachCurrentThread(&m_env, NULL) < 0) { - LOGD("%s", "Failed to get the environment using AttachCurrentThread()"); + SE_LOGD("%s", "Failed to get the environment using AttachCurrentThread()"); m_error = JSJ_ERR_VM_THREAD_DETACHED; return false; } @@ -376,7 +376,7 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() case JNI_EVERSION : default : - LOGD("%s", "Failed to get the environment using GetEnv()"); + SE_LOGD("%s", "Failed to get the environment using GetEnv()"); m_error = JSJ_ERR_VM_FAILURE; return false; } @@ -386,7 +386,7 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() _jstrClassName); if (NULL == m_classID) { - LOGD("Classloader failed to find class of %s", m_className.c_str()); + SE_LOGD("Classloader failed to find class of %s", m_className.c_str()); m_env->ExceptionClear(); m_error = JSJ_ERR_CLASS_NOT_FOUND; return false; @@ -397,7 +397,7 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() if (!m_methodID) { m_env->ExceptionClear(); - LOGD("Failed to find method id of %s.%s %s", + SE_LOGD("Failed to find method id of %s.%s %s", m_className.c_str(), m_methodName.c_str(), m_methodSig.c_str()); @@ -410,9 +410,7 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() bool JavaScriptJavaBridge::convertReturnValue(ReturnValue retValue, ValueType type, se::Value* ret) { - if (ret == nullptr) - return false; - + assert(ret != nullptr); switch (type) { case JavaScriptJavaBridge::ValueType::INTEGER: @@ -431,7 +429,8 @@ bool JavaScriptJavaBridge::convertReturnValue(ReturnValue retValue, ValueType ty ret->setString(*retValue.stringValue); break; default: - return false; + ret->setUndefined(); + break; } return true; @@ -483,8 +482,8 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State& s) SE_REPORT_ERROR("call result code: %d", call.getErrorCode()); return false; } - ok = JavaScriptJavaBridge::convertReturnValue(call.getReturnValue(), call.getReturnValueType(), &s.rval()); - return ok; + JavaScriptJavaBridge::convertReturnValue(call.getReturnValue(), call.getReturnValueType(), &s.rval()); + return true; } SE_REPORT_ERROR("JavaScriptJavaBridge::CallInfo isn't valid!"); return false; @@ -556,8 +555,8 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State& s) return false; } - ok = JavaScriptJavaBridge::convertReturnValue(call.getReturnValue(), call.getReturnValueType(), &s.rval()); - return ok; + JavaScriptJavaBridge::convertReturnValue(call.getReturnValue(), call.getReturnValueType(), &s.rval()); + return true; } SE_REPORT_ERROR("call valid: %d, call.getArgumentsCount()= %d", call.isValid(), call.getArgumentsCount()); return false; diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index adb174810b..bb6702894b 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -53,7 +53,21 @@ ScriptingCore::~ScriptingCore() void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) { - se::ScriptEngine::getInstance()->_retainScriptObject(owner, target); + auto iterOwner = se::NativePtrToObjectMap::find(owner); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + return; + } + + auto iterTarget = se::NativePtrToObjectMap::find(target); + if (iterTarget == se::NativePtrToObjectMap::end()) + { + return; + } + + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + iterOwner->second->attachObject(iterTarget->second); } void ScriptingCore::rootScriptObject(Ref* target) @@ -63,8 +77,22 @@ void ScriptingCore::rootScriptObject(Ref* target) void ScriptingCore::releaseScriptObject(Ref* owner, Ref* target) { + auto iterOwner = se::NativePtrToObjectMap::find(owner); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + return; + } + + auto iterTarget = se::NativePtrToObjectMap::find(target); + if (iterTarget == se::NativePtrToObjectMap::end()) + { + return; + } + assert(!se::ScriptEngine::getInstance()->isGarbageCollecting()); - se::ScriptEngine::getInstance()->_releaseScriptObject(owner, target); + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + iterOwner->second->detachObject(iterTarget->second); } void ScriptingCore::unrootScriptObject(Ref* target) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_conversions.cpp b/native/cocos/scripting/js-bindings/manual/jsb_conversions.cpp index 8fab959dd3..92cf987d92 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_conversions.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_conversions.cpp @@ -18,6 +18,11 @@ bool seval_to_int32(const se::Value& v, int32_t* ret) *ret = v.toInt32(); //FIXME: need to check isNan? return true; } + else if (v.isBoolean()) + { + *ret = v.toBoolean() ? 1 : 0; + return true; + } *ret = 0; return false; } @@ -30,6 +35,11 @@ bool seval_to_uint32(const se::Value& v, uint32_t* ret) *ret = v.toUint32(); return true; } + else if (v.isBoolean()) + { + *ret = v.toBoolean() ? 1 : 0; + return true; + } *ret = 0; return false; } @@ -42,6 +52,11 @@ bool seval_to_int8(const se::Value& v, int8_t* ret) *ret = v.toInt8(); return true; } + else if (v.isBoolean()) + { + *ret = v.toBoolean() ? 1 : 0; + return true; + } *ret = 0; return false; } @@ -54,6 +69,11 @@ bool seval_to_uint8(const se::Value& v, uint8_t* ret) *ret = v.toUint8(); return true; } + else if (v.isBoolean()) + { + *ret = v.toBoolean() ? 1 : 0; + return true; + } *ret = 0; return false; } @@ -66,6 +86,11 @@ bool seval_to_int16(const se::Value& v, int16_t* ret) *ret = v.toInt16(); return true; } + else if (v.isBoolean()) + { + *ret = v.toBoolean() ? 1 : 0; + return true; + } *ret = 0; return false; } @@ -78,6 +103,11 @@ bool seval_to_uint16(const se::Value& v, uint16_t* ret) *ret = v.toUint16(); return true; } + else if (v.isBoolean()) + { + *ret = v.toBoolean() ? 1 : 0; + return true; + } *ret = 0; return false; } @@ -188,13 +218,8 @@ bool seval_to_ssize(const se::Value& v, ssize_t* ret) bool seval_to_std_string(const se::Value& v, std::string* ret) { assert(ret != nullptr); - if (v.isString() || v.isNumber()) - { - *ret = v.toStringForce(); - return true; - } - ret->clear(); - return false; + *ret = v.toStringForce(); + return true; } bool seval_to_Vec2(const se::Value& v, cocos2d::Vec2* pt) @@ -440,6 +465,10 @@ bool seval_to_ccvalue(const se::Value& v, cocos2d::Value* ret) { *ret = v.toBoolean(); } + else if (v.isNullOrUndefined()) + { + *ret = cocos2d::Value::Null; + } else { CCASSERT(false, "not supported type"); @@ -1363,6 +1392,12 @@ bool ccvalue_to_seval(const cocos2d::Value& v, se::Value* ret) bool ok = true; switch (v.getType()) { + case cocos2d::Value::Type::NONE: + ret->setNull(); + break; + case cocos2d::Value::Type::UNSIGNED: + ret->setUint32(v.asUnsignedInt()); + break; case cocos2d::Value::Type::BOOLEAN: ret->setBoolean(v.asBool()); break; @@ -1386,6 +1421,7 @@ bool ccvalue_to_seval(const cocos2d::Value& v, se::Value* ret) ok = ccvaluemapintkey_to_seval(v.asIntKeyMap(), ret); break; default: + SE_LOGE("Could not the way to convert cocos2d::Value::Type (%d) type!", (int)v.getType()); ok = false; break; } diff --git a/native/cocos/scripting/js-bindings/manual/jsb_conversions.hpp b/native/cocos/scripting/js-bindings/manual/jsb_conversions.hpp index fa5a99c984..a46e85e970 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_conversions.hpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_conversions.hpp @@ -98,21 +98,32 @@ template bool seval_to_native_ptr(const se::Value& v, T* ret) { assert(ret != nullptr); - if (!v.isObject()) + + if (v.isObject()) { + T ptr = (T)v.toObject()->getPrivateData(); + if (ptr == nullptr) + { + // This should never happen, return 'false' to mark the conversion fails. + *ret = nullptr; + return false; + } + + *ret = ptr; + return true; + } + else if (v.isNullOrUndefined()) + { + // If js value is null or undefined, the convertion should be successful. + // So we should return 'true' to indicate the convertion succeeds and mark + // the out value to 'nullptr'. *ret = nullptr; - return false; + return true; } - T ptr = (T)v.toObject()->getPrivateData(); - if (ptr == nullptr) - { - *ret = nullptr; - return false; - } - - *ret = ptr; - return true; + // If js value isn't null, undefined and Object, mark the convertion fails. + *ret = nullptr; + return false; } template diff --git a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp index 37c003f984..6d4358eb62 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp @@ -11,6 +11,7 @@ using namespace cocos2d; se::Object* __jscObj = nullptr; se::Object* __ccObj = nullptr; se::Object* __jsbObj = nullptr; +se::Object* __glObj = nullptr; static std::string xxteaKey = ""; void jsb_set_xxtea_key(const std::string& key) @@ -18,7 +19,6 @@ void jsb_set_xxtea_key(const std::string& key) xxteaKey = key; } -#if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_SM static const char* BYTE_CODE_FILE_EXT = ".jsc"; static std::string removeFileExt(const std::string& filePath) @@ -30,7 +30,6 @@ static std::string removeFileExt(const std::string& filePath) } return filePath; } -#endif void jsb_init_file_operation_delegate() { @@ -42,7 +41,6 @@ void jsb_init_file_operation_delegate() Data fileData; -#if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_SM std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; if (FileUtils::getInstance()->isFileExist(byteCodePath)) { fileData = FileUtils::getInstance()->getDataFromFile(byteCodePath); @@ -52,15 +50,32 @@ void jsb_init_file_operation_delegate() if (data == nullptr) { SE_REPORT_ERROR("Can't decrypt code for %s", byteCodePath.c_str()); + return; + } + + ZipFile* zip = ZipFile::createWithBuffer(data, dataLen); + if (zip) { + ssize_t unpackedLen = 0; + uint8_t* unpackedData = zip->getFileData("encrypt.js", &unpackedLen); + + if (unpackedData == nullptr) { + SE_REPORT_ERROR("Can't decrypt code for %s", byteCodePath.c_str()); + return; + } + + readCallback(unpackedData, unpackedLen); + free(data); + free(unpackedData); + delete zip; + } + else { + readCallback(data, dataLen); + free(data); } - - readCallback(data, dataLen); - free(data); return; } -#endif fileData = FileUtils::getInstance()->getDataFromFile(path); readCallback(fileData.getBytes(), fileData.getSize()); }; @@ -68,31 +83,51 @@ void jsb_init_file_operation_delegate() delegate.onGetStringFromFile = [](const std::string& path) -> std::string{ assert(!path.empty()); -#if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_SM std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; if (FileUtils::getInstance()->isFileExist(byteCodePath)) { Data fileData = FileUtils::getInstance()->getDataFromFile(byteCodePath); - uint32_t retLength; - uint8_t* data = xxtea_decrypt((uint8_t*)fileData.getBytes(), (uint32_t)fileData.getSize(), (uint8_t*)xxteaKey.c_str(), (uint32_t)xxteaKey.size(), &retLength); - + uint32_t dataLen; + uint8_t* data = xxtea_decrypt((uint8_t*)fileData.getBytes(), (uint32_t)fileData.getSize(), (uint8_t*)xxteaKey.c_str(), (uint32_t)xxteaKey.size(), &dataLen); + if (data == nullptr) { SE_REPORT_ERROR("Can't decrypt code for %s", byteCodePath.c_str()); return ""; } - - std::string ret(reinterpret_cast(data), retLength); - free(data); - - return ret; + + ZipFile* zip = ZipFile::createWithBuffer(data, dataLen); + if (zip) { + ssize_t unpackedLen = 0; + uint8_t* unpackedData = zip->getFileData("encrypt.js", &unpackedLen); + + if (unpackedData == nullptr) { + SE_REPORT_ERROR("Can't decrypt code for %s", byteCodePath.c_str()); + return ""; + } + + std::string ret(reinterpret_cast(unpackedData), unpackedLen); + free(unpackedData); + free(data); + delete zip; + + return ret; + } + else { + std::string ret(reinterpret_cast(data), dataLen); + free(data); + return ret; + } } -#endif return FileUtils::getInstance()->getStringFromFile(path); }; delegate.onGetFullPath = [](const std::string& path) -> std::string{ assert(!path.empty()); + std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT; + if (FileUtils::getInstance()->isFileExist(byteCodePath)) { + return FileUtils::getInstance()->fullPathForFilename(byteCodePath); + } return FileUtils::getInstance()->fullPathForFilename(path); }; @@ -793,6 +828,7 @@ bool jsb_register_global_variables(se::Object* global) getOrCreatePlainObject_r("jsb", global, &__jsbObj); getOrCreatePlainObject_r("__jsc__", global, &__jscObj); + getOrCreatePlainObject_r("gl", global, &__glObj); __jscObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect)); __jscObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap)); @@ -815,6 +851,7 @@ bool jsb_register_global_variables(se::Object* global) __ccObj->decRef(); __jsbObj->decRef(); __jscObj->decRef(); + __glObj->decRef(); }); return true; diff --git a/native/cocos/scripting/js-bindings/manual/jsb_global.h b/native/cocos/scripting/js-bindings/manual/jsb_global.h index 0352e84e63..78b7ba0d0b 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_global.h +++ b/native/cocos/scripting/js-bindings/manual/jsb_global.h @@ -9,6 +9,7 @@ namespace se { extern se::Object* __ccObj; extern se::Object* __jsbObj; +extern se::Object* __glObj; bool jsb_register_global_variables(se::Object* global); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_module_register.cpp b/native/cocos/scripting/js-bindings/manual/jsb_module_register.cpp index c6426aa3c5..16d2380b8f 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_module_register.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_module_register.cpp @@ -26,6 +26,7 @@ #include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_network_auto.hpp" #include "cocos/scripting/js-bindings/auto/jsb_creator_auto.hpp" +#include "cocos/scripting/js-bindings/manual/jsb_opengl_registration.hpp" #include "cocos/scripting/js-bindings/manual/jsb_creator_manual.hpp" #include "cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.hpp" #include "cocos/scripting/js-bindings/manual/jsb_global.h" @@ -124,6 +125,7 @@ bool jsb_register_all_modules() se->addRegisterCallback(register_all_cocos2dx); se->addRegisterCallback(jsb_register_Node_manual); se->addRegisterCallback(register_all_cocos2dx_manual); + se->addRegisterCallback(JSB_register_opengl); #if USE_AUDIO se->addRegisterCallback(register_all_cocos2dx_audioengine); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp index a5940f37d0..0b3514bdaf 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp @@ -30,7 +30,7 @@ static bool Node_finalized(se::State& s) if (s.nativeThisObject()) { Node* thiz = (Node*) s.nativeThisObject(); - LOGD("Node_finalized %p ...\n", thiz->getUserData()); + SE_LOGD("Node_finalized %p ...\n", thiz->getUserData()); CC_SAFE_RELEASE(thiz); } return true; @@ -39,7 +39,7 @@ SE_BIND_FINALIZE_FUNC(Node_finalized) static bool Node_constructor(se::State& s) { - LOGD("Node_constructor ...\n"); + SE_LOGD("Node_constructor ...\n"); Node* obj = new Node(); s.thisObject()->setPrivateData(obj); return true; @@ -48,7 +48,7 @@ SE_BIND_CTOR(Node_constructor, __jsb_Node_class, Node_finalized) static bool Node_ctor(se::State& s) { - LOGD("Node_ctor ...\n"); + SE_LOGD("Node_ctor ...\n"); Node* obj = new Node(); s.thisObject()->setPrivateData(obj); return true; @@ -427,7 +427,7 @@ public: } ~UnscheduleNotifier() { -// LOGD("~UnscheduleNotifier, targetId: %u, funcId: %u\n", _targetId, _funcId); +// SE_LOGD("~UnscheduleNotifier, targetId: %u, funcId: %u\n", _targetId, _funcId); se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; @@ -559,14 +559,14 @@ static bool Node_schedule(se::State& s) int argc = (int)args.size(); #if 0//COCOS2D_DEBUG > 0 - LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); + SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); int totalCount = 0; for (const auto& e1 : __js_target_schedulekey_map) { - LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); + SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); totalCount += (int)e1.second.size(); } - LOGD("total: %d-------------------------- \n", totalCount); + SE_LOGD("total: %d-------------------------- \n", totalCount); #endif if (argc >= 1) @@ -626,12 +626,12 @@ static bool Node_scheduleOnce(se::State& s) const auto& args = s.args(); size_t argc = args.size(); #if 0//COCOS2D_DEBUG > 0 - LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); + SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); for (const auto& e1 : __js_target_schedulekey_map) { - LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); + SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); } - LOGD("-------------------------- \n"); + SE_LOGD("-------------------------- \n"); #endif Node* thiz = (Node*)s.nativeThisObject(); @@ -676,7 +676,7 @@ public: ~UnscheduleUpdateNotifier() { -// LOGD("~UnscheduleUpdateNotifier: %p\n", _target); +// SE_LOGD("~UnscheduleUpdateNotifier: %p\n", _target); removeScheduleUpdate(_targetId); } @@ -754,13 +754,13 @@ static bool Scheduler_scheduleUpdateCommon(Scheduler* scheduler, const se::Value static bool Node_scheduleUpdate(se::State& s) { -#if COCOS2D_DEBUG > 0 - LOGD("--------------------------\nscheduleUpdate target count: %d\n", (int)__js_target_schedule_update_map.size()); +#if COCOS2D_DEBUG > 1 + SE_LOGD("--------------------------\nscheduleUpdate target count: %d\n", (int)__js_target_schedule_update_map.size()); for (const auto& e1 : __js_target_schedule_update_map) { - LOGD("target: %u, updated: priority: %d\n", e1.first, e1.second.first); + SE_LOGD("target: %u, updated: priority: %d\n", e1.first, e1.second.first); } - LOGD("-------------------------- \n"); + SE_LOGD("-------------------------- \n"); #endif Node* thiz = (Node*)s.nativeThisObject(); @@ -774,13 +774,13 @@ static bool Node_scheduleUpdateWithPriority(se::State& s) { const auto& args = s.args(); int argc = (int)args.size(); -#if COCOS2D_DEBUG > 0 - LOGD("--------------------------\nscheduleUpdate target count: %d\n", (int)__js_target_schedule_update_map.size()); +#if COCOS2D_DEBUG > 1 + SE_LOGD("--------------------------\nscheduleUpdate target count: %d\n", (int)__js_target_schedule_update_map.size()); for (const auto& e1 : __js_target_schedule_update_map) { - LOGD("target: %u, updated: priority: %d\n", e1.first, e1.second.first); + SE_LOGD("target: %u, updated: priority: %d\n", e1.first, e1.second.first); } - LOGD("-------------------------- \n"); + SE_LOGD("-------------------------- \n"); #endif Node* thiz = (Node*)s.nativeThisObject(); @@ -867,7 +867,7 @@ static bool Scheduler_unscheduleCommon(Scheduler* scheduler, const se::Value& js } else { - LOGD("WARNING: %s not found\n", __FUNCTION__); + SE_LOGD("WARNING: %s not found\n", __FUNCTION__); } return true; } @@ -1002,7 +1002,7 @@ static bool Node_set_x(se::State& s) const auto& args = s.args(); Node* thiz = (Node*)s.nativeThisObject(); float x = args[0].toNumber(); - LOGD("cc.Node set_x (%f) native obj: %p\n", x, thiz); + SE_LOGD("cc.Node set_x (%f) native obj: %p\n", x, thiz); thiz->setPositionX(x); return true; } @@ -1021,7 +1021,7 @@ static bool Node_set_y(se::State& s) const auto& args = s.args(); Node* thiz = (Node*)s.nativeThisObject(); float y = args[0].toNumber(); - LOGD("cc.Node set_y (%f) native obj: %p\n", y, thiz); + SE_LOGD("cc.Node set_y (%f) native obj: %p\n", y, thiz); thiz->setPositionY(y); return true; } @@ -1180,12 +1180,12 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) const auto& args = s.args(); int argc = (int)args.size(); #if 0//COCOS2D_DEBUG > 0 - LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); + SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); for (const auto& e1 : __js_target_schedulekey_map) { - LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); + SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); } - LOGD("-------------------------- \n"); + SE_LOGD("-------------------------- \n"); #endif if (argc >= 2) @@ -1208,7 +1208,7 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) bool isBindedObject = jsThis.toObject()->getPrivateData() != nullptr; -// LOGD("%s, is binded object: %s\n", __FUNCTION__, isBindedObject ? "true" : "false"); +// SE_LOGD("%s, is binded object: %s\n", __FUNCTION__, isBindedObject ? "true" : "false"); assert(jsThis.isObject()); assert(!jsThis.toObject()->isFunction()); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_functions.cpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_functions.cpp new file mode 100644 index 0000000000..d943bcace9 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_functions.cpp @@ -0,0 +1,2231 @@ +#include "jsb_opengl_functions.hpp" +#include "cocos/scripting/js-bindings/jswrapper/SeApi.h" +#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp" +#include "cocos/scripting/js-bindings/manual/jsb_global.h" + +namespace { + +template +class GLData +{ +public: + GLData() + : _data(nullptr) + , _count(0) + , _isOwnData(false) + { + } + + ~GLData() + { + if (_isOwnData) + { + free(_data); + } + } + + void setData(T* data, size_t count, bool isOwnData) + { + _data = data; + _count = count; + _isOwnData = isOwnData; + } + + T* data() const { return _data; } + size_t count() const { return _count; } + +private: + + // Disable copy/move constructor, copy/move assigment + GLData(const GLData&); + GLData(GLData&&); + GLData& operator=(const GLData&); + GLData& operator=(GLData&&); + + T* _data; + size_t _count; + bool _isOwnData; +}; + +} + +template +static bool JSB_jsval_typedarray_to_data(const se::Value& v, GLData& data) +{ + if (v.isObject()) + { + se::Object* obj = v.toObject(); + if (obj->isArray()) + { + uint32_t length = 0; + if (obj->getArrayLength(&length) && length > 0) + { + T* d = (T*)malloc(length * sizeof(T)); + se::Value tmp; + for (uint32_t i = 0; i < length; ++i) + { + if (obj->getArrayElement(i, &tmp)) + { + if (std::is_same::value) + { + d[i] = tmp.toInt32(); + } + else if (std::is_same::value) + { + d[i] = tmp.toFloat(); + } + } + } + data.setData(d, length, true); + return true; + } + SE_LOGE("Failed to get array data"); + } + else if (obj->isTypedArray()) + { + size_t bytes = 0; + uint8_t* ptr = nullptr; + + if (obj->getTypedArrayData(&ptr, &bytes) && bytes > 0) + { + data.setData((T*)ptr, bytes / sizeof(T), false); + return true; + } + + SE_LOGE("Failed to get typed array data"); + } + } + + return false; +} + +bool JSB_get_arraybufferview_dataptr(const se::Value& v, GLsizei *count, GLvoid **data) +{ + assert(count != nullptr && data != nullptr); + + if (v.isObject()) + { + se::Object* obj = v.toObject(); + if (obj->isTypedArray()) + { + uint8_t* ptr = nullptr; + size_t length = 0; + if (obj->getTypedArrayData(&ptr, &length) && ptr != nullptr && length > 0) + { + *data = ptr; + *count = (GLsizei)length; + return true; + } + } + } + return false; +} + +// Arguments: GLenum +// Ret value: void +bool JSB_glActiveTexture(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glActiveTexture((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glActiveTexture) + +// Arguments: GLuint, GLuint +// Ret value: void +bool JSB_glAttachShader(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glAttachShader((GLuint)arg0 , (GLuint)arg1 ); + + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glAttachShader) + +// Arguments: GLuint, GLuint, char* +// Ret value: void +bool JSB_glBindAttribLocation(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; std::string arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_std_string(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBindAttribLocation((GLuint)arg0 , (GLuint)arg1 , arg2.c_str() ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBindAttribLocation) + +// Arguments: GLenum, GLuint +// Ret value: void +bool JSB_glBindBuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBindBuffer((GLenum)arg0 , (GLuint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBindBuffer) + +// Arguments: GLenum, GLuint +// Ret value: void +bool JSB_glBindFramebuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBindFramebuffer((GLenum)arg0 , (GLuint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBindFramebuffer) + +// Arguments: GLenum, GLuint +// Ret value: void +bool JSB_glBindRenderbuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBindRenderbuffer((GLenum)arg0 , (GLuint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBindRenderbuffer) + +// Arguments: GLenum, GLuint +// Ret value: void +bool JSB_glBindTexture(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBindTexture((GLenum)arg0 , (GLuint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBindTexture) + +// Arguments: GLclampf, GLclampf, GLclampf, GLclampf +// Ret value: void +bool JSB_glBlendColor(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBlendColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBlendColor) + +// Arguments: GLenum +// Ret value: void +bool JSB_glBlendEquation(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBlendEquation((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBlendEquation) + +// Arguments: GLenum, GLenum +// Ret value: void +bool JSB_glBlendEquationSeparate(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBlendEquationSeparate((GLenum)arg0 , (GLenum)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBlendEquationSeparate) + +// Arguments: GLenum, GLenum +// Ret value: void +bool JSB_glBlendFunc(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBlendFunc((GLenum)arg0 , (GLenum)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBlendFunc) + +// Arguments: GLenum, GLenum, GLenum, GLenum +// Ret value: void +bool JSB_glBlendFuncSeparate(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_uint32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBlendFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBlendFuncSeparate) + +// Arguments: GLenum, ArrayBufferView, GLenum +// Ret value: void +bool JSB_glBufferData(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; void* arg1; uint32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[1], &count, &arg1); + ok &= seval_to_uint32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBufferData((GLenum)arg0 , count, (GLvoid*)arg1 , (GLenum)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBufferData) + +// Arguments: GLenum, GLintptr, ArrayBufferView +// Ret value: void +bool JSB_glBufferSubData(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; void* arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[2], &count, &arg2); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glBufferSubData((GLenum)arg0 , (GLintptr)arg1 , count, (GLvoid*)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glBufferSubData) + +// Arguments: GLenum +// Ret value: GLenum +bool JSB_glCheckFramebufferStatus(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLenum ret_val; + + ret_val = glCheckFramebufferStatus((GLenum)arg0 ); + s.rval().setUint32((uint32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glCheckFramebufferStatus) + +// Arguments: GLbitfield +// Ret value: void +bool JSB_glClear(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glClear((GLbitfield)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glClear) + +// Arguments: GLclampf, GLclampf, GLclampf, GLclampf +// Ret value: void +bool JSB_glClearColor(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glClearColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glClearColor) + +// Arguments: GLclampf +// Ret value: void +bool JSB_glClearDepthf(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glClearDepthf((GLclampf)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glClearDepthf) + +// Arguments: GLint +// Ret value: void +bool JSB_glClearStencil(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glClearStencil((GLint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glClearStencil) + +// Arguments: GLboolean, GLboolean, GLboolean, GLboolean +// Ret value: void +bool JSB_glColorMask(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint16_t arg0; uint16_t arg1; uint16_t arg2; uint16_t arg3; + + ok &= seval_to_uint16(args[0], &arg0 ); + ok &= seval_to_uint16(args[1], &arg1 ); + ok &= seval_to_uint16(args[2], &arg2 ); + ok &= seval_to_uint16(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glColorMask((GLboolean)arg0 , (GLboolean)arg1 , (GLboolean)arg2 , (GLboolean)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glColorMask) + +// Arguments: GLuint +// Ret value: void +bool JSB_glCompileShader(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glCompileShader((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glCompileShader) + +// Arguments: GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, ArrayBufferView +// Ret value: void +bool JSB_glCompressedTexImage2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 8, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; void* arg7; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + ok &= seval_to_int32(args[6], &arg6 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[7], &count, &arg7); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glCompressedTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLsizei)arg3 , (GLsizei)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLvoid*)arg7 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glCompressedTexImage2D) + +// Arguments: GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, ArrayBufferView +// Ret value: void +bool JSB_glCompressedTexSubImage2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 9, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; int32_t arg7; void* arg8; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + ok &= seval_to_uint32(args[6], &arg6 ); + ok &= seval_to_int32(args[7], &arg7 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[8], &count, &arg8); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glCompressedTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLsizei)arg4 , (GLsizei)arg5 , (GLenum)arg6 , (GLsizei)arg7 , (GLvoid*)arg8 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glCompressedTexSubImage2D) + +// Arguments: GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint +// Ret value: void +bool JSB_glCopyTexImage2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 8, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + ok &= seval_to_int32(args[6], &arg6 ); + ok &= seval_to_int32(args[7], &arg7 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glCopyTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLint)arg3 , (GLint)arg4 , (GLsizei)arg5 , (GLsizei)arg6 , (GLint)arg7 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glCopyTexImage2D) + +// Arguments: GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei +// Ret value: void +bool JSB_glCopyTexSubImage2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 8, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + ok &= seval_to_int32(args[6], &arg6 ); + ok &= seval_to_int32(args[7], &arg7 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glCopyTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLsizei)arg7 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glCopyTexSubImage2D) + +// Arguments: +// Ret value: GLuint +bool JSB_glCreateProgram(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 0, false, "Invalid number of arguments" ); + GLuint ret_val; + + ret_val = glCreateProgram( ); + s.rval().setUint32((uint32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glCreateProgram) + +// Arguments: GLenum +// Ret value: GLuint +bool JSB_glCreateShader(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLuint ret_val; + + ret_val = glCreateShader((GLenum)arg0 ); + s.rval().setUint32((uint32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glCreateShader) + +// Arguments: GLenum +// Ret value: void +bool JSB_glCullFace(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glCullFace((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glCullFace) + +// Arguments: GLuint +// Ret value: void +bool JSB_glDeleteProgram(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDeleteProgram((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDeleteProgram) + +// Arguments: GLuint +// Ret value: void +bool JSB_glDeleteShader(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDeleteShader((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDeleteShader) + +// Arguments: GLenum +// Ret value: void +bool JSB_glDepthFunc(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDepthFunc((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDepthFunc) + +// Arguments: GLboolean +// Ret value: void +bool JSB_glDepthMask(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint16_t arg0; + + ok &= seval_to_uint16(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDepthMask((GLboolean)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDepthMask) + +// Arguments: GLclampf, GLclampf +// Ret value: void +bool JSB_glDepthRangef(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDepthRangef((GLclampf)arg0 , (GLclampf)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDepthRangef) + +// Arguments: GLuint, GLuint +// Ret value: void +bool JSB_glDetachShader(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDetachShader((GLuint)arg0 , (GLuint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDetachShader) + +// Arguments: GLenum +// Ret value: void +bool JSB_glDisable(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDisable((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDisable) + +// Arguments: GLuint +// Ret value: void +bool JSB_glDisableVertexAttribArray(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDisableVertexAttribArray((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDisableVertexAttribArray) + +// Arguments: GLenum, GLint, GLsizei +// Ret value: void +bool JSB_glDrawArrays(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDrawArrays((GLenum)arg0 , (GLint)arg1 , (GLsizei)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDrawArrays) + +// Arguments: GLenum, GLsizei, GLenum, ArrayBufferView +// Ret value: void +bool JSB_glDrawElements(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; uint32_t arg2; void* arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[3], &count, &arg3); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDrawElements((GLenum)arg0 , (GLsizei)arg1 , (GLenum)arg2 , (GLvoid*)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glDrawElements) + +// Arguments: GLenum +// Ret value: void +bool JSB_glEnable(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glEnable((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glEnable) + +// Arguments: GLuint +// Ret value: void +bool JSB_glEnableVertexAttribArray(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glEnableVertexAttribArray((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glEnableVertexAttribArray) + +// Arguments: +// Ret value: void +bool JSB_glFinish(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 0, false, "Invalid number of arguments" ); + glFinish( ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glFinish) + +// Arguments: +// Ret value: void +bool JSB_glFlush(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 0, false, "Invalid number of arguments" ); + glFlush( ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glFlush) + +// Arguments: GLenum, GLenum, GLenum, GLuint +// Ret value: void +bool JSB_glFramebufferRenderbuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_uint32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glFramebufferRenderbuffer((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glFramebufferRenderbuffer) + +// Arguments: GLenum, GLenum, GLenum, GLuint, GLint +// Ret value: void +bool JSB_glFramebufferTexture2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 5, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; int32_t arg4; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_uint32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glFramebufferTexture2D((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 , (GLint)arg4 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glFramebufferTexture2D) + +// Arguments: GLenum +// Ret value: void +bool JSB_glFrontFace(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glFrontFace((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glFrontFace) + +// Arguments: GLenum +// Ret value: void +bool JSB_glGenerateMipmap(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glGenerateMipmap((GLenum)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glGenerateMipmap) + +// Arguments: GLuint, char* +// Ret value: int +bool JSB_glGetAttribLocation(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; std::string arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_std_string(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + int ret_val; + + ret_val = glGetAttribLocation((GLuint)arg0 , arg1.c_str() ); + s.rval().setInt32(ret_val); + return true; +} +SE_BIND_FUNC(JSB_glGetAttribLocation) + +// Arguments: +// Ret value: GLenum +bool JSB_glGetError(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 0, false, "Invalid number of arguments" ); + GLenum ret_val; + + ret_val = glGetError( ); + s.rval().setUint32((uint32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glGetError) + +// Arguments: GLuint, char* +// Ret value: int +bool JSB_glGetUniformLocation(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; std::string arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_std_string(args[1], &arg1 ); + + SE_PRECONDITION2(ok, false, "Error processing arguments"); + int ret_val; + + ret_val = glGetUniformLocation((GLuint)arg0 , arg1.c_str() ); + s.rval().setInt32(ret_val); + return true; +} +SE_BIND_FUNC(JSB_glGetUniformLocation) + +// Arguments: GLenum, GLenum +// Ret value: void +bool JSB_glHint(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glHint((GLenum)arg0 , (GLenum)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glHint) + +// Arguments: GLuint +// Ret value: GLboolean +bool JSB_glIsBuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsBuffer((GLuint)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsBuffer) + +// Arguments: GLenum +// Ret value: GLboolean +bool JSB_glIsEnabled(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsEnabled((GLenum)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsEnabled) + +// Arguments: GLuint +// Ret value: GLboolean +bool JSB_glIsFramebuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsFramebuffer((GLuint)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsFramebuffer) + +// Arguments: GLuint +// Ret value: GLboolean +bool JSB_glIsProgram(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsProgram((GLuint)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsProgram) + +// Arguments: GLuint +// Ret value: GLboolean +bool JSB_glIsRenderbuffer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsRenderbuffer((GLuint)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsRenderbuffer) + +// Arguments: GLuint +// Ret value: GLboolean +bool JSB_glIsShader(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsShader((GLuint)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsShader) + +// Arguments: GLuint +// Ret value: GLboolean +bool JSB_glIsTexture(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + GLboolean ret_val; + + ret_val = glIsTexture((GLuint)arg0 ); + s.rval().setInt32((int32_t)ret_val); + return true; +} +SE_BIND_FUNC(JSB_glIsTexture) + +// Arguments: GLfloat +// Ret value: void +bool JSB_glLineWidth(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glLineWidth((GLfloat)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glLineWidth) + +// Arguments: GLuint +// Ret value: void +bool JSB_glLinkProgram(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glLinkProgram((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glLinkProgram) + +// Arguments: GLenum, GLint +// Ret value: void +bool JSB_glPixelStorei(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glPixelStorei((GLenum)arg0 , (GLint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glPixelStorei) + +// Arguments: GLfloat, GLfloat +// Ret value: void +bool JSB_glPolygonOffset(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glPolygonOffset((GLfloat)arg0 , (GLfloat)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glPolygonOffset) + +// Arguments: GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, ArrayBufferView +// Ret value: void +bool JSB_glReadPixels(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 7, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; uint32_t arg4; uint32_t arg5; void* arg6; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_uint32(args[4], &arg4 ); + ok &= seval_to_uint32(args[5], &arg5 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[6], &count, &arg6); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glReadPixels((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 , (GLenum)arg4 , (GLenum)arg5 , (GLvoid*)arg6 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glReadPixels) + +// Arguments: +// Ret value: void +bool JSB_glReleaseShaderCompiler(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 0, false, "Invalid number of arguments" ); + glReleaseShaderCompiler( ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glReleaseShaderCompiler) + +// Arguments: GLenum, GLenum, GLsizei, GLsizei +// Ret value: void +bool JSB_glRenderbufferStorage(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glRenderbufferStorage((GLenum)arg0 , (GLenum)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glRenderbufferStorage) + +// Arguments: GLclampf, GLboolean +// Ret value: void +bool JSB_glSampleCoverage(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; uint16_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_uint16(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glSampleCoverage((GLclampf)arg0 , (GLboolean)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glSampleCoverage) + +// Arguments: GLint, GLint, GLsizei, GLsizei +// Ret value: void +bool JSB_glScissor(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glScissor((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glScissor) + +// Arguments: GLenum, GLint, GLuint +// Ret value: void +bool JSB_glStencilFunc(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; uint32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glStencilFunc((GLenum)arg0 , (GLint)arg1 , (GLuint)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glStencilFunc) + +// Arguments: GLenum, GLenum, GLint, GLuint +// Ret value: void +bool JSB_glStencilFuncSeparate(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; int32_t arg2; uint32_t arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_uint32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glStencilFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 , (GLuint)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glStencilFuncSeparate) + +// Arguments: GLuint +// Ret value: void +bool JSB_glStencilMask(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glStencilMask((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glStencilMask) + +// Arguments: GLenum, GLuint +// Ret value: void +bool JSB_glStencilMaskSeparate(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glStencilMaskSeparate((GLenum)arg0 , (GLuint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glStencilMaskSeparate) + +// Arguments: GLenum, GLenum, GLenum +// Ret value: void +bool JSB_glStencilOp(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; uint32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glStencilOp((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glStencilOp) + +// Arguments: GLenum, GLenum, GLenum, GLenum +// Ret value: void +bool JSB_glStencilOpSeparate(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_uint32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glStencilOpSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glStencilOpSeparate) + +// Arguments: GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, ArrayBufferView +// Ret value: void +bool JSB_glTexImage2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 9, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + ok &= seval_to_uint32(args[6], &arg6 ); + ok &= seval_to_uint32(args[7], &arg7 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[8], &count, &arg8); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLsizei)arg3 , (GLsizei)arg4 , (GLint)arg5 , (GLenum)arg6 , (GLenum)arg7 , (GLvoid*)arg8 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glTexImage2D) + +// Arguments: GLenum, GLenum, GLfloat +// Ret value: void +bool JSB_glTexParameterf(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; int32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glTexParameterf((GLenum)arg0 , (GLenum)arg1 , (GLfloat)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glTexParameterf) + +// Arguments: GLenum, GLenum, GLint +// Ret value: void +bool JSB_glTexParameteri(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; uint32_t arg1; int32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glTexParameteri((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glTexParameteri) + +// Arguments: GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, ArrayBufferView +// Ret value: void +bool JSB_glTexSubImage2D(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 9, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + ok &= seval_to_uint32(args[6], &arg6 ); + ok &= seval_to_uint32(args[7], &arg7 ); + GLsizei count; + ok &= JSB_get_arraybufferview_dataptr(args[8], &count, &arg8); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLsizei)arg4 , (GLsizei)arg5 , (GLenum)arg6 , (GLenum)arg7 , (GLvoid*)arg8 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glTexSubImage2D) + +// Arguments: GLint, GLfloat +// Ret value: void +bool JSB_glUniform1f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform1f((GLint)arg0 , (GLfloat)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform1f) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform1fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0;; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform1fv((GLint)arg0 , (GLsizei)data.count() , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform1fv) + +// Arguments: GLint, GLint +// Ret value: void +bool JSB_glUniform1i(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform1i((GLint)arg0 , (GLint)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform1i) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform1iv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform1iv((GLint)arg0 , (GLsizei)data.count() , (GLint*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform1iv) + +// Arguments: GLint, GLfloat, GLfloat +// Ret value: void +bool JSB_glUniform2f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform2f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform2f) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform2fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform2fv((GLint)arg0 , (GLsizei)(data.count()/2) , (GLfloat*)data.data() ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform2fv) + +// Arguments: GLint, GLint, GLint +// Ret value: void +bool JSB_glUniform2i(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform2i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform2i) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform2iv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform2iv((GLint)arg0 , (GLsizei)(data.count()/2) , (GLint*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform2iv) + +// Arguments: GLint, GLfloat, GLfloat, GLfloat +// Ret value: void +bool JSB_glUniform3f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform3f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform3f) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform3fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform3fv((GLint)arg0 , (GLsizei)(data.count()/3) , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform3fv) + +// Arguments: GLint, GLint, GLint, GLint +// Ret value: void +bool JSB_glUniform3i(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform3i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform3i) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform3iv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform3iv((GLint)arg0 , (GLsizei)(data.count()/3) , (GLint*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform3iv) + +// Arguments: GLint, GLfloat, GLfloat, GLfloat, GLfloat +// Ret value: void +bool JSB_glUniform4f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 5, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform4f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform4f) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform4fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0;; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform4fv((GLint)arg0 , (GLsizei)(data.count()/4) , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform4fv) + +// Arguments: GLint, GLint, GLint, GLint, GLint +// Ret value: void +bool JSB_glUniform4i(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 5, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform4i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform4i) + +// Arguments: GLint, GLsizei, TypedArray/Sequence +// Ret value: void +bool JSB_glUniform4iv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; + + ok &= seval_to_int32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniform4iv((GLint)arg0 , (GLsizei)(data.count()/4) , (GLint*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniform4iv) + +// Arguments: GLint, GLboolean, TypedArray/Sequence +// Ret value: void +bool JSB_glUniformMatrix2fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; uint16_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_uint16(args[1], &arg1 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[2], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniformMatrix2fv(arg0, (GLsizei)(data.count()/4), (GLboolean)arg1 , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniformMatrix2fv) + +// Arguments: GLint, GLboolean, TypedArray/Sequence +// Ret value: void +bool JSB_glUniformMatrix3fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; uint16_t arg1; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_uint16(args[1], &arg1 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[2], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniformMatrix3fv(arg0, (GLsizei)(data.count()/9), (GLboolean)arg1 , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniformMatrix3fv) + +// Arguments: GLint, GLboolean, TypedArray/Sequence +// Ret value: void +bool JSB_glUniformMatrix4fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; uint16_t arg1;; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_uint16(args[1], &arg1 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[2], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUniformMatrix4fv(arg0, (GLsizei)(data.count()/16), (GLboolean)arg1 , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUniformMatrix4fv) + +// Arguments: GLuint +// Ret value: void +bool JSB_glUseProgram(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glUseProgram((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glUseProgram) + +// Arguments: GLuint +// Ret value: void +bool JSB_glValidateProgram(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 1, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glValidateProgram((GLuint)arg0 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glValidateProgram) + +// Arguments: GLuint, GLfloat +// Ret value: void +bool JSB_glVertexAttrib1f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib1f((GLuint)arg0 , (GLfloat)arg1 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib1f) + +// Arguments: GLuint, TypedArray/Sequence +// Ret value: void +bool JSB_glVertexAttrib1fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib1fv((GLuint)arg0 , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib1fv) + +// Arguments: GLuint, GLfloat, GLfloat +// Ret value: void +bool JSB_glVertexAttrib2f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 3, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib2f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib2f) + +// Arguments: GLuint, TypedArray/Sequence +// Ret value: void +bool JSB_glVertexAttrib2fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib2fv((GLuint)arg0 , (GLfloat*)data.data() ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib2fv) + +// Arguments: GLuint, GLfloat, GLfloat, GLfloat +// Ret value: void +bool JSB_glVertexAttrib3f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib3f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib3f) + +// Arguments: GLuint, TypedArray/Sequence +// Ret value: void +bool JSB_glVertexAttrib3fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib3fv((GLuint)arg0 , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib3fv) + +// Arguments: GLuint, GLfloat, GLfloat, GLfloat, GLfloat +// Ret value: void +bool JSB_glVertexAttrib4f(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 5, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib4f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib4f) + +// Arguments: GLuint, TypedArray/Sequence +// Ret value: void +bool JSB_glVertexAttrib4fv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 2, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + GLData data; + ok &= JSB_jsval_typedarray_to_data(args[1], data); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttrib4fv((GLuint)arg0 , (GLfloat*)data.data()); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttrib4fv) + +// Arguments: GLuint, GLint, GLenum, GLboolean, GLsizei, GLvoid* +// Ret value: void +bool JSB_glVertexAttribPointer(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 6, false, "Invalid number of arguments" ); + bool ok = true; + uint32_t arg0; int32_t arg1; uint32_t arg2; uint16_t arg3; int32_t arg4; int32_t arg5; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_uint32(args[2], &arg2 ); + ok &= seval_to_uint16(args[3], &arg3 ); + ok &= seval_to_int32(args[4], &arg4 ); + ok &= seval_to_int32(args[5], &arg5 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glVertexAttribPointer((GLuint)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLboolean)arg3 , (GLsizei)arg4 , (GLvoid*)arg5 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glVertexAttribPointer) + +// Arguments: GLint, GLint, GLsizei, GLsizei +// Ret value: void +bool JSB_glViewport(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2( argc == 4, false, "Invalid number of arguments" ); + bool ok = true; + int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; + + ok &= seval_to_int32(args[0], &arg0 ); + ok &= seval_to_int32(args[1], &arg1 ); + ok &= seval_to_int32(args[2], &arg2 ); + ok &= seval_to_int32(args[3], &arg3 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glViewport((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); + s.rval().setUndefined(); + return true; +} +SE_BIND_FUNC(JSB_glViewport) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_functions.hpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_functions.hpp new file mode 100644 index 0000000000..1419b7c8d4 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_functions.hpp @@ -0,0 +1,130 @@ +#pragma once + +#include "cocos/scripting/js-bindings/jswrapper/SeApi.h" + +SE_DECLARE_FUNC(JSB_glActiveTexture); +SE_DECLARE_FUNC(JSB_glAttachShader); +SE_DECLARE_FUNC(JSB_glBindAttribLocation); +SE_DECLARE_FUNC(JSB_glBindBuffer); +SE_DECLARE_FUNC(JSB_glBindFramebuffer); +SE_DECLARE_FUNC(JSB_glBindRenderbuffer); +SE_DECLARE_FUNC(JSB_glBindTexture); +SE_DECLARE_FUNC(JSB_glBlendColor); +SE_DECLARE_FUNC(JSB_glBlendEquation); +SE_DECLARE_FUNC(JSB_glBlendEquationSeparate); +SE_DECLARE_FUNC(JSB_glBlendFunc); +SE_DECLARE_FUNC(JSB_glBlendFuncSeparate); +SE_DECLARE_FUNC(JSB_glBufferData); +SE_DECLARE_FUNC(JSB_glBufferSubData); +SE_DECLARE_FUNC(JSB_glCheckFramebufferStatus); +SE_DECLARE_FUNC(JSB_glClear); +SE_DECLARE_FUNC(JSB_glClearColor); +SE_DECLARE_FUNC(JSB_glClearDepthf); +SE_DECLARE_FUNC(JSB_glClearStencil); +SE_DECLARE_FUNC(JSB_glColorMask); +SE_DECLARE_FUNC(JSB_glCompileShader); +SE_DECLARE_FUNC(JSB_glCompressedTexImage2D); +SE_DECLARE_FUNC(JSB_glCompressedTexSubImage2D); +SE_DECLARE_FUNC(JSB_glCopyTexImage2D); +SE_DECLARE_FUNC(JSB_glCopyTexSubImage2D); +SE_DECLARE_FUNC(JSB_glCreateProgram); +SE_DECLARE_FUNC(JSB_glCreateShader); +SE_DECLARE_FUNC(JSB_glCullFace); +SE_DECLARE_FUNC(JSB_glDeleteBuffers); +SE_DECLARE_FUNC(JSB_glDeleteFramebuffers); +SE_DECLARE_FUNC(JSB_glDeleteProgram); +SE_DECLARE_FUNC(JSB_glDeleteRenderbuffers); +SE_DECLARE_FUNC(JSB_glDeleteShader); +SE_DECLARE_FUNC(JSB_glDeleteTextures); +SE_DECLARE_FUNC(JSB_glDepthFunc); +SE_DECLARE_FUNC(JSB_glDepthMask); +SE_DECLARE_FUNC(JSB_glDepthRangef); +SE_DECLARE_FUNC(JSB_glDetachShader); +SE_DECLARE_FUNC(JSB_glDisable); +SE_DECLARE_FUNC(JSB_glDisableVertexAttribArray); +SE_DECLARE_FUNC(JSB_glDrawArrays); +SE_DECLARE_FUNC(JSB_glDrawElements); +SE_DECLARE_FUNC(JSB_glEnable); +SE_DECLARE_FUNC(JSB_glEnableVertexAttribArray); +SE_DECLARE_FUNC(JSB_glFinish); +SE_DECLARE_FUNC(JSB_glFlush); +SE_DECLARE_FUNC(JSB_glFramebufferRenderbuffer); +SE_DECLARE_FUNC(JSB_glFramebufferTexture2D); +SE_DECLARE_FUNC(JSB_glFrontFace); +SE_DECLARE_FUNC(JSB_glGenBuffers); +SE_DECLARE_FUNC(JSB_glGenFramebuffers); +SE_DECLARE_FUNC(JSB_glGenRenderbuffers); +SE_DECLARE_FUNC(JSB_glGenTextures); +SE_DECLARE_FUNC(JSB_glGenerateMipmap); +SE_DECLARE_FUNC(JSB_glGetActiveAttrib); +SE_DECLARE_FUNC(JSB_glGetActiveUniform); +SE_DECLARE_FUNC(JSB_glGetAttachedShaders); +SE_DECLARE_FUNC(JSB_glGetAttribLocation); +SE_DECLARE_FUNC(JSB_glGetError); +SE_DECLARE_FUNC(JSB_glGetProgramInfoLog); +SE_DECLARE_FUNC(JSB_glGetProgramiv); +SE_DECLARE_FUNC(JSB_glGetShaderInfoLog); +SE_DECLARE_FUNC(JSB_glGetShaderSource); +SE_DECLARE_FUNC(JSB_glGetShaderiv); +SE_DECLARE_FUNC(JSB_glGetTexParameterfv); +SE_DECLARE_FUNC(JSB_glGetUniformLocation); +SE_DECLARE_FUNC(JSB_glGetUniformfv); +SE_DECLARE_FUNC(JSB_glHint); +SE_DECLARE_FUNC(JSB_glIsBuffer); +SE_DECLARE_FUNC(JSB_glIsEnabled); +SE_DECLARE_FUNC(JSB_glIsFramebuffer); +SE_DECLARE_FUNC(JSB_glIsProgram); +SE_DECLARE_FUNC(JSB_glIsRenderbuffer); +SE_DECLARE_FUNC(JSB_glIsShader); +SE_DECLARE_FUNC(JSB_glIsTexture); +SE_DECLARE_FUNC(JSB_glLineWidth); +SE_DECLARE_FUNC(JSB_glLinkProgram); +SE_DECLARE_FUNC(JSB_glPixelStorei); +SE_DECLARE_FUNC(JSB_glPolygonOffset); +SE_DECLARE_FUNC(JSB_glReadPixels); +SE_DECLARE_FUNC(JSB_glReleaseShaderCompiler); +SE_DECLARE_FUNC(JSB_glRenderbufferStorage); +SE_DECLARE_FUNC(JSB_glSampleCoverage); +SE_DECLARE_FUNC(JSB_glScissor); +SE_DECLARE_FUNC(JSB_glShaderSource); +SE_DECLARE_FUNC(JSB_glStencilFunc); +SE_DECLARE_FUNC(JSB_glStencilFuncSeparate); +SE_DECLARE_FUNC(JSB_glStencilMask); +SE_DECLARE_FUNC(JSB_glStencilMaskSeparate); +SE_DECLARE_FUNC(JSB_glStencilOp); +SE_DECLARE_FUNC(JSB_glStencilOpSeparate); +SE_DECLARE_FUNC(JSB_glTexImage2D); +SE_DECLARE_FUNC(JSB_glTexParameterf); +SE_DECLARE_FUNC(JSB_glTexParameteri); +SE_DECLARE_FUNC(JSB_glTexSubImage2D); +SE_DECLARE_FUNC(JSB_glUniform1f); +SE_DECLARE_FUNC(JSB_glUniform1fv); +SE_DECLARE_FUNC(JSB_glUniform1i); +SE_DECLARE_FUNC(JSB_glUniform1iv); +SE_DECLARE_FUNC(JSB_glUniform2f); +SE_DECLARE_FUNC(JSB_glUniform2fv); +SE_DECLARE_FUNC(JSB_glUniform2i); +SE_DECLARE_FUNC(JSB_glUniform2iv); +SE_DECLARE_FUNC(JSB_glUniform3f); +SE_DECLARE_FUNC(JSB_glUniform3fv); +SE_DECLARE_FUNC(JSB_glUniform3i); +SE_DECLARE_FUNC(JSB_glUniform3iv); +SE_DECLARE_FUNC(JSB_glUniform4f); +SE_DECLARE_FUNC(JSB_glUniform4fv); +SE_DECLARE_FUNC(JSB_glUniform4i); +SE_DECLARE_FUNC(JSB_glUniform4iv); +SE_DECLARE_FUNC(JSB_glUniformMatrix2fv); +SE_DECLARE_FUNC(JSB_glUniformMatrix3fv); +SE_DECLARE_FUNC(JSB_glUniformMatrix4fv); +SE_DECLARE_FUNC(JSB_glUseProgram); +SE_DECLARE_FUNC(JSB_glValidateProgram); +SE_DECLARE_FUNC(JSB_glVertexAttrib1f); +SE_DECLARE_FUNC(JSB_glVertexAttrib1fv); +SE_DECLARE_FUNC(JSB_glVertexAttrib2f); +SE_DECLARE_FUNC(JSB_glVertexAttrib2fv); +SE_DECLARE_FUNC(JSB_glVertexAttrib3f); +SE_DECLARE_FUNC(JSB_glVertexAttrib3fv); +SE_DECLARE_FUNC(JSB_glVertexAttrib4f); +SE_DECLARE_FUNC(JSB_glVertexAttrib4fv); +SE_DECLARE_FUNC(JSB_glVertexAttribPointer); +SE_DECLARE_FUNC(JSB_glViewport); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp new file mode 100644 index 0000000000..c1c37cc919 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp @@ -0,0 +1,539 @@ +#include "scripting/js-bindings/manual/jsb_opengl_manual.hpp" +#include "scripting/js-bindings/manual/jsb_opengl_functions.hpp" +#include "scripting/js-bindings/manual/jsb_conversions.hpp" +#include "platform/CCGL.h" + +// Helper functions that link "glGenXXXs" (OpenGL ES 2.0 spec), with "gl.createXXX" (WebGL spec) +bool JSB_glGenTextures(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 0, false, "Invalid number of arguments" ); + + GLuint texture; + glGenTextures(1, &texture); + + s.rval().setUint32(texture); + return true; +} +SE_BIND_FUNC(JSB_glGenTextures) + +bool JSB_glGenBuffers(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 0, false, "Invalid number of arguments" ); + + GLuint buffer; + glGenBuffers(1, &buffer); + s.rval().setUint32(buffer); + return true; +} +SE_BIND_FUNC(JSB_glGenBuffers) + +bool JSB_glGenRenderbuffers(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 0, false, "Invalid number of arguments" ); + + GLuint renderbuffers; + glGenRenderbuffers(1, &renderbuffers); + s.rval().setUint32(renderbuffers); + return true; +} +SE_BIND_FUNC(JSB_glGenRenderbuffers) + +bool JSB_glGenFramebuffers(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 0, false, "Invalid number of arguments" ); + + GLuint framebuffers; + glGenFramebuffers(1, &framebuffers); + s.rval().setUint32(framebuffers); + return true; +} +SE_BIND_FUNC(JSB_glGenFramebuffers) + +bool JSB_glDeleteTextures(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDeleteTextures(1, &arg0); + + return true; +} +SE_BIND_FUNC(JSB_glDeleteTextures) + +bool JSB_glDeleteBuffers(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDeleteBuffers(1, &arg0); + + return true; +} +SE_BIND_FUNC(JSB_glDeleteBuffers) + +bool JSB_glDeleteRenderbuffers(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDeleteRenderbuffers(1, &arg0); + + return true; +} +SE_BIND_FUNC(JSB_glDeleteRenderbuffers) + +bool JSB_glDeleteFramebuffers(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + glDeleteFramebuffers(1, &arg0); + + return true; +} +SE_BIND_FUNC(JSB_glDeleteFramebuffers) + +bool JSB_glShaderSource(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; std::string arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_std_string(args[1], &arg1); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + const GLchar* sources[] = { arg1.c_str() }; + glShaderSource(arg0, 1, sources, nullptr); + + return true; +} +SE_BIND_FUNC(JSB_glShaderSource) + +bool JSB_glGetShaderiv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0, arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLint ret; + glGetShaderiv(arg0, arg1, &ret); + s.rval().setInt32(ret); + return true; +} +SE_BIND_FUNC(JSB_glGetShaderiv) + +bool JSB_glGetProgramiv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0, arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLint ret; + glGetProgramiv(arg0, arg1, &ret); + s.rval().setInt32(ret); + return true; +} +SE_BIND_FUNC(JSB_glGetProgramiv) + +bool JSB_glGetProgramInfoLog(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLsizei length; + glGetProgramiv(arg0, GL_INFO_LOG_LENGTH, &length); + GLchar* src = new (std::nothrow) GLchar[length]; + glGetProgramInfoLog(arg0, length, NULL, src); + + s.rval().setString(src); + CC_SAFE_DELETE_ARRAY(src); + return true; +} +SE_BIND_FUNC(JSB_glGetProgramInfoLog) + +// DOMString? getShaderInfoLog(WebGLShader? shader); +bool JSB_glGetShaderInfoLog(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLsizei length; + glGetShaderiv(arg0, GL_INFO_LOG_LENGTH, &length); + GLchar* src = new (std::nothrow) GLchar[length]; + glGetShaderInfoLog(arg0, length, NULL, src); + + s.rval().setString(src); + CC_SAFE_DELETE_ARRAY(src); + return true; +} +SE_BIND_FUNC(JSB_glGetShaderInfoLog) + +// DOMString? getShaderSource(WebGLShader? shader); +bool JSB_glGetShaderSource(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLsizei length; + glGetShaderiv(arg0, GL_SHADER_SOURCE_LENGTH, &length); + GLchar* src = new (std::nothrow) GLchar[length]; + glGetShaderSource(arg0, length, NULL, src); + + s.rval().setString(src); + CC_SAFE_DELETE_ARRAY(src); + return true; +} +SE_BIND_FUNC(JSB_glGetShaderSource) + +// interface WebGLActiveInfo { +// readonly attribute GLint size; +// readonly attribute GLenum type; +// readonly attribute DOMString name; +// WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index); +bool JSB_glGetActiveAttrib(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0, arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLsizei length; + glGetProgramiv(arg0, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length); + GLchar* buffer = new (std::nothrow) GLchar[length]; + GLint size = -1; + GLenum type = -1; + + glGetActiveAttrib(arg0, arg1, length, NULL, &size, &type, buffer); + + se::HandleObject object(se::Object::createPlainObject()); + object->setProperty("size", se::Value((int32_t)size)); + object->setProperty("type", se::Value((int32_t)type)); + object->setProperty("name", se::Value((char*)buffer)); + s.rval().setObject(object.get()); + + CC_SAFE_DELETE_ARRAY(buffer); + + return true; +} +SE_BIND_FUNC(JSB_glGetActiveAttrib) + + +// interface WebGLActiveInfo { +// readonly attribute GLint size; +// readonly attribute GLenum type; +// readonly attribute DOMString name; +// }; +// WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index); +bool JSB_glGetActiveUniform(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0, arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLsizei length; + glGetProgramiv(arg0, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length); + GLchar* buffer = new (std::nothrow) GLchar[length]; + GLint size = -1; + GLenum type = -1; + + glGetActiveUniform(arg0, arg1, length, NULL, &size, &type, buffer); + + se::HandleObject object(se::Object::createPlainObject()); + object->setProperty("size", se::Value((int32_t)size)); + object->setProperty("type", se::Value((int32_t)type)); + object->setProperty("name", se::Value((char*)buffer)); + s.rval().setObject(object.get()); + + CC_SAFE_DELETE_ARRAY(buffer); + return true; +} +SE_BIND_FUNC(JSB_glGetActiveUniform) + +// sequence? getAttachedShaders(WebGLProgram? program); +bool JSB_glGetAttachedShaders(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0; + + ok &= seval_to_uint32(args[0], &arg0 ); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + GLsizei length; + glGetProgramiv(arg0, GL_ATTACHED_SHADERS, &length); + GLuint* buffer = new (std::nothrow) GLuint[length]; + memset(buffer, 0, length * sizeof(GLuint)); + //Fix bug 2448, it seems that glGetAttachedShaders will crash if we send NULL to the third parameter (eg Windows), same as in lua binding + GLsizei realShaderCount = 0; + glGetAttachedShaders(arg0, length, &realShaderCount, buffer); + + se::HandleObject jsobj(se::Object::createArrayObject(length)); + for( int i=0; isetArrayElement(i, se::Value(buffer[i])); + } + + s.rval().setObject(jsobj.get()); + CC_SAFE_DELETE_ARRAY(buffer); + return true; + +} +SE_BIND_FUNC(JSB_glGetAttachedShaders) + +// sequence? getSupportedExtensions(); +bool JSB_glGetSupportedExtensions(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 0, false, "Invalid number of arguments" ); + + const GLubyte *extensions = glGetString(GL_EXTENSIONS); + + se::HandleObject jsobj(se::Object::createArrayObject(1)); + + // copy, to be able to add '\0' + size_t len = strlen((char*)extensions); + GLubyte* copy = new (std::nothrow) GLubyte[len+1]; + copy[len] = '\0'; + strncpy((char*)copy, (const char*)extensions, len ); + + size_t start_extension = 0; + uint32_t element = 0; + for( size_t i=0; isetArrayElement(element, se::Value((const char*)©[start_extension])); + + start_extension = i+1; + ++element; + ++i; + } + } + + s.rval().setObject(jsobj.get()); + CC_SAFE_DELETE_ARRAY(copy); + return true; + +} +SE_BIND_FUNC(JSB_glGetSupportedExtensions) + +// any getTexParameter(GLenum target, GLenum pname); +bool JSB_glGetTexParameterfv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false,"JSB_glGetTexParameterfv: Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0, arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + + SE_PRECONDITION2(ok, false, "JSB_glGetTexParameterfv: Error processing arguments"); + + GLfloat param; + glGetTexParameterfv(arg0, arg1, ¶m); + + s.rval().setFloat(param); + return true; +} +SE_BIND_FUNC(JSB_glGetTexParameterfv) + +// any getUniform(WebGLProgram? program, WebGLUniformLocation? location); +bool JSB_glGetUniformfv(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + SE_PRECONDITION2(argc == 2, false,"JSB_glGetUniformfv: Invalid number of arguments" ); + + bool ok = true; + uint32_t arg0, arg1; + + ok &= seval_to_uint32(args[0], &arg0 ); + ok &= seval_to_uint32(args[1], &arg1 ); + + SE_PRECONDITION2(ok, false, "JSB_glGetUniformfv: Error processing arguments"); + + GLint activeUniforms; + glGetProgramiv(arg0, GL_ACTIVE_UNIFORMS, &activeUniforms); + + GLsizei length; + glGetProgramiv(arg0, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length); + GLchar* namebuffer = new (std::nothrow) GLchar[length+1]; + GLint size = -1; + GLenum type = -1; + + bool isLocationFound = false; + for (int i = 0; i < activeUniforms; ++i) + { + glGetActiveUniform(arg0, i, length, NULL, &size, &type, namebuffer); + if(arg1 == glGetUniformLocation(arg0, namebuffer)) + { + isLocationFound = true; + break; + } + } + + if(!isLocationFound) + { + size = -1; + type = -1; + } + CC_SAFE_DELETE_ARRAY(namebuffer); + + int usize = 0; + int utype = 0; + switch(type) { + + // float + case GL_FLOAT: + usize = 1; + utype = GL_FLOAT; + break; + case GL_FLOAT_MAT2: + usize = 2 * 2; + utype = GL_FLOAT; + break; + case GL_FLOAT_MAT3: + usize = 3 * 3; + utype = GL_FLOAT; + break; + case GL_FLOAT_MAT4: + usize = 4 * 4; + utype = GL_FLOAT; + break; + case GL_FLOAT_VEC2: + usize = 2; + utype = GL_FLOAT; + break; + case GL_FLOAT_VEC3: + usize = 3; + utype = GL_FLOAT; + break; + case GL_FLOAT_VEC4: + usize = 4; + utype = GL_FLOAT; + break; + + // int + case GL_INT: + usize = 1; + utype = GL_INT; + break; + case GL_INT_VEC2: + usize = 2; + utype = GL_INT; + break; + case GL_INT_VEC3: + usize = 3; + utype = GL_INT; + break; + case GL_INT_VEC4: + usize = 4; + utype = GL_INT; + break; + + default: + SE_REPORT_ERROR("JSB_glGetUniformfv: Uniform Type (%d) not supported", (int)type); + return false; + } + + if( utype == GL_FLOAT) + { + GLfloat* param = new (std::nothrow) GLfloat[usize]; + glGetUniformfv(arg0, arg1, param); + + se::HandleObject obj(se::Object::createTypedArray(se::Object::TypedArrayType::FLOAT32, param, usize * sizeof(GLfloat))); + s.rval().setObject(obj); + CC_SAFE_DELETE_ARRAY(param); + return true; + } + else if( utype == GL_INT ) + { + GLint* param = new (std::nothrow) GLint[usize]; + glGetUniformiv(arg0, arg1, param); + + se::HandleObject obj(se::Object::createTypedArray(se::Object::TypedArrayType::INT32, param, usize * sizeof(GLint))); + s.rval().setObject(obj); + CC_SAFE_DELETE_ARRAY(param); + return true; + } + + SE_REPORT_ERROR("Supported type: %d", utype); + return false; +} +SE_BIND_FUNC(JSB_glGetUniformfv) + diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.hpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.hpp new file mode 100644 index 0000000000..c8d5d97988 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.hpp @@ -0,0 +1,6 @@ +#pragma once + +#include "cocos/scripting/js-bindings/jswrapper/SeApi.h" + +// forward declaration of new functions +SE_DECLARE_FUNC(JSB_glGetSupportedExtensions); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_node.cpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_node.cpp new file mode 100644 index 0000000000..c0ba637667 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_node.cpp @@ -0,0 +1,104 @@ +#include "jsb_opengl_node.hpp" +#include "cocos/scripting/js-bindings/jswrapper/SeApi.h" +#include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp" +#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp" +#include "cocos/scripting/js-bindings/manual/jsb_global.h" +#include "scripting/js-bindings/manual/jsb_opengl_functions.hpp" + +USING_NS_CC; + +void JSB_GLNode::draw(Renderer *renderer, const Mat4& transform, uint32_t flags) +{ + _customCommand.init(_globalZOrder); + _customCommand.func = CC_CALLBACK_0(JSB_GLNode::onDraw, this, transform, flags); + renderer->addCommand(&_customCommand); +} + +void JSB_GLNode::onDraw(Mat4 &transform, uint32_t flags) +{ + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + auto iter = se::NativePtrToObjectMap::find(this); + if (iter != se::NativePtrToObjectMap::end()) + { + se::Object* jsObj = iter->second; + se::Value funcVal; + if (jsObj->getProperty("draw", &funcVal) && funcVal.isObject() && funcVal.toObject()->isFunction()) + { + auto director = Director::getInstance(); + director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); + director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, transform); + + funcVal.toObject()->call(se::EmptyValueArray, jsObj); + + director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW); + } + } +} + +static se::Class* __jsb_cocos2dx_GLNode_class = nullptr; +static se::Object* __jsb_cocos2dx_GLNode_proto = nullptr; + +static bool js_cocos2dx_GLNode_finalize(se::State& s) +{ + CCLOGINFO("jsbindings: finalizing JS object %p (JSB_GLNode)", s.nativeThisObject()); + JSB_GLNode* cobj = (JSB_GLNode*)s.nativeThisObject(); + if (cobj->getReferenceCount() == 1) + cobj->autorelease(); + else + cobj->release(); + return true; +} +SE_BIND_FINALIZE_FUNC(js_cocos2dx_GLNode_finalize) + +static bool js_cocos2dx_GLNode_constructor(se::State& s) +{ + JSB_GLNode* cobj = new (std::nothrow) JSB_GLNode(); + s.thisObject()->setPrivateData(cobj); + return true; +} +SE_BIND_CTOR(js_cocos2dx_GLNode_constructor, __jsb_cocos2dx_GLNode_class, js_cocos2dx_GLNode_finalize) + +static bool js_cocos2dx_GLNode_ctor(se::State& s) +{ + JSB_GLNode* cobj = new (std::nothrow) JSB_GLNode(); + s.thisObject()->setPrivateData(cobj); + return true; +} +SE_BIND_SUB_CLS_CTOR(js_cocos2dx_GLNode_ctor, __jsb_cocos2dx_GLNode_class, js_cocos2dx_GLNode_finalize) + +static bool js_cocos2dx_GLNode_create(se::State& s) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + auto result = new (std::nothrow) JSB_GLNode(); + auto obj = se::Object::createObjectWithClass(__jsb_cocos2dx_GLNode_class); + obj->setPrivateData(result); + s.rval().setObject(obj); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_GLNode_create) + +bool js_register_cocos2dx_GLNode(se::Object* obj) +{ + auto cls = se::Class::create("GLNode", obj, __jsb_cocos2d_Node_proto, _SE(js_cocos2dx_GLNode_constructor)); + + cls->defineFunction("ctor", _SE(js_cocos2dx_GLNode_ctor)); + cls->defineStaticFunction("create", _SE(js_cocos2dx_GLNode_create)); + cls->defineFinalizeFunction(_SE(js_cocos2dx_GLNode_finalize)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cocos2dx_GLNode_proto = cls->getProto(); + __jsb_cocos2dx_GLNode_class = cls; + + jsb_set_extend_property("cc", "GLNode"); + se::ScriptEngine::getInstance()->clearException(); + return true; +} diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_node.hpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_node.hpp new file mode 100644 index 0000000000..f3fae89083 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_node.hpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2013-2017 Chukong Technologies Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "cocos2d.h" + +class JSB_GLNode : public cocos2d::Node +{ +public: + void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4& transform, uint32_t flags) override; +protected: + void onDraw(cocos2d::Mat4 &transform, uint32_t flags); + cocos2d::CustomCommand _customCommand; +}; + +namespace se { + class Object; +} + +bool js_register_cocos2dx_GLNode(se::Object* global); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_registration.cpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_registration.cpp new file mode 100644 index 0000000000..1d629881fc --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_registration.cpp @@ -0,0 +1,145 @@ +#include "jsb_opengl_registration.hpp" +#include "cocos/scripting/js-bindings/jswrapper/SeApi.h" +#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp" +#include "cocos/scripting/js-bindings/manual/jsb_global.h" +#include "scripting/js-bindings/manual/jsb_opengl_functions.hpp" +#include "scripting/js-bindings/manual/jsb_opengl_node.hpp" +#include "scripting/js-bindings/manual/jsb_opengl_manual.hpp" + +bool JSB_register_opengl(se::Object* obj) +{ + js_register_cocos2dx_GLNode(__ccObj); + + // New WebGL functions, not present on OpenGL ES 2.0 + __glObj->defineFunction("getSupportedExtensions", _SE(JSB_glGetSupportedExtensions)); + __glObj->defineFunction("activeTexture", _SE(JSB_glActiveTexture)); + __glObj->defineFunction("_attachShader", _SE(JSB_glAttachShader)); + __glObj->defineFunction("_bindAttribLocation", _SE(JSB_glBindAttribLocation)); + __glObj->defineFunction("_bindBuffer", _SE(JSB_glBindBuffer)); + __glObj->defineFunction("_bindFramebuffer", _SE(JSB_glBindFramebuffer)); + __glObj->defineFunction("_bindRenderbuffer", _SE(JSB_glBindRenderbuffer)); + __glObj->defineFunction("_bindTexture", _SE(JSB_glBindTexture)); + __glObj->defineFunction("blendColor", _SE(JSB_glBlendColor)); + __glObj->defineFunction("blendEquation", _SE(JSB_glBlendEquation)); + __glObj->defineFunction("blendEquationSeparate", _SE(JSB_glBlendEquationSeparate)); + __glObj->defineFunction("blendFunc", _SE(JSB_glBlendFunc)); + __glObj->defineFunction("blendFuncSeparate", _SE(JSB_glBlendFuncSeparate)); + __glObj->defineFunction("bufferData", _SE(JSB_glBufferData)); + __glObj->defineFunction("bufferSubData", _SE(JSB_glBufferSubData)); + __glObj->defineFunction("checkFramebufferStatus", _SE(JSB_glCheckFramebufferStatus)); + __glObj->defineFunction("clear", _SE(JSB_glClear)); + __glObj->defineFunction("clearColor", _SE(JSB_glClearColor)); + __glObj->defineFunction("clearDepthf", _SE(JSB_glClearDepthf)); + __glObj->defineFunction("clearStencil", _SE(JSB_glClearStencil)); + __glObj->defineFunction("colorMask", _SE(JSB_glColorMask)); + __glObj->defineFunction("_compileShader", _SE(JSB_glCompileShader)); + __glObj->defineFunction("compressedTexImage2D", _SE(JSB_glCompressedTexImage2D)); + __glObj->defineFunction("compressedTexSubImage2D", _SE(JSB_glCompressedTexSubImage2D)); + __glObj->defineFunction("copyTexImage2D", _SE(JSB_glCopyTexImage2D)); + __glObj->defineFunction("copyTexSubImage2D", _SE(JSB_glCopyTexSubImage2D)); + __glObj->defineFunction("_createProgram", _SE(JSB_glCreateProgram)); + __glObj->defineFunction("_createShader", _SE(JSB_glCreateShader)); + __glObj->defineFunction("cullFace", _SE(JSB_glCullFace)); + __glObj->defineFunction("_deleteBuffer", _SE(JSB_glDeleteBuffers)); + __glObj->defineFunction("_deleteFramebuffer", _SE(JSB_glDeleteFramebuffers)); + __glObj->defineFunction("_deleteProgram", _SE(JSB_glDeleteProgram)); + __glObj->defineFunction("_deleteRenderbuffer", _SE(JSB_glDeleteRenderbuffers)); + __glObj->defineFunction("_deleteShader", _SE(JSB_glDeleteShader)); + __glObj->defineFunction("_deleteTexture", _SE(JSB_glDeleteTextures)); + __glObj->defineFunction("depthFunc", _SE(JSB_glDepthFunc)); + __glObj->defineFunction("depthMask", _SE(JSB_glDepthMask)); + __glObj->defineFunction("depthRangef", _SE(JSB_glDepthRangef)); + __glObj->defineFunction("detachShader", _SE(JSB_glDetachShader)); + __glObj->defineFunction("disable", _SE(JSB_glDisable)); + __glObj->defineFunction("disableVertexAttribArray", _SE(JSB_glDisableVertexAttribArray)); + __glObj->defineFunction("drawArrays", _SE(JSB_glDrawArrays)); + __glObj->defineFunction("drawElements", _SE(JSB_glDrawElements)); + __glObj->defineFunction("enable", _SE(JSB_glEnable)); + __glObj->defineFunction("enableVertexAttribArray", _SE(JSB_glEnableVertexAttribArray)); + __glObj->defineFunction("finish", _SE(JSB_glFinish)); + __glObj->defineFunction("flush", _SE(JSB_glFlush)); + __glObj->defineFunction("framebufferRenderbuffer", _SE(JSB_glFramebufferRenderbuffer)); + __glObj->defineFunction("framebufferTexture2D", _SE(JSB_glFramebufferTexture2D)); + __glObj->defineFunction("frontFace", _SE(JSB_glFrontFace)); + __glObj->defineFunction("_createBuffer", _SE(JSB_glGenBuffers)); + __glObj->defineFunction("_createFramebuffer", _SE(JSB_glGenFramebuffers)); + __glObj->defineFunction("_createRenderbuffer", _SE(JSB_glGenRenderbuffers)); + __glObj->defineFunction("_createTexture", _SE(JSB_glGenTextures)); + __glObj->defineFunction("generateMipmap", _SE(JSB_glGenerateMipmap)); + __glObj->defineFunction("_getActiveAttrib", _SE(JSB_glGetActiveAttrib)); + __glObj->defineFunction("_getActiveUniform", _SE(JSB_glGetActiveUniform)); + __glObj->defineFunction("_getAttachedShaders", _SE(JSB_glGetAttachedShaders)); + __glObj->defineFunction("_getAttribLocation", _SE(JSB_glGetAttribLocation)); + __glObj->defineFunction("getError", _SE(JSB_glGetError)); + __glObj->defineFunction("_getProgramInfoLog", _SE(JSB_glGetProgramInfoLog)); + __glObj->defineFunction("_getProgramParameter", _SE(JSB_glGetProgramiv)); + __glObj->defineFunction("_getShaderInfoLog", _SE(JSB_glGetShaderInfoLog)); + __glObj->defineFunction("_getShaderSource", _SE(JSB_glGetShaderSource)); + __glObj->defineFunction("_getShaderParameter", _SE(JSB_glGetShaderiv)); + __glObj->defineFunction("getTexParameter", _SE(JSB_glGetTexParameterfv)); + __glObj->defineFunction("_getUniformLocation", _SE(JSB_glGetUniformLocation)); + __glObj->defineFunction("_getUniform", _SE(JSB_glGetUniformfv)); + __glObj->defineFunction("hint", _SE(JSB_glHint)); + __glObj->defineFunction("isBuffer", _SE(JSB_glIsBuffer)); + __glObj->defineFunction("isEnabled", _SE(JSB_glIsEnabled)); + __glObj->defineFunction("isFramebuffer", _SE(JSB_glIsFramebuffer)); + __glObj->defineFunction("isProgram", _SE(JSB_glIsProgram)); + __glObj->defineFunction("isRenderbuffer", _SE(JSB_glIsRenderbuffer)); + __glObj->defineFunction("isShader", _SE(JSB_glIsShader)); + __glObj->defineFunction("isTexture", _SE(JSB_glIsTexture)); + __glObj->defineFunction("lineWidth", _SE(JSB_glLineWidth)); + __glObj->defineFunction("_linkProgram", _SE(JSB_glLinkProgram)); + __glObj->defineFunction("pixelStorei", _SE(JSB_glPixelStorei)); + __glObj->defineFunction("polygonOffset", _SE(JSB_glPolygonOffset)); + __glObj->defineFunction("readPixels", _SE(JSB_glReadPixels)); + __glObj->defineFunction("releaseShaderCompiler", _SE(JSB_glReleaseShaderCompiler)); + __glObj->defineFunction("renderbufferStorage", _SE(JSB_glRenderbufferStorage)); + __glObj->defineFunction("sampleCoverage", _SE(JSB_glSampleCoverage)); + __glObj->defineFunction("scissor", _SE(JSB_glScissor)); + __glObj->defineFunction("_shaderSource", _SE(JSB_glShaderSource)); + __glObj->defineFunction("stencilFunc", _SE(JSB_glStencilFunc)); + __glObj->defineFunction("stencilFuncSeparate", _SE(JSB_glStencilFuncSeparate)); + __glObj->defineFunction("stencilMask", _SE(JSB_glStencilMask)); + __glObj->defineFunction("stencilMaskSeparate", _SE(JSB_glStencilMaskSeparate)); + __glObj->defineFunction("stencilOp", _SE(JSB_glStencilOp)); + __glObj->defineFunction("stencilOpSeparate", _SE(JSB_glStencilOpSeparate)); + __glObj->defineFunction("_texImage2D", _SE(JSB_glTexImage2D)); + __glObj->defineFunction("texParameterf", _SE(JSB_glTexParameterf)); + __glObj->defineFunction("texParameteri", _SE(JSB_glTexParameteri)); + __glObj->defineFunction("_texSubImage2D", _SE(JSB_glTexSubImage2D)); + __glObj->defineFunction("uniform1f", _SE(JSB_glUniform1f)); + __glObj->defineFunction("uniform1fv", _SE(JSB_glUniform1fv)); + __glObj->defineFunction("uniform1i", _SE(JSB_glUniform1i)); + __glObj->defineFunction("uniform1iv", _SE(JSB_glUniform1iv)); + __glObj->defineFunction("uniform2f", _SE(JSB_glUniform2f)); + __glObj->defineFunction("uniform2fv", _SE(JSB_glUniform2fv)); + __glObj->defineFunction("uniform2i", _SE(JSB_glUniform2i)); + __glObj->defineFunction("uniform2iv", _SE(JSB_glUniform2iv)); + __glObj->defineFunction("uniform3f", _SE(JSB_glUniform3f)); + __glObj->defineFunction("uniform3fv", _SE(JSB_glUniform3fv)); + __glObj->defineFunction("uniform3i", _SE(JSB_glUniform3i)); + __glObj->defineFunction("uniform3iv", _SE(JSB_glUniform3iv)); + __glObj->defineFunction("uniform4f", _SE(JSB_glUniform4f)); + __glObj->defineFunction("uniform4fv", _SE(JSB_glUniform4fv)); + __glObj->defineFunction("uniform4i", _SE(JSB_glUniform4i)); + __glObj->defineFunction("uniform4iv", _SE(JSB_glUniform4iv)); + __glObj->defineFunction("uniformMatrix2fv", _SE(JSB_glUniformMatrix2fv)); + __glObj->defineFunction("uniformMatrix3fv", _SE(JSB_glUniformMatrix3fv)); + __glObj->defineFunction("uniformMatrix4fv", _SE(JSB_glUniformMatrix4fv)); + __glObj->defineFunction("_useProgram", _SE(JSB_glUseProgram)); + __glObj->defineFunction("_validateProgram", _SE(JSB_glValidateProgram)); + __glObj->defineFunction("vertexAttrib1f", _SE(JSB_glVertexAttrib1f)); + __glObj->defineFunction("vertexAttrib1fv", _SE(JSB_glVertexAttrib1fv)); + __glObj->defineFunction("vertexAttrib2f", _SE(JSB_glVertexAttrib2f)); + __glObj->defineFunction("vertexAttrib2fv", _SE(JSB_glVertexAttrib2fv)); + __glObj->defineFunction("vertexAttrib3f", _SE(JSB_glVertexAttrib3f)); + __glObj->defineFunction("vertexAttrib3fv", _SE(JSB_glVertexAttrib3fv)); + __glObj->defineFunction("vertexAttrib4f", _SE(JSB_glVertexAttrib4f)); + __glObj->defineFunction("vertexAttrib4fv", _SE(JSB_glVertexAttrib4fv)); + __glObj->defineFunction("vertexAttribPointer", _SE(JSB_glVertexAttribPointer)); + __glObj->defineFunction("viewport", _SE(JSB_glViewport)); + + return true; + +} + diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_registration.hpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_registration.hpp new file mode 100644 index 0000000000..77bed3e554 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_registration.hpp @@ -0,0 +1,7 @@ +#pragma once + +namespace se { + class Object; +} + +bool JSB_register_opengl(se::Object* obj); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_platform_ios.h b/native/cocos/scripting/js-bindings/manual/jsb_platform_ios.h new file mode 100644 index 0000000000..3bea5f0042 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_platform_ios.h @@ -0,0 +1,12 @@ +#pragma once + +#import + +@interface JSB_PlatformIOS : NSObject +{ + +} + ++ (NSString*) getChannelID; + +@end diff --git a/native/cocos/scripting/js-bindings/manual/jsb_platfrom_ios.m b/native/cocos/scripting/js-bindings/manual/jsb_platfrom_ios.m new file mode 100644 index 0000000000..f1280890d3 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/jsb_platfrom_ios.m @@ -0,0 +1,16 @@ +#import "jsb_platform_ios.h" + +@implementation JSB_PlatformIOS + ++ (NSString*) getChannelID +{ + NSString* File = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"]; + NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithContentsOfFile:File]; + id channelId = [dict objectForKey:@"ASC_ChannelID"]; + if (nil != channelId) { + return channelId; + } + return @""; +} + +@end diff --git a/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp index 1d61b61f92..8fa90712eb 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp @@ -25,7 +25,7 @@ se::Object* __jsb_spine_TrackEntry_proto = nullptr; static bool jsb_spine_TrackEntry_finalize(se::State& s) { - CCLOG("jsbindings: finalizing JS object %p (spTrackEntry)", s.nativeThisObject()); + CCLOGINFO("jsbindings: finalizing JS object %p (spTrackEntry)", s.nativeThisObject()); return true; } SE_BIND_FINALIZE_FUNC(jsb_spine_TrackEntry_finalize) @@ -290,7 +290,7 @@ static bool js_register_spine_TrackEntry(se::Object* obj) auto iter = se::NativePtrToObjectMap::find(entry); if (iter != se::NativePtrToObjectMap::end()) { - CCLOG("spTrackEntry %p was recycled!", entry); + CCLOGINFO("spTrackEntry %p was recycled!", entry); se::Object* seObj = iter->second; seObj->clearPrivateData(); seObj->unroot(); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/scripting/js-bindings/manual/jsb_xmlhttprequest.cpp index 5760528dfe..7612dd434f 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_xmlhttprequest.cpp @@ -142,7 +142,7 @@ XMLHttpRequest::XMLHttpRequest() _isDiscardedByReset = true; if (!_isLoadEnd) { - LOGD("XMLHttpRequest (%p) receives DIRECTOR::EVENT_RESET, retain self.\n", this); + SE_LOGD("XMLHttpRequest (%p) receives DIRECTOR::EVENT_RESET, retain self.\n", this); retain(); } }); @@ -330,7 +330,7 @@ void XMLHttpRequest::onResponse(HttpClient* client, HttpResponse* response) std::string tag = response->getHttpRequest()->getTag(); if (!tag.empty()) { - LOGD("XMLHttpRequest::onResponse, %s completed\n", tag.c_str()); + SE_LOGD("XMLHttpRequest::onResponse, %s completed\n", tag.c_str()); } long statusCode = response->getResponseCode(); @@ -343,7 +343,7 @@ void XMLHttpRequest::onResponse(HttpClient* client, HttpResponse* response) if (!response->isSucceed()) { std::string errorBuffer = response->getErrorBuffer(); - LOGD("Response failed, error buffer: %s\n", errorBuffer.c_str()); + SE_LOGD("Response failed, error buffer: %s\n", errorBuffer.c_str()); if (statusCode == 0 || statusCode == -1) { _errorFlag = true; @@ -511,7 +511,7 @@ se::Class* __jsb_XMLHttpRequest_class = nullptr; static bool XMLHttpRequest_finalize(se::State& s) { XMLHttpRequest* request = (XMLHttpRequest*)s.nativeThisObject(); - LOGD("XMLHttpRequest_finalize, %p ... \n", request); + SE_LOGD("XMLHttpRequest_finalize, %p ... \n", request); if (request->getReferenceCount() == 1) { request->autorelease(); @@ -561,13 +561,13 @@ static bool XMLHttpRequest_constructor(se::State& s) request->onloadend = [=](){ if (!request->isDiscardedByReset()) { -// LOGD("XMLHttpRequest (%p) onloadend ...\n", request); +// SE_LOGD("XMLHttpRequest (%p) onloadend ...\n", request); cb("onloadend"); thiz.toObject()->unroot(); } else { - LOGD("XMLHttpRequest (%p) onloadend after restart ScriptEngine.\n", request); + SE_LOGD("XMLHttpRequest (%p) onloadend after restart ScriptEngine.\n", request); request->release(); } }; @@ -643,13 +643,18 @@ static bool XMLHttpRequest_send(se::State& s) } else if (argc > 0) { - if (args[0].isString()) + const auto& arg0 = args[0]; + if (arg0.isNullOrUndefined()) { - request->sendString(args[0].toString()); + request->send(); } - else if (args[0].isObject()) + else if (arg0.isString()) { - se::Object* obj = args[0].toObject(); + request->sendString(arg0.toString()); + } + else if (arg0.isObject()) + { + se::Object* obj = arg0.toObject(); if (obj->isTypedArray()) { @@ -663,7 +668,8 @@ static bool XMLHttpRequest_send(se::State& s) } else { - SE_PRECONDITION2(false, false, "args[0] isn't a typed array"); + SE_REPORT_ERROR("Failed to get data of TypedArray!"); + return false; } } else if (obj->isArrayBuffer()) @@ -678,14 +684,27 @@ static bool XMLHttpRequest_send(se::State& s) } else { - SE_PRECONDITION2(false, false, "args[0] isn't an array buffer"); + SE_REPORT_ERROR("Failed to get data of ArrayBufferObject!"); + return false; } } else { - SE_PRECONDITION2(false, false, "args[0] isn't a typed array or an array buffer"); + SE_REPORT_ERROR("args[0] isn't a typed array or an array buffer"); + return false; } } + else + { + const char* typeName = "UNKNOWN"; + if (arg0.isBoolean()) + typeName = "boolean"; + else if (arg0.isNumber()) + typeName = "number"; + + SE_REPORT_ERROR("args[0] type: %s isn't supported!", typeName); + return false; + } } return true; @@ -746,7 +765,7 @@ SE_BIND_FUNC(XMLHttpRequest_getResonpseHeader) static bool XMLHttpRequest_overrideMimeType(se::State& s) { - LOGD("XMLHttpRequest.overrideMimeType isn't implemented on JSB!"); + SE_LOGD("XMLHttpRequest.overrideMimeType isn't implemented on JSB!"); return true; } SE_BIND_FUNC(XMLHttpRequest_overrideMimeType) @@ -864,7 +883,7 @@ static bool XMLHttpRequest_setTimeout(se::State& s) SE_PRECONDITION2(ok, false, "args[0] isn't a number"); if (timeoutInMilliseconds < 50) { - LOGE("The timeout value (%lu ms) is too small, please note that timeout unit is milliseconds!", timeoutInMilliseconds); + SE_LOGE("The timeout value (%lu ms) is too small, please note that timeout unit is milliseconds!", timeoutInMilliseconds); } cobj->setTimeout(timeoutInMilliseconds); return true; @@ -934,7 +953,7 @@ SE_BIND_PROP_SET(XMLHttpRequest_setResponseType) static bool XMLHttpRequest_getWithCredentials(se::State& s) { - LOGD("XMLHttpRequest.withCredentials isn't implemented on JSB!"); + SE_LOGD("XMLHttpRequest.withCredentials isn't implemented on JSB!"); return true; } SE_BIND_PROP_GET(XMLHttpRequest_getWithCredentials) diff --git a/native/cocos/scripting/js-bindings/proj.android/Android.mk b/native/cocos/scripting/js-bindings/proj.android/Android.mk index 34a3656252..7d923856f3 100644 --- a/native/cocos/scripting/js-bindings/proj.android/Android.mk +++ b/native/cocos/scripting/js-bindings/proj.android/Android.mk @@ -60,6 +60,10 @@ LOCAL_SRC_FILES := \ ../manual/jsb_dragonbones_manual.cpp \ ../manual/jsb_global.cpp \ ../manual/jsb_node.cpp \ + ../manual/jsb_opengl_functions.cpp \ + ../manual/jsb_opengl_manual.cpp \ + ../manual/jsb_opengl_node.cpp \ + ../manual/jsb_opengl_registration.cpp \ ../manual/jsb_socketio.cpp \ ../manual/jsb_spine_manual.cpp \ ../manual/jsb_websocket.cpp \ diff --git a/native/cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj/project.pbxproj b/native/cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj/project.pbxproj index a4297f8bcf..c036b5eb67 100644 --- a/native/cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj/project.pbxproj +++ b/native/cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj/project.pbxproj @@ -27,8 +27,6 @@ 1A210D951F456821006CCBAE /* MappingUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A210D921F456821006CCBAE /* MappingUtils.cpp */; }; 1A210D961F456821006CCBAE /* MappingUtils.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1A210D931F456821006CCBAE /* MappingUtils.hpp */; }; 1A210D971F456821006CCBAE /* MappingUtils.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1A210D931F456821006CCBAE /* MappingUtils.hpp */; }; - 1A210DE41F46C2DF006CCBAE /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A210DE21F46C2DF006CCBAE /* libjs_static.a */; }; - 1A210DE51F46C2DF006CCBAE /* libmozglue.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A210DE31F46C2DF006CCBAE /* libmozglue.a */; }; 1A5F228A1F0DDD6B0008BF09 /* jsb_dragonbones_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A5F22881F0DDD6B0008BF09 /* jsb_dragonbones_manual.cpp */; }; 1A5F228B1F0DDD6B0008BF09 /* jsb_dragonbones_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A5F22881F0DDD6B0008BF09 /* jsb_dragonbones_manual.cpp */; }; 1A5F228C1F0DDD6B0008BF09 /* jsb_dragonbones_manual.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1A5F22891F0DDD6B0008BF09 /* jsb_dragonbones_manual.hpp */; }; @@ -45,6 +43,8 @@ 1A6293F11F44128300A07B77 /* BaseJSAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6293EE1F44128300A07B77 /* BaseJSAction.cpp */; }; 1A6293F21F44128300A07B77 /* BaseJSAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A6293EF1F44128300A07B77 /* BaseJSAction.h */; }; 1A6293F31F44128300A07B77 /* BaseJSAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A6293EF1F44128300A07B77 /* BaseJSAction.h */; }; + 1A6821401FAC206300C18C60 /* jsb_platfrom_ios.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A68213F1FAC206300C18C60 /* jsb_platfrom_ios.m */; }; + 1A6821421FAC20B300C18C60 /* jsb_platform_ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A6821411FAC20B300C18C60 /* jsb_platform_ios.h */; }; 1A6B8FB31F3BF7E800BC83DC /* SHA1.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6B8FB11F3BF7E800BC83DC /* SHA1.cpp */; }; 1A6B8FB41F3BF7E800BC83DC /* SHA1.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A6B8FB21F3BF7E800BC83DC /* SHA1.h */; }; 1A7759C91F340FB10012A210 /* inspector_agent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1A7759C11F340FB10012A210 /* inspector_agent.cc */; }; @@ -87,6 +87,21 @@ 1AD4AE681F0F920700A823D8 /* jsb_websocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD4AE651F0F920700A823D8 /* jsb_websocket.cpp */; }; 1AD4AE691F0F920700A823D8 /* jsb_websocket.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD4AE661F0F920700A823D8 /* jsb_websocket.hpp */; }; 1AD4AE6A1F0F920700A823D8 /* jsb_websocket.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD4AE661F0F920700A823D8 /* jsb_websocket.hpp */; }; + 1AD53AD51FB1B2BF000F476C /* jsb_opengl_manual.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53ACF1FB1B2BE000F476C /* jsb_opengl_manual.hpp */; }; + 1AD53AD61FB1B2BF000F476C /* jsb_opengl_registration.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53AD01FB1B2BE000F476C /* jsb_opengl_registration.hpp */; }; + 1AD53AD71FB1B2BF000F476C /* jsb_opengl_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53AD11FB1B2BF000F476C /* jsb_opengl_registration.cpp */; }; + 1AD53AD81FB1B2BF000F476C /* jsb_opengl_node.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53AD21FB1B2BF000F476C /* jsb_opengl_node.cpp */; }; + 1AD53AD91FB1B2BF000F476C /* jsb_opengl_node.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53AD31FB1B2BF000F476C /* jsb_opengl_node.hpp */; }; + 1AD53ADC1FB1B32A000F476C /* jsb_opengl_functions.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53ADA1FB1B329000F476C /* jsb_opengl_functions.hpp */; }; + 1AD53ADD1FB1B32A000F476C /* jsb_opengl_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53ADB1FB1B32A000F476C /* jsb_opengl_functions.cpp */; }; + 1AD53ADE1FB2B1E0000F476C /* jsb_opengl_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53ACE1FB1B2BE000F476C /* jsb_opengl_manual.cpp */; }; + 1AD53ADF1FB2B1E1000F476C /* jsb_opengl_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53ACE1FB1B2BE000F476C /* jsb_opengl_manual.cpp */; }; + 1AD53AE01FB2B1E4000F476C /* jsb_opengl_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53ADB1FB1B32A000F476C /* jsb_opengl_functions.cpp */; }; + 1AD53AE11FB2B1E7000F476C /* jsb_opengl_functions.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53ADA1FB1B329000F476C /* jsb_opengl_functions.hpp */; }; + 1AD53AE21FB2B1EB000F476C /* jsb_opengl_node.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53AD21FB1B2BF000F476C /* jsb_opengl_node.cpp */; }; + 1AD53AE31FB2B1EB000F476C /* jsb_opengl_node.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53AD31FB1B2BF000F476C /* jsb_opengl_node.hpp */; }; + 1AD53AE41FB2B1EE000F476C /* jsb_opengl_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD53AD11FB1B2BF000F476C /* jsb_opengl_registration.cpp */; }; + 1AD53AE51FB2B1EE000F476C /* jsb_opengl_registration.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AD53AD01FB1B2BE000F476C /* jsb_opengl_registration.hpp */; }; 1AF82D431F2EE1C40002C5A0 /* HandleObject.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AF82D411F2EE1C20002C5A0 /* HandleObject.cpp */; }; 1AF82D441F2EE1C40002C5A0 /* HandleObject.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AF82D411F2EE1C20002C5A0 /* HandleObject.cpp */; }; 1AF82D451F2EE1C40002C5A0 /* HandleObject.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 1AF82D421F2EE1C20002C5A0 /* HandleObject.hpp */; }; @@ -301,6 +316,8 @@ 1A5F229B1F0E37B20008BF09 /* jsb_creator_physics_manual.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_creator_physics_manual.hpp; sourceTree = ""; }; 1A6293EE1F44128300A07B77 /* BaseJSAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BaseJSAction.cpp; sourceTree = ""; }; 1A6293EF1F44128300A07B77 /* BaseJSAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BaseJSAction.h; sourceTree = ""; }; + 1A68213F1FAC206300C18C60 /* jsb_platfrom_ios.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = jsb_platfrom_ios.m; sourceTree = ""; }; + 1A6821411FAC20B300C18C60 /* jsb_platform_ios.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = jsb_platform_ios.h; sourceTree = ""; }; 1A6B8FB11F3BF7E800BC83DC /* SHA1.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SHA1.cpp; sourceTree = ""; }; 1A6B8FB21F3BF7E800BC83DC /* SHA1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SHA1.h; sourceTree = ""; }; 1A7759C11F340FB10012A210 /* inspector_agent.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = inspector_agent.cc; sourceTree = ""; }; @@ -333,6 +350,14 @@ 1AB5E62A18D05BC80088DAA4 /* jsb_cocos2dx_ui_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_ui_auto.hpp; sourceTree = ""; }; 1AD4AE651F0F920700A823D8 /* jsb_websocket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_websocket.cpp; sourceTree = ""; }; 1AD4AE661F0F920700A823D8 /* jsb_websocket.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_websocket.hpp; sourceTree = ""; }; + 1AD53ACE1FB1B2BE000F476C /* jsb_opengl_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_opengl_manual.cpp; sourceTree = ""; }; + 1AD53ACF1FB1B2BE000F476C /* jsb_opengl_manual.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_opengl_manual.hpp; sourceTree = ""; }; + 1AD53AD01FB1B2BE000F476C /* jsb_opengl_registration.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_opengl_registration.hpp; sourceTree = ""; }; + 1AD53AD11FB1B2BF000F476C /* jsb_opengl_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_opengl_registration.cpp; sourceTree = ""; }; + 1AD53AD21FB1B2BF000F476C /* jsb_opengl_node.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_opengl_node.cpp; sourceTree = ""; }; + 1AD53AD31FB1B2BF000F476C /* jsb_opengl_node.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_opengl_node.hpp; sourceTree = ""; }; + 1AD53ADA1FB1B329000F476C /* jsb_opengl_functions.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_opengl_functions.hpp; sourceTree = ""; }; + 1AD53ADB1FB1B32A000F476C /* jsb_opengl_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_opengl_functions.cpp; sourceTree = ""; }; 1AF82D411F2EE1C20002C5A0 /* HandleObject.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HandleObject.cpp; sourceTree = ""; }; 1AF82D421F2EE1C20002C5A0 /* HandleObject.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = HandleObject.hpp; sourceTree = ""; }; 1AFD35FA1EF115100097DBB1 /* Base.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Base.h; sourceTree = ""; }; @@ -437,8 +462,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 1A210DE41F46C2DF006CCBAE /* libjs_static.a in Frameworks */, - 1A210DE51F46C2DF006CCBAE /* libmozglue.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -503,6 +526,14 @@ 1A119E4118BDF19200352BAA /* manual */ = { isa = PBXGroup; children = ( + 1AD53ADB1FB1B32A000F476C /* jsb_opengl_functions.cpp */, + 1AD53ADA1FB1B329000F476C /* jsb_opengl_functions.hpp */, + 1AD53ACE1FB1B2BE000F476C /* jsb_opengl_manual.cpp */, + 1AD53ACF1FB1B2BE000F476C /* jsb_opengl_manual.hpp */, + 1AD53AD21FB1B2BF000F476C /* jsb_opengl_node.cpp */, + 1AD53AD31FB1B2BF000F476C /* jsb_opengl_node.hpp */, + 1AD53AD11FB1B2BF000F476C /* jsb_opengl_registration.cpp */, + 1AD53AD01FB1B2BE000F476C /* jsb_opengl_registration.hpp */, 4D3EB2621F8F7358007DA644 /* jsb_creator_manual.cpp */, 4D3EB2631F8F7358007DA644 /* jsb_creator_manual.hpp */, 1A6293EE1F44128300A07B77 /* BaseJSAction.cpp */, @@ -539,6 +570,8 @@ 1AFD36C11EF116190097DBB1 /* ScriptingCore.h */, 1A9F0F9B1F30235C00A499E1 /* jsb_helper.cpp */, 1A9F0F9C1F30235C00A499E1 /* jsb_helper.hpp */, + 1A68213F1FAC206300C18C60 /* jsb_platfrom_ios.m */, + 1A6821411FAC20B300C18C60 /* jsb_platform_ios.h */, ); name = manual; path = ../manual; @@ -701,11 +734,13 @@ 1A5F228C1F0DDD6B0008BF09 /* jsb_dragonbones_manual.hpp in Headers */, 1AFD367A1EF115100097DBB1 /* SeApi.h in Headers */, 1AFD36661EF115100097DBB1 /* RefCounter.hpp in Headers */, + 1AD53AD61FB1B2BF000F476C /* jsb_opengl_registration.hpp in Headers */, 1AFD36561EF115100097DBB1 /* Object.hpp in Headers */, 1AFD36FC1EF116190097DBB1 /* jsb_xmlhttprequest.hpp in Headers */, 1AFD36921EF115100097DBB1 /* ObjectWrap.h in Headers */, 1AFD36741EF115100097DBB1 /* Object.hpp in Headers */, 1AFD36381EF115100097DBB1 /* Class.hpp in Headers */, + 1AD53AD51FB1B2BF000F476C /* jsb_opengl_manual.hpp in Headers */, 1A7759E81F3411050012A210 /* util-inl.h in Headers */, 1AFD36421EF115100097DBB1 /* ScriptEngine.hpp in Headers */, 1A119E9118BDF19200352BAA /* jsb_cocos2dx_extension_auto.hpp in Headers */, @@ -760,9 +795,11 @@ 1AFD368E1EF115100097DBB1 /* Object.hpp in Headers */, BAF638DE1B5F5DC900CDB43A /* jsb_cocos2dx_audioengine_auto.hpp in Headers */, 1AFD363E1EF115100097DBB1 /* Object.hpp in Headers */, + 1AD53AD91FB1B2BF000F476C /* jsb_opengl_node.hpp in Headers */, 1AFD36341EF115100097DBB1 /* Base.h in Headers */, 1AFD36621EF115100097DBB1 /* Object.hpp in Headers */, 1A119E8518BDF19200352BAA /* jsb_cocos2dx_auto.hpp in Headers */, + 1AD53ADC1FB1B32A000F476C /* jsb_opengl_functions.hpp in Headers */, 1AFD36821EF115100097DBB1 /* State.hpp in Headers */, 1A7759E31F3410A20012A210 /* http_parser.h in Headers */, ); @@ -789,6 +826,7 @@ 1AFD36D11EF116190097DBB1 /* jsb_cocos2dx_manual.hpp in Headers */, 1AFD36711EF115100097DBB1 /* HelperMacros.h in Headers */, 1AFD36611EF115100097DBB1 /* Utils.hpp in Headers */, + 1AD53AE31FB2B1EB000F476C /* jsb_opengl_node.hpp in Headers */, 1AFD36451EF115100097DBB1 /* SeApi.h in Headers */, 1AFD36531EF115100097DBB1 /* HelperMacros.h in Headers */, 1AFD363F1EF115100097DBB1 /* Object.hpp in Headers */, @@ -811,12 +849,14 @@ 1AFD36431EF115100097DBB1 /* ScriptEngine.hpp in Headers */, 1A5F229F1F0E37B20008BF09 /* jsb_creator_physics_manual.hpp in Headers */, 1AFD36FD1EF116190097DBB1 /* jsb_xmlhttprequest.hpp in Headers */, + 1AD53AE11FB2B1E7000F476C /* jsb_opengl_functions.hpp in Headers */, 1AFD365D1EF115100097DBB1 /* SeApi.h in Headers */, 1AFD364B1EF115100097DBB1 /* config.hpp in Headers */, 1AFD368B1EF115100097DBB1 /* HelperMacros.h in Headers */, 1A9F0FA01F30235C00A499E1 /* jsb_helper.hpp in Headers */, 1AF82D461F2EE1C40002C5A0 /* HandleObject.hpp in Headers */, 1AFD36511EF115100097DBB1 /* Class.hpp in Headers */, + 1A6821421FAC20B300C18C60 /* jsb_platform_ios.h in Headers */, 1AFD36491EF115100097DBB1 /* Utils.hpp in Headers */, 1A159D531F13216F00558E38 /* jsb_socketio.hpp in Headers */, 1AFD36691EF115100097DBB1 /* SeApi.h in Headers */, @@ -827,6 +867,7 @@ BAF638DF1B5F5DC900CDB43A /* jsb_cocos2dx_audioengine_auto.hpp in Headers */, 1AFD368F1EF115100097DBB1 /* Object.hpp in Headers */, 1A81B41F1F137BFE008C38F8 /* JavaScriptObjCBridge.h in Headers */, + 1AD53AE51FB2B1EE000F476C /* jsb_opengl_registration.hpp in Headers */, 1A6293F31F44128300A07B77 /* BaseJSAction.h in Headers */, 1A5F22991F0E306C0008BF09 /* jsb_box2d_manual.hpp in Headers */, 1AFD363B1EF115100097DBB1 /* HelperMacros.h in Headers */, @@ -935,6 +976,7 @@ 1A81B4201F137BFE008C38F8 /* JavaScriptObjCBridge.mm in Sources */, 1A119E8F18BDF19200352BAA /* jsb_cocos2dx_extension_auto.cpp in Sources */, 1AFD369E1EF115100097DBB1 /* Value.cpp in Sources */, + 1AD53ADD1FB1B32A000F476C /* jsb_opengl_functions.cpp in Sources */, 1AB5E62B18D05BC80088DAA4 /* jsb_cocos2dx_ui_auto.cpp in Sources */, 1A8FB50E1F99F04600BED3CF /* PlatformUtils.mm in Sources */, 1AFD36861EF115100097DBB1 /* Class.cpp in Sources */, @@ -956,6 +998,7 @@ 1A5F228A1F0DDD6B0008BF09 /* jsb_dragonbones_manual.cpp in Sources */, 4DFA4C101CBCC49000E3B736 /* jsb_creator_auto.cpp in Sources */, 1A7759F61F3421B90012A210 /* node.cc in Sources */, + 1AD53AD81FB1B2BF000F476C /* jsb_opengl_node.cpp in Sources */, 1AFD367C1EF115100097DBB1 /* Utils.cpp in Sources */, 1AD4AE671F0F920700A823D8 /* jsb_websocket.cpp in Sources */, 1AFD36E61EF116190097DBB1 /* jsb_node.cpp in Sources */, @@ -968,9 +1011,11 @@ 1AFD36FA1EF116190097DBB1 /* jsb_xmlhttprequest.cpp in Sources */, 4D672A891F8E0EE30073B9A4 /* jsb_creator_graphics_auto.cpp in Sources */, BA4F59841E28DCD3003F5096 /* jsb_cocos2dx_network_auto.cpp in Sources */, + 1AD53AD71FB1B2BF000F476C /* jsb_opengl_registration.cpp in Sources */, 1A7759DB1F34105B0012A210 /* node_debug_options.cc in Sources */, 1AFD36461EF115100097DBB1 /* Utils.cpp in Sources */, 1A210D941F456821006CCBAE /* MappingUtils.cpp in Sources */, + 1AD53ADE1FB2B1E0000F476C /* jsb_opengl_manual.cpp in Sources */, 1A5F22961F0E306C0008BF09 /* jsb_box2d_manual.cpp in Sources */, 1A7759F01F341D6E0012A210 /* env.cc in Sources */, 1A7759D51F340FB10012A210 /* inspector_socket.cc in Sources */, @@ -981,6 +1026,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 1AD53ADF1FB2B1E1000F476C /* jsb_opengl_manual.cpp in Sources */, 1AFD36551EF115100097DBB1 /* Object.cpp in Sources */, 1A159D511F13216F00558E38 /* jsb_socketio.cpp in Sources */, 1AFD36411EF115100097DBB1 /* ScriptEngine.cpp in Sources */, @@ -992,8 +1038,10 @@ 1AFD36371EF115100097DBB1 /* Class.cpp in Sources */, 1AFD36811EF115100097DBB1 /* State.cpp in Sources */, 1AFD36FB1EF116190097DBB1 /* jsb_xmlhttprequest.cpp in Sources */, + 1A6821401FAC206300C18C60 /* jsb_platfrom_ios.m in Sources */, 1AFD36471EF115100097DBB1 /* Utils.cpp in Sources */, 4D3EB2671F8F779E007DA644 /* jsb_creator_manual.cpp in Sources */, + 1AD53AE21FB2B1EB000F476C /* jsb_opengl_node.cpp in Sources */, 4D558C8E1F9700770083B43B /* jsb_creator_graphics_auto.cpp in Sources */, 1A5F229D1F0E37B20008BF09 /* jsb_creator_physics_manual.cpp in Sources */, FA6F1BB41D815C2C007DD223 /* jsb_cocos2dx_dragonbones_auto.cpp in Sources */, @@ -1021,6 +1069,7 @@ 1AFD36871EF115100097DBB1 /* Class.cpp in Sources */, 1A6293F11F44128300A07B77 /* BaseJSAction.cpp in Sources */, 1AFD369F1EF115100097DBB1 /* Value.cpp in Sources */, + 1AD53AE01FB2B1E4000F476C /* jsb_opengl_functions.cpp in Sources */, 1AF82D441F2EE1C40002C5A0 /* HandleObject.cpp in Sources */, 1AFD365F1EF115100097DBB1 /* Utils.cpp in Sources */, 1AFD36F31EF116190097DBB1 /* jsb_spine_manual.cpp in Sources */, @@ -1030,6 +1079,7 @@ 1AFD36591EF115100097DBB1 /* ScriptEngine.cpp in Sources */, 1AFD369B1EF115100097DBB1 /* Utils.cpp in Sources */, 1AFD36FF1EF116190097DBB1 /* ScriptingCore.cpp in Sources */, + 1AD53AE41FB2B1EE000F476C /* jsb_opengl_registration.cpp in Sources */, 1A8FB50F1F99F04600BED3CF /* PlatformUtils.mm in Sources */, 1AFD36DB1EF116190097DBB1 /* jsb_global.cpp in Sources */, 1A9F0F9E1F30235C00A499E1 /* jsb_helper.cpp in Sources */, diff --git a/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj b/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj index 2995470b26..2fc4d468df 100644 --- a/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj +++ b/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj @@ -74,6 +74,10 @@ + + + + @@ -138,6 +142,10 @@ + + + + diff --git a/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj.filters b/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj.filters index fc5bfe2aa8..ececd64951 100644 --- a/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj.filters +++ b/native/cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj.filters @@ -176,6 +176,18 @@ manual + + manual + + + manual + + + manual + + + manual + @@ -364,5 +376,17 @@ manual + + manual + + + manual + + + manual + + + manual + \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index b29056d28e..df4ddb3347 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -1126,23 +1126,3 @@ cc.GLProgram.prototype.setUniformLocationWithMatrix4fv = function(){ tempArray.push(4); this.setUniformLocationWithMatrixfvUnion.apply(this, tempArray); }; - -// -// LocalStorage -// -sys.localStorage._setItem = sys.localStorage.setItem; -sys.localStorage.setItem = function(itemKey,itemValue) { - if (typeof itemKey === 'string') { - if(itemValue !== undefined && itemValue !== null) - { - if (typeof itemValue !== 'string') { - cc.log("sys.localStorage.setItem Warning: itemValue[" + itemValue + "] is not string!"); - itemValue = '' + itemValue; - } - sys.localStorage._setItem(itemKey, itemValue); - } - } - else - cc.log("sys.localStorage.setItem Warning: itemKey[" + itemKey + "] is not string!"); -} - diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js b/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js index 234be796e1..7e15691d6b 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js @@ -20,6 +20,13 @@ if (platform === sys.ANDROID) { var cls_CAAgentWrapper = "org/cocos2dx/lib/CAAgentWrapper"; cocosAnalytics.init = function(info) { + + if (!info.channel) { + var anysdkChannelID = jsb.reflection.callStaticMethod(cls_CAAgentWrapper, "getChannelID", "()Ljava/lang/String;"); + console.log("Found AnySDK channel ID: " + anysdkChannelID); + info.channel = anysdkChannelID; + } + if (info && info.appID && info.appSecret && info.channel) { jsb.reflection.callStaticMethod(cls_CAAgentWrapper, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", @@ -300,8 +307,16 @@ if (platform === sys.ANDROID) { var cls_CAPayment = "CAPeiment"; var cls_CATask = "CATask"; var cls_CAVirtual = "CAVirtual"; + var cls_JSB_PlatformIOS = "JSB_PlatformIOS"; cocosAnalytics.init = function(info) { + + if (!info.channel) { + var anysdkChannelID = jsb.reflection.callStaticMethod(cls_JSB_PlatformIOS, "getChannelID"); + console.log("Found AnySDK channel ID: " + anysdkChannelID); + info.channel = anysdkChannelID; + } + if (info && info.appID && info.appSecret && info.channel) { jsb.reflection.callStaticMethod(cls_CAAgent, "init:appID:appSecret:", @@ -319,10 +334,6 @@ if (platform === sys.ANDROID) { cocosAnalytics.CAAccount = { - testbool: function(v, boolean, integer, longtype, shorttype, uinttype, ulongtype, ushorttype, floattype, doubletype, chartype, uchartype) { - return jsb.reflection.callStaticMethod(cls_CAAccount, "testbool:boolean:integer:longtype:shorttype:uinttype:ulongtype:ushorttype:floattype:doubletype:chartype:uchartype:", v, boolean, integer, longtype, shorttype, uinttype, ulongtype, ushorttype, floattype, doubletype, chartype, uchartype); - }, - loginStart: function() { jsb.reflection.callStaticMethod(cls_CAAccount, "loginStart"); }, @@ -576,7 +587,123 @@ if (platform === sys.ANDROID) { } }; } else { + // Empty implementation for other platforms + cocosAnalytics = {}; + cocosAnalytics.init = function(info) { + console.log("Cocos Analytics module isn't available on this platform!"); + }; + + cocosAnalytics.enableDebug = function(enabled) { + }; + + cocosAnalytics.CAAccount = { + loginStart: function() { + }, + + loginSuccess: function(info) { + }, + + loginFailed: function() { + }, + + logout: function(info) { + }, + + setAccountType: function(type) { + }, + + setAge: function(age) { + }, + + setGender: function(gender) { + }, + + setLevel: function(level) { + }, + + createRole: function(info) { + } + }; + + cocosAnalytics.CAEvent = { + onEvent: function(info) { + }, + + onEventStart: function(info) { + }, + + onEventEnd: function(info) { + } + }; + + cocosAnalytics.CAPayment = { + payBegin: function(info) { + }, + + paySuccess: function(info) { + }, + + payFailed: function(info) { + }, + + payCanceled: function(info) { + } + }; + + cocosAnalytics.CALevels = { + begin: function(info) { + }, + + complete: function(info) { + }, + + failed: function(info) { + } + }; + + cocosAnalytics.CATaskType = { + GuideLine: 1, + MainLine: 2, + BranchLine: 3, + Daily: 4, + Activity: 5, + Other: 100 + }; + + cocosAnalytics.CATask = { + + begin: function(info) { + }, + + complete: function(info) { + }, + + failed: function(info) { + } + }; + + cocosAnalytics.CAItem = { + buy: function(info) { + }, + + get: function(info) { + }, + + consume: function(info) { + } + }; + + cocosAnalytics.CAVirtual = { + setVirtualNum: function(info) { + }, + + get: function(info) { + }, + + consume: function(info) { + } + }; } })(); diff --git a/native/cocos/scripting/js-bindings/script/jsb_prepare.js b/native/cocos/scripting/js-bindings/script/jsb_prepare.js index 3886f3c1f3..59704edf4a 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_prepare.js +++ b/native/cocos/scripting/js-bindings/script/jsb_prepare.js @@ -26,6 +26,7 @@ var window = window || this; // Hack JavaScriptCore begin + if (window.scriptEngineType == "JavaScriptCore") { window.__jsc_createArrayBufferObject = function(arr) { var len = arr.length; @@ -37,10 +38,6 @@ if (window.scriptEngineType == "JavaScriptCore") { return buffer; }; - window.__jsc_createUint8TypedArray = function(arr) { - return new Uint8Array(arr); - }; - window.__jsc_getArrayBufferData = function(arrBuf) { var typedArr = new Uint8Array(arrBuf); var len = typedArr.length; @@ -51,38 +48,25 @@ if (window.scriptEngineType == "JavaScriptCore") { return arr; }; - window.__jsc_getUint8ArrayData = function(typedArr) { - var len = typedArr.length; - var arr = new Array(len); - for (var i = 0; i < len; ++i) { - arr[i] = typedArr[i]; + window.__jsc_getTypedArrayData = function(typedArr) { + var length = typedArr.byteLength; + var offset = typedArr.byteOffset; + var buf = typedArr.buffer; + var uint8Arr = new Uint8Array(buf); + var retArr = new Array(length); + var arrIndex = 0; + var bufIndex = offset; + var bufEnd = offset + length; + for (; bufIndex < bufEnd; ++bufIndex, ++arrIndex) { + retArr[arrIndex] = uint8Arr[bufIndex]; } - return arr; + return retArr; }; - window.__jsc_isArrayBuffer = function(arrBuf) { - if (!arrBuf) - return false; - - return arrBuf instanceof ArrayBuffer; - }; - - window.__jsc_isTypedArray = function(typedArr) { - if (!typedArr) - return false; - - var typedArrayTypes = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; - - for (var i = 0, len = typedArrayTypes.length; i < len; ++i) { - if (typedArr instanceof typedArrayTypes[i]) { - return true; - } - } - - return false; - }; + window.__jscTypedArrayConstructor = Object.getPrototypeOf(Uint16Array.prototype).constructor; } + // Hack JavaScriptCore end var cc = cc || {}; @@ -244,35 +228,41 @@ cc.Class.extend = function (prop) { return Class; }; +jsb.__obj_ref_id = 0; + jsb.registerNativeRef = function (owner, target) { if (owner && target && owner !== target) { + var targetID = target.__jsb_ref_id; + if (targetID === undefined) + targetID = target.__jsb_ref_id = jsb.__obj_ref_id++; + var refs = owner.__nativeRefs; if (!refs) { - refs = owner.__nativeRefs = []; - } - var index = refs.indexOf(target); - if (index === -1) { - owner.__nativeRefs.push(target); + refs = owner.__nativeRefs = {}; } + + refs[targetID] = target; } }; jsb.unregisterNativeRef = function (owner, target) { if (owner && target && owner !== target) { + var targetID = target.__jsb_ref_id; + if (targetID === undefined) + return; + var refs = owner.__nativeRefs; if (!refs) { return; } - var index = refs.indexOf(target); - if (index !== -1) { - owner.__nativeRefs.splice(index, 1); - } + + delete refs[targetID]; } }; jsb.unregisterAllNativeRefs = function (owner) { if (!owner) return; - owner.__nativeRefs.length = 0; + delete owner.__nativeRefs; }; jsb.unregisterChildRefsForNode = function (node, recursive) { diff --git a/native/cocos/ui/UIEditBox/Mac/CCUIPasswordTextField.m b/native/cocos/ui/UIEditBox/Mac/CCUIPasswordTextField.m index 8d04eb3d73..3711c21d80 100644 --- a/native/cocos/ui/UIEditBox/Mac/CCUIPasswordTextField.m +++ b/native/cocos/ui/UIEditBox/Mac/CCUIPasswordTextField.m @@ -111,14 +111,14 @@ -(id) initWithFrame:(NSRect)frameRect { - if ([super initWithFrame:frameRect]) { + self = [super initWithFrame:frameRect]; + if (self) { NSFont* font = [NSFont systemFontOfSize:frameRect.size.height * 3 /2]; self.placeholderAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, [NSColor grayColor], NSForegroundColorAttributeName, nil]; [self setLineBreakMode:NSLineBreakByTruncatingTail]; - } return self; diff --git a/native/cocos/ui/UIEditBox/Mac/CCUISingleLineTextField.m b/native/cocos/ui/UIEditBox/Mac/CCUISingleLineTextField.m index d9afe623c4..cdd49a1e9c 100644 --- a/native/cocos/ui/UIEditBox/Mac/CCUISingleLineTextField.m +++ b/native/cocos/ui/UIEditBox/Mac/CCUISingleLineTextField.m @@ -109,7 +109,8 @@ -(id) initWithFrame:(NSRect)frameRect { - if ([super initWithFrame:frameRect]) { + self = [super initWithFrame:frameRect]; + if (self) { [self setLineBreakMode:NSLineBreakByTruncatingTail]; } @@ -122,7 +123,8 @@ } - (void)dealloc -{ +{ + self.placeholderAttributes = nil; [super dealloc]; } diff --git a/native/cocos/ui/UIScale9Sprite.cpp b/native/cocos/ui/UIScale9Sprite.cpp index 343eb27851..1e276d8c14 100644 --- a/native/cocos/ui/UIScale9Sprite.cpp +++ b/native/cocos/ui/UIScale9Sprite.cpp @@ -670,12 +670,17 @@ namespace ui { void Scale9Sprite::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) { if (_scale9Image && _scale9Enabled) { -#if CC_USE_CULLING - // Don't do calculate the culling if the transform was not updated - _insideBounds = (flags & FLAGS_TRANSFORM_DIRTY) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds; + if (_director->isCullingEnabled()) { + // Don't do calculate the culling if the transform was not updated + if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) { + _insideBounds = renderer->checkVisibility(transform, _contentSize); + } + } + else { + _insideBounds = true; + } if(_insideBounds) -#endif { auto texture = _scale9Image->getTexture(); auto programState = _scale9Image->getGLProgramState(); diff --git a/native/download-deps.py b/native/download-deps.py index 7332648dea..c8aa6b1e6b 100755 --- a/native/download-deps.py +++ b/native/download-deps.py @@ -215,7 +215,7 @@ class CocosZipInstaller(object): print("==> Extraction done!") def ask_to_delete_downloaded_zip_file(self): - ret = self.get_input_value("==> Would you like to save '%s'? So you don't have to download it later. [Yes/no]: " % self._filename) + ret = self.get_input_value("==> Would you like to save '%s'? So you don't have to download it later. [yes/no]: " % self._filename) ret = ret.strip() if ret != 'yes' and ret != 'y' and ret != 'no' and ret != 'n': print("==> Saving the dependency libraries by default") diff --git a/native/extensions/Android.mk b/native/extensions/Android.mk index 8749c4ae6a..04f45adf92 100644 --- a/native/extensions/Android.mk +++ b/native/extensions/Android.mk @@ -15,7 +15,7 @@ assets-manager/AssetsManagerEx.cpp \ assets-manager/CCEventAssetsManagerEx.cpp \ assets-manager/CCEventListenerAssetsManagerEx.cpp \ -LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static +LOCAL_STATIC_LIBRARIES := cis LOCAL_STATIC_LIBRARIES += cocos_chipmunk_static LOCAL_CXXFLAGS += -fexceptions diff --git a/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp b/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp index f0a6ba28f1..6a1adae474 100644 --- a/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp +++ b/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp @@ -28,8 +28,10 @@ #ifdef ANYSDK_FOR_APPSTORE #define jsb_funcName_getIAPPlugin "getYAPPlugin" +#define jsb_funcName_payForProduct "yapForProduct" #else #define jsb_funcName_getIAPPlugin "getIAPPlugin" +#define jsb_funcName_payForProduct "payForProduct" #define ProtocolYAP ProtocolIAP #define getYAPPlugin getIAPPlugin #define YapResultCode PayResultCode @@ -312,7 +314,7 @@ bool js_cocos2dx_PluginParam_create(se::State& s) return false; } - se::HandleObject jsret(se::Object::createObjectWithClass(__jsb_anysdk_framework_PluginParam_class)); + se::Object* jsret = se::Object::createObjectWithClass(__jsb_anysdk_framework_PluginParam_class); jsret->setPrivateData(ret); s.rval().setObject(jsret); @@ -430,7 +432,8 @@ se::Object* __jsb_anysdk_framework_ProtocolShare_proto = nullptr; static bool js_anysdk_framework_ProtocolShare_finalize(se::State& s) { - CCLOGINFO("jsbindings: finalizing JS object %p (ProtocolShare)", obj); + ProtocolShare* cobj = (ProtocolShare*)s.nativeThisObject(); + CCLOGINFO("jsbindings: finalizing JS object %p (ProtocolShare)", cobj); return true; } SE_BIND_FINALIZE_FUNC(js_anysdk_framework_ProtocolShare_finalize) @@ -1586,7 +1589,7 @@ bool register_all_anysdk_manual(se::Object* obj) //ProtocolYAP __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction("setResultListener", _SE(jsb_anysdk_framework_ProtocolYAP_setResultListener)); __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction("removeListener", _SE(jsb_anysdk_framework_ProtocolYAP_removeListener)); - __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction("yapForProduct", _SE(jsb_anysdk_framework_ProtocolYAP_yapForProduct)); + __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction(jsb_funcName_payForProduct, _SE(jsb_anysdk_framework_ProtocolYAP_yapForProduct)); //ProtocolSocial __jsb_anysdk_framework_ProtocolSocial_proto->defineFunction("setListener", _SE(jsb_anysdk_framework_ProtocolSocial_setListener)); diff --git a/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp b/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp index ad8158945a..3efffd2b51 100644 --- a/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp +++ b/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp @@ -28,8 +28,10 @@ #ifdef ANYSDK_FOR_APPSTORE #define jsb_funcName_getIAPPlugin "getYAPPlugin" +#define jsb_funcName_payForProduct "yapForProduct" #else #define jsb_funcName_getIAPPlugin "getIAPPlugin" +#define jsb_funcName_payForProduct "payForProduct" #define ProtocolYAP ProtocolIAP #define getYAPPlugin getIAPPlugin #define YapResultCode PayResultCode @@ -312,7 +314,7 @@ bool js_cocos2dx_PluginParam_create(se::State& s) return false; } - se::HandleObject jsret(se::Object::createObjectWithClass(__jsb_anysdk_framework_PluginParam_class)); + se::Object* jsret = se::Object::createObjectWithClass(__jsb_anysdk_framework_PluginParam_class); jsret->setPrivateData(ret); s.rval().setObject(jsret); @@ -430,7 +432,8 @@ se::Object* __jsb_anysdk_framework_ProtocolShare_proto = nullptr; static bool js_anysdk_framework_ProtocolShare_finalize(se::State& s) { - CCLOGINFO("jsbindings: finalizing JS object %p (ProtocolShare)", obj); + ProtocolShare* cobj = (ProtocolShare*)s.nativeThisObject(); + CCLOGINFO("jsbindings: finalizing JS object %p (ProtocolShare)", cobj); return true; } SE_BIND_FINALIZE_FUNC(js_anysdk_framework_ProtocolShare_finalize) @@ -1586,7 +1589,7 @@ bool register_all_anysdk_manual(se::Object* obj) //ProtocolYAP __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction("setResultListener", _SE(jsb_anysdk_framework_ProtocolYAP_setResultListener)); __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction("removeListener", _SE(jsb_anysdk_framework_ProtocolYAP_removeListener)); - __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction("yapForProduct", _SE(jsb_anysdk_framework_ProtocolYAP_yapForProduct)); + __jsb_anysdk_framework_ProtocolYAP_proto->defineFunction(jsb_funcName_payForProduct, _SE(jsb_anysdk_framework_ProtocolYAP_yapForProduct)); //ProtocolSocial __jsb_anysdk_framework_ProtocolSocial_proto->defineFunction("setListener", _SE(jsb_anysdk_framework_ProtocolSocial_setListener)); diff --git a/native/external/config.json b/native/external/config.json index 634373d91f..d61f771a86 100644 --- a/native/external/config.json +++ b/native/external/config.json @@ -1,5 +1,5 @@ { - "version": "v3-deps-49", + "version": "v3-deps-51", "zip_file_size": "114318593", "repo_name": "cocos2d-x-lite-external", "repo_parent": "https://github.com/cocos-creator/" diff --git a/native/gulpfile.js b/native/gulpfile.js index 74be6e5ffd..5b495cbf96 100644 --- a/native/gulpfile.js +++ b/native/gulpfile.js @@ -13,9 +13,19 @@ gulp.task('make-cocos2d-x', gulpSequence('gen-cocos2d-x', 'upload-cocos2d-x')); gulp.task('make-prebuilt', gulpSequence('gen-libs', 'collect-prebuilt-mk', 'archive-prebuilt-mk', 'archive-prebuilt', 'upload-prebuilt', 'upload-prebuilt-mk')); gulp.task('make-simulator', gulpSequence('gen-simulator', 'update-simulator-config', 'update-simulator-dll', 'archive-simulator', 'upload-simulator')); +gulp.task('publish-source', gulpSequence('init', 'make-cocos2d-x')); +gulp.task('publish-prebuilt', gulpSequence('init', 'make-simulator', 'make-prebuilt')); + +if (process.platform === 'darwin') { + gulp.task('publish', gulpSequence('init', 'make-cocos2d-x', 'make-simulator', 'make-prebuilt')); +} +else { + gulp.task('publish', gulpSequence('publish-prebuilt')); +} + function execSync(cmd, workPath) { var execOptions = { - cwd: workPath, + cwd: workPath || '.', stdio: 'inherit' }; ExecSync(cmd, execOptions); @@ -24,40 +34,42 @@ function execSync(cmd, workPath) { function downloadSimulatorDLL(callback) { var Download = require('download'); var destPath = Path.join('simulator', 'win32'); - new Download({ - mode: '755', - extract: true, - strip: 0 - }) - .get('http://192.168.52.109/TestBuilds/Fireball/simulator/dlls/dll.zip') - .dest(destPath) - .run(function(err, files) { - if (err) throw err; - else callback(); - }); + Download('http://192.168.52.109/TestBuilds/Fireball/simulator/dlls/dll.zip', destPath, { + mode: '755', + extract: true, + strip: 0 + }).then(function(res) { + callback(); + }).catch(callback); } function upload2Ftp(localPath, ftpPath, config, cb) { var ftpClient = new Ftp(); ftpClient.on('error', function(err) { if (err) { - cb(err); + if (cb) { + cb(err); + } + else { + console.warn('Upload errored after destroy: ', ftpPath); + } } }); ftpClient.on('ready', function() { var dirName = Path.dirname(ftpPath); ftpClient.mkdir(dirName, true, function(err) { if (err) { - cb(err); + return cb(err); } - }); - - ftpClient.put(localPath, ftpPath, function(err) { - if (err) { - cb(err); - } - ftpClient.end(); - cb(); + ftpClient.put(localPath, ftpPath, function(err) { + if (err) { + return cb(err); + } + ftpClient.end(); + ftpClient.destroy(); + cb(); + cb = null; + }); }); }); @@ -76,12 +88,7 @@ function uploadZipFile(zipFileName, path, cb) { host: '192.168.52.109', user: process.env.ftpUser, password: process.env.ftpPass - }, function(err) { - if (err) { - throw err; - } - cb(); - }); + }, cb); } function getCurrentBranch() { @@ -92,8 +99,9 @@ function getCurrentBranch() { } gulp.task('init', function(cb) { - execSync('python download-deps.py', '.'); - execSync('git submodule update --init', '.'); + execSync('python download-deps.py --remove-download no'); + execSync('git submodule update --init'); + execSync('python download-bin.py --remove-download no', './tools/cocos2d-console'); cb(); }); @@ -105,8 +113,22 @@ gulp.task('gen-libs', function(cb) { } else { cocosConsoleBin = Path.join(cocosConsoleRoot, 'cocos.bat'); } - execSync(cocosConsoleBin + ' gen-libs -m release --vs 2015 --android-studio --app-abi armeabi:arm64-v8a:armeabi-v7a:x86', '.'); - cb(); + var child = spawn(cocosConsoleBin, + 'gen-libs -m release --vs 2015 --android-studio --app-abi armeabi:arm64-v8a:armeabi-v7a:x86'.split(' '), + { + stdio: 'inherit' + } + ); + child.on('close', (code) => { + if (code !== 0) { + cb('Generate libs failed'); + return; + } + cb(); + }); + child.on('error', function() { + cb('Generate libs failed'); + }); }); gulp.task('gen-cocos2d-x', function(cb) { @@ -119,11 +141,15 @@ gulp.task('gen-simulator', function(cb) { var cocosConsoleBin; if (process.platform === 'darwin') { cocosConsoleBin = Path.join(cocosConsoleRoot, 'cocos'); - // copy mac xcode project with signing info - if (fs.existsSync('simulator.xcodeproj')) { + if (fs.existsSync('./simulator.xcodeproj')) { + // copy mac xcode project with signing info fs.copySync('./simulator.xcodeproj', './tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj'); } - } else { + else { + return cb('Failed to generate simulator, xcode project not signed. Run "gulp sign-simulator" please.'); + } + } + else { cocosConsoleBin = Path.join(cocosConsoleRoot, 'cocos.bat'); } var args; @@ -142,21 +168,28 @@ gulp.task('gen-simulator', function(cb) { }); child.on('close', (code) => { if (code !== 0) { - console.error('Generate simulator failed'); + cb('Generate simulator failed'); + return; + } + if (process.platform === 'darwin') { + //reset project file to hide code sign information. + execSync('git checkout -- ./tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj'); } - //reset project file to hide code sign information. - ExecSync('git checkout -- ./tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj'); cb(); - return; }); child.on('error', function() { - console.error('Generate simulator failed'); - cb(); + cb('Generate simulator failed'); }); } catch (err) { - console.error(err); - cb(); - return; + cb(err); + } +}); + +gulp.task('sign-simulator', function () { + if (process.platform === 'darwin') { + execSync('git checkout -- ./tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj'); + execSync('/Applications/Xcode.app/Contents/MacOS/Xcode ./tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj'); + fs.copySync('./tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj', './simulator.xcodeproj'); } }); @@ -242,4 +275,4 @@ gulp.task('upload-cocos2d-x', function(cb) { gulp.task('upload-simulator', function(cb) { var zipFileName = 'simulator_' + process.platform + '.zip'; uploadZipFile(zipFileName, '.', cb); -}); \ No newline at end of file +}); diff --git a/native/package.json b/native/package.json index 69b041d9c4..043192d344 100644 --- a/native/package.json +++ b/native/package.json @@ -7,7 +7,7 @@ "update-version": "node utils/update-version.js" }, "devDependencies": { - "download": "4.4.3", + "download": "^6.2.5", "fs-extra": "0.30.0", "ftp": "0.3.10", "gulp": "3.9.1", diff --git a/native/templates/cocos2dx_files.json b/native/templates/cocos2dx_files.json index b56b5760ec..483069f34a 100644 --- a/native/templates/cocos2dx_files.json +++ b/native/templates/cocos2dx_files.json @@ -628,6 +628,7 @@ "cocos/platform/android/java/libs/libcocosanalytics.jar", "cocos/platform/android/java/proguard-project.txt", "cocos/platform/android/java/project.properties", + "cocos/platform/android/java/src/org/cocos2dx/lib/CAAgentWrapper.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAudioFocusManager.java", @@ -1245,7 +1246,6 @@ "external/android/arm64-v8a/include/tiff/tiffconf.h", "external/android/arm64-v8a/include/tiff/tiffio.h", "external/android/arm64-v8a/include/tiff/tiffvers.h", - "external/android/arm64-v8a/include/uv/android-ifaddrs.h", "external/android/arm64-v8a/include/uv/pthread-barrier.h", "external/android/arm64-v8a/include/uv/stdint-msvc2008.h", "external/android/arm64-v8a/include/uv/tree.h", @@ -1651,7 +1651,6 @@ "external/android/armeabi-v7a/include/tiff/tiffconf.h", "external/android/armeabi-v7a/include/tiff/tiffio.h", "external/android/armeabi-v7a/include/tiff/tiffvers.h", - "external/android/armeabi-v7a/include/uv/android-ifaddrs.h", "external/android/armeabi-v7a/include/uv/pthread-barrier.h", "external/android/armeabi-v7a/include/uv/stdint-msvc2008.h", "external/android/armeabi-v7a/include/uv/tree.h", @@ -2057,7 +2056,6 @@ "external/android/armeabi/include/tiff/tiffconf.h", "external/android/armeabi/include/tiff/tiffio.h", "external/android/armeabi/include/tiff/tiffvers.h", - "external/android/armeabi/include/uv/android-ifaddrs.h", "external/android/armeabi/include/uv/pthread-barrier.h", "external/android/armeabi/include/uv/stdint-msvc2008.h", "external/android/armeabi/include/uv/tree.h", @@ -2463,7 +2461,6 @@ "external/android/x86/include/tiff/tiffconf.h", "external/android/x86/include/tiff/tiffio.h", "external/android/x86/include/tiff/tiffvers.h", - "external/android/x86/include/uv/android-ifaddrs.h", "external/android/x86/include/uv/pthread-barrier.h", "external/android/x86/include/uv/stdint-msvc2008.h", "external/android/x86/include/uv/tree.h", @@ -4464,6 +4461,7 @@ "tools/simulator/frameworks/runtime-src/Classes/ide-support/lang", "tools/simulator/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml", "tools/simulator/frameworks/runtime-src/proj.android-studio/app/build.gradle", + "tools/simulator/frameworks/runtime-src/proj.android-studio/app/debug.keystore", "tools/simulator/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk", "tools/simulator/frameworks/runtime-src/proj.android-studio/app/jni/Application.mk", "tools/simulator/frameworks/runtime-src/proj.android-studio/app/jni/hellojavascript/main.cpp", @@ -4742,6 +4740,7 @@ "cocos/scripting/js-bindings/auto/jsb_creator_physics_auto.cpp", "cocos/scripting/js-bindings/auto/jsb_creator_physics_auto.hpp", "cocos/scripting/js-bindings/docs/JSB2.0-Architecture.png", + "cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md", "cocos/scripting/js-bindings/docs/JSB2.0-learning-zh.md", "cocos/scripting/js-bindings/docs/jsc-breakpoint.png", "cocos/scripting/js-bindings/docs/jsc-entitlements-check.png", @@ -4872,6 +4871,16 @@ "cocos/scripting/js-bindings/manual/jsb_module_register.hpp", "cocos/scripting/js-bindings/manual/jsb_node.cpp", "cocos/scripting/js-bindings/manual/jsb_node.hpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_functions.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_functions.hpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_manual.hpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_node.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_node.hpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_registration.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_registration.hpp", + "cocos/scripting/js-bindings/manual/jsb_platform_ios.h", + "cocos/scripting/js-bindings/manual/jsb_platfrom_ios.m", "cocos/scripting/js-bindings/manual/jsb_socketio.cpp", "cocos/scripting/js-bindings/manual/jsb_socketio.hpp", "cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp", diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml index e05719fcf3..3bf8b065b2 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml @@ -5,6 +5,17 @@ + + + + + + + + + + + - - - - - - - - - - - + diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle index 0d0dbe18ae..fc5b4f3112 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -4,7 +4,7 @@ apply plugin: 'com.android.application' android { compileSdkVersion 22 - buildToolsVersion "25.0.0" + buildToolsVersion '26.0.2' defaultConfig { applicationId "org.cocos2dx.hellojavascript" @@ -31,8 +31,6 @@ android { arguments 'NDK_MODULE_PATH=' + module_paths.join(':') } - arguments 'NDK_OUT=./obj' - arguments '-j' + Runtime.runtime.availableProcessors() abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String}) } @@ -121,28 +119,6 @@ android.applicationVariants.all { variant -> } } -def copySo() { - copy { - from('./obj/local') { - include '**/*.so' - exclude '**/objs*' - } - into './libs' - } -} - -afterEvaluate { - tasks.findByName('externalNativeBuildDebug')?.doLast { - println ('Copying debug .so') - copySo() - } - - tasks.findByName('externalNativeBuildRelease')?.doLast { - println ('Copying release .so') - copySo() - } -} - dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':libcocos2dx') diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/build.gradle b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/build.gradle index c6f2f5009e..2b56747de5 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/build.gradle +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/build.gradle @@ -1,11 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.0' + classpath 'com.android.tools.build:gradle:3.0.0' + // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -14,6 +17,11 @@ buildscript { allprojects { repositories { + google() jcenter() } } + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties index b043b8ebca..1c6b75e38f 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Jul 31 20:40:49 CST 2015 +#Fri Oct 27 10:18:28 CST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android/AndroidManifest.xml b/native/templates/js-template-binary/frameworks/runtime-src/proj.android/AndroidManifest.xml index c4d1dfb142..d7ff3bdc58 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android/AndroidManifest.xml +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -8,6 +8,17 @@ + + + + + + + + + + + @@ -32,15 +43,5 @@ android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true"/> - - - - - - - - - - - + diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index e009474331..da39d06dcb 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -511,7 +511,7 @@ MACOSX_DEPLOYMENT_TARGET = 10.8; OTHER_LDFLAGS = ""; SDKROOT = macosx; - USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/mac /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/glfw3 /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources"; + USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/mac /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/glfw3 /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources"; }; name = Debug; }; @@ -541,7 +541,7 @@ MACOSX_DEPLOYMENT_TARGET = 10.8; OTHER_LDFLAGS = ""; SDKROOT = macosx; - USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/mac /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/glfw3 /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources"; + USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/mac /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/glfw3 /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources"; }; name = Release; }; @@ -626,7 +626,7 @@ SDKROOT = iphoneos; STRIP_PNG_TEXT = NO; TARGETED_DEVICE_FAMILY = "1,2"; - USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/ios /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/auto /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/manual /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/anysdk/common/"; + USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/ios /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/auto /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/manual /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/anysdk/common/"; VALID_ARCHS = "arm64 armv7"; }; name = Debug; @@ -664,7 +664,7 @@ SDKROOT = iphoneos; STRIP_PNG_TEXT = NO; TARGETED_DEVICE_FAMILY = "1,2"; - USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/ios /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/auto /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/manual /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/anysdk/common/"; + USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/ios /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/auto /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/manual /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/anysdk/common/"; VALID_ARCHS = "arm64 armv7"; }; name = Release; diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 844c029ed3..4d63a42d0e 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -29,6 +29,8 @@ #import "RootViewController.h" #import "platform/ios/CCEAGLView-ios.h" +#import "cocos-analytics/CAAgent.h" + using namespace cocos2d; @implementation AppController @@ -43,6 +45,8 @@ static AppDelegate* s_sharedApplication = nullptr; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + [CAAgent enableDebug:NO]; + if (s_sharedApplication == nullptr) { s_sharedApplication = new (std::nothrow) AppDelegate(); @@ -113,6 +117,7 @@ static AppDelegate* s_sharedApplication = nullptr; If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); + [CAAgent onPause]; } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -124,6 +129,7 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } + [CAAgent onResume]; } - (void)applicationWillTerminate:(UIApplication *)application { @@ -136,6 +142,7 @@ static AppDelegate* s_sharedApplication = nullptr; delete s_sharedApplication; s_sharedApplication = nullptr; } + [CAAgent onDestroy]; } diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj b/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj index 614844099d..5e8b83e0ea 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj @@ -122,8 +122,8 @@ xcopy /Y /Q "$(COCOS_X_ROOT)\prebuilt\win32\*.*" "$(OutDir)" true Windows MachineX86 - $(ProjectDir)../../../simulator/win32/$(TargetName)$(TargetExt) - $(ProjectDir)../../../simulator/win32/$(TargetName).pdb + $(OutDir)$(TargetName)$(TargetExt) + $(OutDir)$(TargetName).pdb diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user b/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user index aa74fdbfc6..870b9eb8c1 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user @@ -1,13 +1,14 @@  - $(OutDir)../../../../simulator/win32 + $(OutDir) WindowsLocalDebugger - $(OutDir)../../../../simulator/win32/$(TargetFileName) - -workdir $(ProjectDir)../../../ + $(TargetPath) + + $(OutDir) WindowsLocalDebugger - + \ No newline at end of file diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml index e05719fcf3..91163e3279 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml @@ -4,7 +4,18 @@ android:installLocation="auto"> - + + + + + + + + + + + + - - - - - - - - - - - + diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle index 2ee236b04f..63c4e2f394 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -4,7 +4,7 @@ apply plugin: 'com.android.application' android { compileSdkVersion 22 - buildToolsVersion "25.0.0" + buildToolsVersion '26.0.2' defaultConfig { applicationId "org.cocos2d.helloworld" @@ -30,8 +30,6 @@ android { else { arguments 'NDK_MODULE_PATH=' + module_paths.join(':') } - - arguments 'NDK_OUT=./obj' arguments '-j' + Runtime.runtime.availableProcessors() abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String}) @@ -121,28 +119,6 @@ android.applicationVariants.all { variant -> } } -def copySo() { - copy { - from('./obj/local') { - include '**/*.so' - exclude '**/objs*' - } - into './libs' - } -} - -afterEvaluate { - tasks.findByName('externalNativeBuildDebug')?.doLast { - println ('Copying debug .so') - copySo() - } - - tasks.findByName('externalNativeBuildRelease')?.doLast { - println ('Copying release .so') - copySo() - } -} - dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':libcocos2dx') diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle index c6f2f5009e..2b56747de5 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle @@ -1,11 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.0' + classpath 'com.android.tools.build:gradle:3.0.0' + // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -14,6 +17,11 @@ buildscript { allprojects { repositories { + google() jcenter() } } + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties index b043b8ebca..1c6b75e38f 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Jul 31 20:40:49 CST 2015 +#Fri Oct 27 10:18:28 CST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml b/native/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml index c4d1dfb142..d7ff3bdc58 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -8,6 +8,17 @@ + + + + + + + + + + + @@ -32,15 +43,5 @@ android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true"/> - - - - - - - - - - - + diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index c25b9cca82..4d63a42d0e 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -29,6 +29,8 @@ #import "RootViewController.h" #import "platform/ios/CCEAGLView-ios.h" +#import "cocos-analytics/CAAgent.h" + using namespace cocos2d; @implementation AppController @@ -43,6 +45,8 @@ static AppDelegate* s_sharedApplication = nullptr; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + [CAAgent enableDebug:NO]; + if (s_sharedApplication == nullptr) { s_sharedApplication = new (std::nothrow) AppDelegate(); @@ -113,6 +117,7 @@ static AppDelegate* s_sharedApplication = nullptr; If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); + [CAAgent onPause]; } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -124,6 +129,7 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } + [CAAgent onResume]; } - (void)applicationWillTerminate:(UIApplication *)application { @@ -131,12 +137,12 @@ static AppDelegate* s_sharedApplication = nullptr; Called when the application is about to terminate. See also applicationDidEnterBackground:. */ - if (s_sharedApplication != nullptr) { delete s_sharedApplication; s_sharedApplication = nullptr; } + [CAAgent onDestroy]; } diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml index e05719fcf3..6b1074015c 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml @@ -4,7 +4,18 @@ android:installLocation="auto"> - + + + + + + + + + + + + - - - - - - - - - - diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle index 0d0dbe18ae..fc5b4f3112 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -4,7 +4,7 @@ apply plugin: 'com.android.application' android { compileSdkVersion 22 - buildToolsVersion "25.0.0" + buildToolsVersion '26.0.2' defaultConfig { applicationId "org.cocos2dx.hellojavascript" @@ -31,8 +31,6 @@ android { arguments 'NDK_MODULE_PATH=' + module_paths.join(':') } - arguments 'NDK_OUT=./obj' - arguments '-j' + Runtime.runtime.availableProcessors() abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String}) } @@ -121,28 +119,6 @@ android.applicationVariants.all { variant -> } } -def copySo() { - copy { - from('./obj/local') { - include '**/*.so' - exclude '**/objs*' - } - into './libs' - } -} - -afterEvaluate { - tasks.findByName('externalNativeBuildDebug')?.doLast { - println ('Copying debug .so') - copySo() - } - - tasks.findByName('externalNativeBuildRelease')?.doLast { - println ('Copying release .so') - copySo() - } -} - dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':libcocos2dx') diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle index c6f2f5009e..2b56747de5 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle @@ -1,11 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.0' + classpath 'com.android.tools.build:gradle:3.0.0' + // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -14,6 +17,11 @@ buildscript { allprojects { repositories { + google() jcenter() } } + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties index b043b8ebca..1c6b75e38f 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Jul 31 20:40:49 CST 2015 +#Fri Oct 27 10:18:28 CST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android/AndroidManifest.xml b/native/templates/js-template-link/frameworks/runtime-src/proj.android/AndroidManifest.xml index c4d1dfb142..0019058e9f 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android/AndroidManifest.xml +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -8,6 +8,17 @@ + + + + + + + + + + + @@ -33,14 +44,4 @@ android:largeScreens="true" android:xlargeScreens="true"/> - - - - - - - - - - diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm index 844c029ed3..4d63a42d0e 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -29,6 +29,8 @@ #import "RootViewController.h" #import "platform/ios/CCEAGLView-ios.h" +#import "cocos-analytics/CAAgent.h" + using namespace cocos2d; @implementation AppController @@ -43,6 +45,8 @@ static AppDelegate* s_sharedApplication = nullptr; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + [CAAgent enableDebug:NO]; + if (s_sharedApplication == nullptr) { s_sharedApplication = new (std::nothrow) AppDelegate(); @@ -113,6 +117,7 @@ static AppDelegate* s_sharedApplication = nullptr; If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); + [CAAgent onPause]; } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -124,6 +129,7 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } + [CAAgent onResume]; } - (void)applicationWillTerminate:(UIApplication *)application { @@ -136,6 +142,7 @@ static AppDelegate* s_sharedApplication = nullptr; delete s_sharedApplication; s_sharedApplication = nullptr; } + [CAAgent onDestroy]; } diff --git a/native/tools/cocos2d-console b/native/tools/cocos2d-console index eb9f5af3eb..d176fa08f6 160000 --- a/native/tools/cocos2d-console +++ b/native/tools/cocos2d-console @@ -1 +1 @@ -Subproject commit eb9f5af3eb4c2ea0a84b42246becbd6334f6c7c1 +Subproject commit d176fa08f649e7c1ac63e0644fea25d1fd4e365a diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml index e05719fcf3..6b1074015c 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml +++ b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml @@ -4,7 +4,18 @@ android:installLocation="auto"> - + + + + + + + + + + + + - - - - - - - - - - diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/build.gradle index 7c529111af..d5ec30dc85 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -4,7 +4,7 @@ apply plugin: 'com.android.application' android { compileSdkVersion 22 - buildToolsVersion "25.0.0" + buildToolsVersion '26.0.2' defaultConfig { applicationId "org.cocos2d.helloworld" @@ -41,6 +41,7 @@ android { sourceSets.main { java.srcDir "src" res.srcDir "res" + jniLibs.srcDir "libs" manifest.srcFile "AndroidManifest.xml" } @@ -56,10 +57,10 @@ android { signingConfigs { release { if (project.hasProperty("RELEASE_STORE_FILE")) { - storeFile file('/Users/jryin/.android/debug.keystore') - storePassword 'android' - keyAlias 'androiddebugkey' - keyPassword 'android' + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD } } } diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/debug.keystore b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/debug.keystore new file mode 100644 index 0000000000..062087fb00 Binary files /dev/null and b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/app/debug.keystore differ diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/build.gradle b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/build.gradle index f46d6535c5..2b56747de5 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/build.gradle +++ b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/build.gradle @@ -1,11 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.2.3' + classpath 'com.android.tools.build:gradle:3.0.0' + // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -14,6 +17,11 @@ buildscript { allprojects { repositories { + google() jcenter() } } + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle.properties b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle.properties index b0fc42cea2..cc90e06ea7 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle.properties +++ b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle.properties @@ -18,4 +18,9 @@ # org.gradle.parallel=true PROP_TARGET_SDK_VERSION=22 -PROP_APP_ABI=armeabi-v7a +PROP_APP_ABI=armeabi:armeabi-v7a:arm64-v8a:x86 + +RELEASE_STORE_FILE=debug.keystore +RELEASE_STORE_PASSWORD=123456 +RELEASE_KEY_ALIAS=debug_keystore +RELEASE_KEY_PASSWORD=123456 diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties index 5695367ecb..1c6b75e38f 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties +++ b/native/tools/simulator/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Jul 31 20:40:49 CST 2015 +#Fri Oct 27 10:18:28 CST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/native/tools/simulator/frameworks/runtime-src/proj.android/AndroidManifest.xml b/native/tools/simulator/frameworks/runtime-src/proj.android/AndroidManifest.xml index 5068cd5af3..ad14840c57 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.android/AndroidManifest.xml +++ b/native/tools/simulator/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -8,6 +8,17 @@ + + + + + + + + + + + @@ -32,12 +43,5 @@ android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true"/> - - - - - - - - + diff --git a/native/tools/tojs/cocos2dx.ini b/native/tools/tojs/cocos2dx.ini index aa68362c60..4b71fa0f6c 100644 --- a/native/tools/tojs/cocos2dx.ini +++ b/native/tools/tojs/cocos2dx.ini @@ -61,7 +61,7 @@ skip = Node::[update ^setPosition$ setGLServerState description getUserObject .* Label::[getLettersInfo getFontAtlas listenToBackground listenToFontAtlasPurge], .*Delegate::[*], PoolManager::[*], - Texture2D::[getName getStringForFormat getBitsPerPixelForFormat initWithMipmaps initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData getPixelFormatInfoMap updateWithData forceDeleteALLTexture2D], + Texture2D::[getStringForFormat getBitsPerPixelForFormat initWithMipmaps initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData getPixelFormatInfoMap updateWithData forceDeleteALLTexture2D], Set::[begin end acceptVisitor], IMEDispatcher::[*], Thread::[*], @@ -95,7 +95,7 @@ skip = Node::[update ^setPosition$ setGLServerState description getUserObject .* Action::[update], TargetedAction::[create], RotateTo::[calculateAngles], - GLProgram::[getUniformFlags getVertexAttrib getProgram setUniformLocationWith(1|2|3|4)fv setUniformLocationWith(2|3|4)iv setUniformLocationWithMatrix(2|3|4)fv], + GLProgram::[getUniformFlags getVertexAttrib setUniformLocationWith(1|2|3|4)fv setUniformLocationWith(2|3|4)iv setUniformLocationWithMatrix(2|3|4)fv], GLProgramState::[setUniformVec4 setVertexAttribPointer], TMXLayer::[getTiles setTiles], TMXMapInfo::[startElement endElement textHandler], @@ -111,7 +111,7 @@ skip = Node::[update ^setPosition$ setGLServerState description getUserObject .* Application::[^application.* ^run$ getCurrentLanguageCode setAnimationInterval], ccFontDefinition::[*], NewTextureAtlas::[*], - RenderTexture::[listenToBackground listenToForeground saveToFile], + RenderTexture::[listenToBackground listenToForeground], TextFieldTTF::[(g|s)etDelegate], EventListenerVector::[*], EventListener(Touch|Keyboard|Mouse|Acceleration|Focus|Custom).*::[create], @@ -139,7 +139,7 @@ rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames ge ProgressTimer::[setReverseProgress=setReverseDirection], Animation::[create=createWithAnimationFrames], AnimationCache::[addAnimationsWithFile=addAnimations], - GLProgram::[initWithByteArrays=initWithString initWithFilenames=init setUniformLocationWith1i=setUniformLocationI32 bindAttribLocation=addAttribute], + GLProgram::[initWithByteArrays=initWithString initWithFilenames=init bindAttribLocation=addAttribute setUniformLocationWith1i=setUniformLocationI32 setUniformLocationWith2i=setUniformLocationI32 setUniformLocationWith3i=setUniformLocationI32 setUniformLocationWith4i=setUniformLocationI32 setUniformLocationWith1f=setUniformLocationF32 setUniformLocationWith2f=setUniformLocationF32 setUniformLocationWith3f=setUniformLocationF32 setUniformLocationWith4f=setUniformLocationF32], Node::[getGLProgram=getShaderProgram setGLProgram=setShaderProgram getPositionZ=getVertexZ setPositionZ=setVertexZ removeFromParentAndCleanup=removeFromParent removeAllChildrenWithCleanup=removeAllChildren setRotationSkewX=setRotationX setRotationSkewY=setRotationY getRotationSkewX=getRotationX getRotationSkewY=getRotationY getNodeToParentTransform=getNodeToParentTransform3D getParentToNodeTransform=getParentToNodeTransform3D getNodeToWorldTransform=getNodeToWorldTransform3D getWorldToNodeTransform=getWorldToNodeTransform3D getNodeToWorldAffineTransform=getNodeToWorldTransform getNodeToParentAffineTransform=getNodeToParentTransform getParentToNodeAffineTransform=getParentToNodeTransform getWorldToNodeAffineTransform=getWorldToNodeTransform], LabelAtlas::[create=_create], Sprite::[getPositionZ=getVertexZ setPositionZ=setVertexZ],