diff --git a/native/cocos/2d/CCActionInstant.cpp b/native/cocos/2d/CCActionInstant.cpp index c872fe5f8d..ccab1c7bcc 100644 --- a/native/cocos/2d/CCActionInstant.cpp +++ b/native/cocos/2d/CCActionInstant.cpp @@ -349,7 +349,6 @@ bool CallFunc::initWithFunction(const std::function &func) CallFunc::~CallFunc() { - CC_SAFE_RELEASE(_selectorTarget); } CallFunc* CallFunc::clone() const diff --git a/native/cocos/2d/CCActionInstant.h b/native/cocos/2d/CCActionInstant.h index 2a06c15686..375dea3119 100644 --- a/native/cocos/2d/CCActionInstant.h +++ b/native/cocos/2d/CCActionInstant.h @@ -42,7 +42,7 @@ NS_CC_BEGIN /** @class ActionInstant * @brief Instant actions are immediate actions. They don't have a duration like the IntervalAction actions. **/ -class CC_DLL ActionInstant : public FiniteTimeAction // +class CC_DLL ActionInstant : public FiniteTimeAction { public: // @@ -316,7 +316,7 @@ private: /** @class CallFunc * @brief Calls a 'callback'. */ -class CC_DLL CallFunc : public ActionInstant // +class CC_DLL CallFunc : public ActionInstant { public: /** Creates the action with the callback of type std::function. @@ -335,28 +335,6 @@ public: */ virtual void execute(); - /** Get the selector target. - * - * @return The selector target. - */ - inline Ref* getTargetCallback() - { - return _selectorTarget; - } - - /** Set the selector target. - * - * @param sel The selector target. - */ - inline void setTargetCallback(Ref* sel) - { - if (sel != _selectorTarget) - { - CC_SAFE_RETAIN(sel); - CC_SAFE_RELEASE(_selectorTarget); - _selectorTarget = sel; - } - } // // Overrides // @@ -369,9 +347,7 @@ public: CC_CONSTRUCTOR_ACCESS: CallFunc() - : _selectorTarget(nullptr) - , _callFunc(nullptr) - , _function(nullptr) + : _function(nullptr) { } virtual ~CallFunc(); @@ -382,14 +358,6 @@ CC_CONSTRUCTOR_ACCESS: bool initWithFunction(const std::function& func); protected: - /** Target that will be called */ - Ref* _selectorTarget; - - union - { - SEL_CallFunc _callFunc; - SEL_CallFuncN _callFuncN; - }; /** function that will be called */ std::function _function; diff --git a/native/cocos/2d/CCActionInterval.cpp b/native/cocos/2d/CCActionInterval.cpp index 7049f80764..5d19ae343a 100644 --- a/native/cocos/2d/CCActionInterval.cpp +++ b/native/cocos/2d/CCActionInterval.cpp @@ -264,6 +264,11 @@ bool Sequence::init(const Vector& arrayOfActions) { FiniteTimeAction *action = arrayOfActions.at(i); prev = createWithTwoActions(prev, action); + + // The owner 'prev' is a pure C++ object, 'createWithTwoActions' in the previous line + // will not be able to find a relevant JS object associated with 'prev' object. + // So 'retainScriptObject' in 'initWithTwoActions' will fail to hold 'prev' object. + // The workaround is that we need to associate 'action' to Sequence object like the following code. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) @@ -286,6 +291,9 @@ bool Sequence::initWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction return false; } + CCASSERT(actionOne != this, "actionOne should not be sequence self!"); + CCASSERT(actionTwo != this, "actionOne should not be sequence self!"); + float d = actionOne->getDuration() + actionTwo->getDuration(); ActionInterval::initWithDuration(d); @@ -758,6 +766,11 @@ bool Spawn::init(const Vector& arrayOfActions) { FiniteTimeAction* action = arrayOfActions.at(i); prev = createWithTwoActions(prev, action); + + // The owner 'prev' is a pure C++ object, 'createWithTwoActions' in the previous line + // will not be able to find a relevant JS object associated with 'prev' object. + // So 'retainScriptObject' in 'initWithTwoActions' will fail to hold 'prev' object. + // The workaround is that we need to associate 'action' to Spawn object like the following code. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) @@ -801,13 +814,17 @@ bool Spawn::initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *acti _one->retain(); _two->retain(); - + + // NOTE: We should retainScriptObject for action1 and action2 rather than _one and _two. + // It's because _one & _two actions are pure C++ objects and Sequence::initWithTwoActions + // can't retainScriptObject for action1 and action2. action1 or action2 will be hung up + // and they may be garbage collected whenever, which may cause crash bug that really hard to find. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) { - sEngine->retainScriptObject(this, _one); - sEngine->retainScriptObject(this, _two); + sEngine->retainScriptObject(this, action1); + sEngine->retainScriptObject(this, action2); } #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS diff --git a/native/cocos/2d/CCActionManager.cpp b/native/cocos/2d/CCActionManager.cpp index 2d0c8e17ac..7559846565 100644 --- a/native/cocos/2d/CCActionManager.cpp +++ b/native/cocos/2d/CCActionManager.cpp @@ -239,9 +239,7 @@ void ActionManager::removeAllActionsFromTarget(Node *target) element->currentAction->retain(); element->currentActionSalvaged = true; } - - ccArrayRemoveAllObjects(element->actions); - + #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine(); if (sEngine) @@ -257,6 +255,8 @@ void ActionManager::removeAllActionsFromTarget(Node *target) } } #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS + + ccArrayRemoveAllObjects(element->actions); if (_currentTarget == element) { diff --git a/native/cocos/2d/CCNode.cpp b/native/cocos/2d/CCNode.cpp index 4d750ad984..0eebd9a9d3 100644 --- a/native/cocos/2d/CCNode.cpp +++ b/native/cocos/2d/CCNode.cpp @@ -694,11 +694,8 @@ void Node::setGLProgram(GLProgram* glProgram) { if (_glProgramState == nullptr || (_glProgramState && _glProgramState->getGLProgram() != glProgram)) { - CC_SAFE_RELEASE(_glProgramState); - _glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram); - _glProgramState->retain(); - - _glProgramState->setNodeBinding(this); + auto glProgramState = GLProgramState::getOrCreateWithGLProgram(glProgram); + setGLProgramState(glProgramState); } } diff --git a/native/cocos/2d/CCNode.h b/native/cocos/2d/CCNode.h index b4c0c271ad..f4bd03575a 100644 --- a/native/cocos/2d/CCNode.h +++ b/native/cocos/2d/CCNode.h @@ -986,7 +986,7 @@ public: * Since v2.0, each rendering node must set its shader program. * It should be set in initialize phase. @code - node->setGLrProgram(GLProgramCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + node->setGLProgram(GLProgramCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); @endcode * * @param glprogram The shader program. diff --git a/native/cocos/base/CCEvent.cpp b/native/cocos/base/CCEvent.cpp index c7928d51e0..ed8c2ceae9 100644 --- a/native/cocos/base/CCEvent.cpp +++ b/native/cocos/base/CCEvent.cpp @@ -38,5 +38,10 @@ Event::~Event() { } +void Event::reset() +{ + _isStopped = false; + _currentTarget = nullptr; +} NS_CC_END diff --git a/native/cocos/base/CCEvent.h b/native/cocos/base/CCEvent.h index acbbcaf721..899ce95cfd 100644 --- a/native/cocos/base/CCEvent.h +++ b/native/cocos/base/CCEvent.h @@ -88,6 +88,8 @@ public: */ inline Node* getCurrentTarget() { return _currentTarget; }; + virtual void reset(); + protected: /** Sets current target */ inline void setCurrentTarget(Node* target) { _currentTarget = target; }; diff --git a/native/cocos/base/CCEventMouse.cpp b/native/cocos/base/CCEventMouse.cpp index e0369beafd..e21418a9ca 100644 --- a/native/cocos/base/CCEventMouse.cpp +++ b/native/cocos/base/CCEventMouse.cpp @@ -82,4 +82,16 @@ Vec2 EventMouse::getDelta() const { return getLocation() - getPreviousLocation(); } + +void EventMouse::reset() +{ + Event::reset(); + _mouseButton = -1; + _x = 0.0f; + _y = 0.0f; + _scrollX = 0.0f; + _scrollY = 0.0f; + _startPointCaptured = false; +} + NS_CC_END diff --git a/native/cocos/base/CCEventMouse.h b/native/cocos/base/CCEventMouse.h index 3ee3d12a0a..2a42e10dda 100644 --- a/native/cocos/base/CCEventMouse.h +++ b/native/cocos/base/CCEventMouse.h @@ -173,6 +173,7 @@ public: */ Vec2 getStartLocationInView() const; + virtual void reset() override; private: virtual ~EventMouse() {} diff --git a/native/cocos/base/CCEventTouch.cpp b/native/cocos/base/CCEventTouch.cpp index 73f1b0d8c1..39346b58a0 100644 --- a/native/cocos/base/CCEventTouch.cpp +++ b/native/cocos/base/CCEventTouch.cpp @@ -30,12 +30,15 @@ NS_CC_BEGIN EventTouch::EventTouch() : Event(Type::TOUCH) +, _eventCode(EventCode::INVALID) { _touches.reserve(MAX_TOUCHES); } void EventTouch::reset() { + Event::reset(); + _eventCode = EventCode::INVALID; _touches.clear(); } diff --git a/native/cocos/base/CCEventTouch.h b/native/cocos/base/CCEventTouch.h index 7f576d0b2a..4c6fdecbff 100644 --- a/native/cocos/base/CCEventTouch.h +++ b/native/cocos/base/CCEventTouch.h @@ -51,10 +51,11 @@ public: /** EventCode Touch event code.*/ enum class EventCode { - BEGAN, + BEGAN = 0, MOVED, ENDED, - CANCELLED + CANCELLED, + INVALID = -1, }; /** @@ -75,6 +76,8 @@ public: */ inline const std::vector& getTouches() const { return _touches; }; + virtual void reset() override; + #if TOUCH_PERF_DEBUG /** Set the event code. * @@ -91,8 +94,6 @@ public: private: virtual ~EventTouch() {} - void reset(); - EventCode _eventCode; std::vector _touches; diff --git a/native/cocos/cocos2d.cpp b/native/cocos/cocos2d.cpp index 3985c767a1..8463c7bbf4 100644 --- a/native/cocos/cocos2d.cpp +++ b/native/cocos/cocos2d.cpp @@ -32,7 +32,7 @@ NS_CC_BEGIN CC_DLL const char* cocos2dVersion() { - return "1.7.0"; + return "Cocos2d-x-lite v1.8.2"; } NS_CC_END diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp b/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp index adfa819531..66aa461853 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCArmatureDisplay.cpp @@ -28,7 +28,12 @@ CCArmatureDisplay::CCArmatureDisplay() : this->setEventDispatcher(_dispatcher); _dispatcher->setEnabled(true); } -CCArmatureDisplay::~CCArmatureDisplay() {} + +CCArmatureDisplay::~CCArmatureDisplay() +{ + dispose(); + CC_SAFE_RELEASE(_dispatcher); +} // cleared by armature void CCArmatureDisplay::_onClear() diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp index dc5f6c42f9..3e98b4ede3 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.cpp @@ -5,7 +5,23 @@ DRAGONBONES_NAMESPACE_BEGIN -CCFactory CCFactory::factory; +namespace { + CCFactory* __instance = nullptr; +} + +CCFactory* CCFactory::getInstance() +{ + if (__instance == nullptr) + __instance = new (std::nothrow) CCFactory(); + + return __instance; +} + +void CCFactory::destroyInstance() +{ + delete __instance; + __instance = nullptr; +} CCFactory::CCFactory() { diff --git a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h index 3b73259dc8..065d73d941 100644 --- a/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h +++ b/native/cocos/editor-support/dragonbones/cocos2dx/CCFactory.h @@ -10,15 +10,12 @@ DRAGONBONES_NAMESPACE_BEGIN class CCFactory : public BaseFactory { public: - static CCFactory factory; + static CCFactory* getInstance(); + static void destroyInstance(); -public: CCFactory(); ~CCFactory(); -private: - DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CCFactory); - protected: virtual TextureAtlasData* _generateTextureAtlasData(TextureAtlasData* textureAtlasData, void* textureAtlas) const override; virtual Armature* _generateArmature(const BuildArmaturePackage& dataPackage) const override; @@ -35,6 +32,8 @@ public: private: void _initTextureAtlasData(TextureAtlasData* atlasData); + + DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CCFactory); }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp index 7c0dd6be47..380636d3d7 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp @@ -1,6 +1,9 @@ #include "BaseObject.h" + DRAGONBONES_NAMESPACE_BEGIN +std::vector BaseObject::__allDragonBonesObjects; + std::size_t BaseObject::_hashCode = 0; std::size_t BaseObject::_defaultMaxCount = 5000; std::unordered_map BaseObject::_maxCountMap; @@ -25,14 +28,12 @@ void BaseObject::_returnObject(BaseObject* object) DRAGONBONES_ASSERT(false, "The object aleady in pool."); } + object->_isInPool = true; if (_recycleOrDestroyCallback != nullptr) _recycleOrDestroyCallback(object, 0); } else { - if (_recycleOrDestroyCallback != nullptr) - _recycleOrDestroyCallback(object, 1); - delete object; } } @@ -116,6 +117,7 @@ void BaseObject::clearPool(std::size_t classTypeIndex) { for (auto object : pool) { +// printf("delete object: %s, %p\n", typeid(*object).name(), object); delete object; } @@ -125,19 +127,37 @@ void BaseObject::clearPool(std::size_t classTypeIndex) } } -BaseObject::BaseObject() : - hashCode(BaseObject::_hashCode++) -{} +BaseObject::BaseObject() +: hashCode(BaseObject::_hashCode++) +, _isInPool(false) +{ + __allDragonBonesObjects.push_back(this); +} + BaseObject::~BaseObject() { - int i = 0; - ++i; + if (_recycleOrDestroyCallback != nullptr) + _recycleOrDestroyCallback(this, 1); + + auto iter = std::find(__allDragonBonesObjects.begin(), __allDragonBonesObjects.end(), this); + if (iter != __allDragonBonesObjects.end()) + { + __allDragonBonesObjects.erase(iter); + } } void BaseObject::returnToPool() { _onClear(); + // _returnObject make delete this BaseObject, + // so after the function invocation, any other operations of + // this object should not be done. _returnObject(this); } +std::vector& BaseObject::getAllObjects() +{ + return __allDragonBonesObjects; +} + DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.h b/native/cocos/editor-support/dragonbones/core/BaseObject.h index b80b237c78..900a165aa7 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.h +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.h @@ -1,4 +1,4 @@ -#ifndef DRAGONBONES_BASE_OBJECT_H +#ifndef DRAGONBONES_BASE_OBJECT_H #define DRAGONBONES_BASE_OBJECT_H #include "DragonBones.h" @@ -47,7 +47,7 @@ public: { const auto object = dynamic_cast(pool.back()); pool.pop_back(); - + object->_isInPool = false; return object; } } @@ -55,6 +55,8 @@ public: return new (std::nothrow) T(); } + static std::vector& getAllObjects(); + public: const std::size_t hashCode; @@ -72,6 +74,10 @@ public: virtual std::size_t getClassTypeIndex() const = 0; void returnToPool(); + inline bool isInPool() const { return _isInPool; } +private: + static std::vector __allDragonBonesObjects; + bool _isInPool; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/spine/SkeletonRenderer.cpp b/native/cocos/editor-support/spine/SkeletonRenderer.cpp index ea92a595ec..e66de41713 100644 --- a/native/cocos/editor-support/spine/SkeletonRenderer.cpp +++ b/native/cocos/editor-support/spine/SkeletonRenderer.cpp @@ -59,8 +59,11 @@ SkeletonRenderer* SkeletonRenderer::createWithFile (const std::string& skeletonD return node; } -void SkeletonRenderer::initialize () { - _worldVertices = new float[1000]; // Max number of vertices per mesh. +void SkeletonRenderer::initialize () { + + // SkeletonRenderer::initalize may be invoked twice, need to check whether _worldVertics is already allocated to avoid memory leak. + if (_worldVertices == nullptr) + _worldVertices = new float[1000]; // Max number of vertices per mesh. _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; setOpacityModifyRGB(true); @@ -74,25 +77,25 @@ void SkeletonRenderer::setSkeletonData (spSkeletonData *skeletonData, bool ownsS } SkeletonRenderer::SkeletonRenderer () - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { } SkeletonRenderer::SkeletonRenderer (spSkeletonData *skeletonData, bool ownsSkeletonData) - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { initWithData(skeletonData, ownsSkeletonData); } SkeletonRenderer::SkeletonRenderer (const std::string& skeletonDataFile, spAtlas* atlas, float scale) - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { initWithJsonFile(skeletonDataFile, atlas, scale); } SkeletonRenderer::SkeletonRenderer (const std::string& skeletonDataFile, const std::string& atlasFile, float scale) - : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _timeScale(1) { + : _atlas(nullptr), _attachmentLoader(nullptr), _debugSlots(false), _debugBones(false), _worldVertices(nullptr), _timeScale(1) { initWithJsonFile(skeletonDataFile, atlasFile, scale); } -SkeletonRenderer::~SkeletonRenderer () { +SkeletonRenderer::~SkeletonRenderer () { if (_ownsSkeletonData) spSkeletonData_dispose(_skeleton->data); spSkeleton_dispose(_skeleton); if (_atlas) spAtlas_dispose(_atlas); diff --git a/native/cocos/platform/android/java/libs/libcocosanalytics.jar b/native/cocos/platform/android/java/libs/libcocosanalytics.jar index 29e665f8f5..5ed690948f 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/Cocos2dxGLSurfaceView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java index 5fb3f8e842..2e4c875ad7 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 @@ -180,7 +180,9 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume(); - CAAgent.onResume(Cocos2dxGLSurfaceView.this.getContext()); + if (CAAgent.isInited()) { + CAAgent.onResume(Cocos2dxGLSurfaceView.this.getContext()); + } } }); } @@ -191,7 +193,9 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause(); - CAAgent.onPause(Cocos2dxGLSurfaceView.this.getContext()); + if (CAAgent.isInited()) { + CAAgent.onPause(Cocos2dxGLSurfaceView.this.getContext()); + } } }); this.setRenderMode(RENDERMODE_WHEN_DIRTY); diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java index 2d2a69a083..34106492e8 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java @@ -423,7 +423,6 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl mCurrentState = STATE_PLAYBACK_COMPLETED; mTargetState = STATE_PLAYBACK_COMPLETED; - release(true); if (mOnVideoEventListener != null) { mOnVideoEventListener.onVideoEvent(mViewTag,EVENT_COMPLETED); } diff --git a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 34ce3a7adb..452c29e00e 100644 --- a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -679,6 +679,7 @@ void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, if(GLFW_PRESS == action) { EventMouse* event = __mouseDownEvent; + event->reset(); event->setCursorPosition(cursorX, cursorY); event->setMouseButton(button); Director::getInstance()->getEventDispatcher()->dispatchEvent(event); @@ -686,6 +687,7 @@ void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, else if(GLFW_RELEASE == action) { EventMouse* event = __mouseUpEvent; + event->reset(); event->setCursorPosition(cursorX, cursorY); event->setMouseButton(button); Director::getInstance()->getEventDispatcher()->dispatchEvent(event); @@ -720,6 +722,7 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; EventMouse* event = __mouseMoveEvent; + event->reset(); // Set current button if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { @@ -740,6 +743,7 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) { EventMouse* event = __mouseScrollEvent; + event->reset(); //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX; float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; diff --git a/native/cocos/renderer/CCGLProgramCache.cpp b/native/cocos/renderer/CCGLProgramCache.cpp index 0fc2e17324..f0caeef76c 100644 --- a/native/cocos/renderer/CCGLProgramCache.cpp +++ b/native/cocos/renderer/CCGLProgramCache.cpp @@ -38,6 +38,11 @@ THE SOFTWARE. NS_CC_BEGIN +namespace { + GLProgramCache::GLProgramLifeCycleHook __glProgramCreateHook = nullptr; + GLProgramCache::GLProgramLifeCycleHook __glProgramDestroyHook = nullptr; +} + enum { kShaderType_PositionTextureColor, kShaderType_PositionTextureColor_noMVP, @@ -77,6 +82,8 @@ GLProgramCache* GLProgramCache::getInstance() void GLProgramCache::destroyInstance() { + if (_sharedGLProgramCache != nullptr) + _sharedGLProgramCache->cleanup(); CC_SAFE_RELEASE_NULL(_sharedGLProgramCache); } @@ -88,11 +95,8 @@ GLProgramCache::GLProgramCache() GLProgramCache::~GLProgramCache() { - for( auto it = _programs.begin(); it != _programs.end(); ++it ) { - (it->second)->release(); - } - CCLOGINFO("deallocing GLProgramCache: %p", this); + cleanup(); } bool GLProgramCache::init() @@ -108,6 +112,18 @@ bool GLProgramCache::init() return true; } +void GLProgramCache::cleanup() +{ + for(auto& e : _programs) + { + if (__glProgramDestroyHook != nullptr) + __glProgramDestroyHook(this, e.second); + + e.second->release(); + } + _programs.clear(); +} + void GLProgramCache::loadDefaultGLPrograms() { // Position Texture Color shader @@ -409,11 +425,18 @@ void GLProgramCache::addGLProgram(GLProgram* program, const std::string &key) if( prev == program ) return; + if (__glProgramDestroyHook != nullptr) + __glProgramDestroyHook(this, prev); + _programs.erase(key); CC_SAFE_RELEASE_NULL(prev); if (program) program->retain(); + + if (__glProgramCreateHook != nullptr) + __glProgramCreateHook(this, program); + _programs[key] = program; } @@ -431,4 +454,25 @@ std::string GLProgramCache::getShaderMacrosForLight() const return std::string(def); } +/* static */ +void GLProgramCache::setGLProgramCreateHook(GLProgramLifeCycleHook hook) +{ + __glProgramCreateHook = hook; +} + +/* static */ +void GLProgramCache::setGLProgramDestroyHook(GLProgramLifeCycleHook hook) +{ + __glProgramDestroyHook = hook; +} + +void GLProgramCache::notifyAllGLProgramsCreated() +{ + if (__glProgramCreateHook != nullptr) + { + for (const auto& e : _programs) + __glProgramCreateHook(this, e.second); + } +} + NS_CC_END diff --git a/native/cocos/renderer/CCGLProgramCache.h b/native/cocos/renderer/CCGLProgramCache.h index 054b020238..e94ddfeab8 100644 --- a/native/cocos/renderer/CCGLProgramCache.h +++ b/native/cocos/renderer/CCGLProgramCache.h @@ -85,12 +85,20 @@ public: /** reload default programs these are relative to light */ void reloadDefaultGLProgramsRelativeToLights(); + using GLProgramLifeCycleHook = void (*)(GLProgramCache*, GLProgram*); + static void setGLProgramCreateHook(GLProgramLifeCycleHook hook); + static void setGLProgramDestroyHook(GLProgramLifeCycleHook hook); + + void notifyAllGLProgramsCreated(); + private: /** @{ Init and load predefined shaders. */ bool init(); + void cleanup(); + void loadDefaultGLProgram(GLProgram *program, int type); /** @} diff --git a/native/cocos/renderer/CCGLProgramStateCache.cpp b/native/cocos/renderer/CCGLProgramStateCache.cpp index 485c15704e..0337d3534a 100644 --- a/native/cocos/renderer/CCGLProgramStateCache.cpp +++ b/native/cocos/renderer/CCGLProgramStateCache.cpp @@ -28,9 +28,13 @@ THE SOFTWARE. #include "renderer/CCGLProgramState.h" #include "renderer/CCGLProgram.h" - NS_CC_BEGIN +namespace { + GLProgramStateCache::GLProgramStateLifeCycleHook __glProgramStateCreateHook = nullptr; + GLProgramStateCache::GLProgramStateLifeCycleHook __glProgramStateDestroyHook = nullptr; +} + GLProgramStateCache* GLProgramStateCache::s_instance = nullptr; GLProgramStateCache::GLProgramStateCache() @@ -39,7 +43,7 @@ GLProgramStateCache::GLProgramStateCache() GLProgramStateCache::~GLProgramStateCache() { - _glProgramStates.clear(); + removeAllGLProgramState(); } GLProgramStateCache* GLProgramStateCache::getInstance() @@ -66,6 +70,10 @@ GLProgramState* GLProgramStateCache::getGLProgramState(GLProgram* glprogram) auto ret = new (std::nothrow) GLProgramState; if(ret && ret->init(glprogram)) { _glProgramStates.insert(glprogram, ret); + + if (__glProgramStateCreateHook != nullptr) + __glProgramStateCreateHook(this, ret); + ret->release(); return ret; } @@ -81,6 +89,8 @@ void GLProgramStateCache::removeUnusedGLProgramState() if( value->getReferenceCount() == 1 ) { CCLOG("cocos2d: GLProgramStateCache: removing unused GLProgramState"); + if (__glProgramStateDestroyHook != nullptr) + __glProgramStateDestroyHook(this, value); //value->release(); it = _glProgramStates.erase(it); } else { @@ -91,8 +101,26 @@ void GLProgramStateCache::removeUnusedGLProgramState() void GLProgramStateCache::removeAllGLProgramState() { + if (__glProgramStateDestroyHook != nullptr) + { + for (const auto& e : _glProgramStates) + __glProgramStateDestroyHook(this, e.second); + } + _glProgramStates.clear(); } +/* static */ +void GLProgramStateCache::setGLProgramStateCreateHook(GLProgramStateLifeCycleHook hook) +{ + __glProgramStateCreateHook = hook; +} + +/* static */ +void GLProgramStateCache::setGLProgramStateDestroyHook(GLProgramStateLifeCycleHook hook) +{ + __glProgramStateDestroyHook = hook; +} + NS_CC_END diff --git a/native/cocos/renderer/CCGLProgramStateCache.h b/native/cocos/renderer/CCGLProgramStateCache.h index 583822931d..34e34f32c7 100644 --- a/native/cocos/renderer/CCGLProgramStateCache.h +++ b/native/cocos/renderer/CCGLProgramStateCache.h @@ -63,6 +63,10 @@ public: /**Remove unused GLProgramState.*/ void removeUnusedGLProgramState(); + using GLProgramStateLifeCycleHook = void (*)(GLProgramStateCache*, GLProgramState*); + static void setGLProgramStateCreateHook(GLProgramStateLifeCycleHook hook); + static void setGLProgramStateDestroyHook(GLProgramStateLifeCycleHook hook); + protected: GLProgramStateCache(); ~GLProgramStateCache(); diff --git a/native/cocos/renderer/CCTexture2D.cpp b/native/cocos/renderer/CCTexture2D.cpp index cf4e2c785d..c9a322554f 100644 --- a/native/cocos/renderer/CCTexture2D.cpp +++ b/native/cocos/renderer/CCTexture2D.cpp @@ -432,16 +432,6 @@ void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, ssize_t dataL } // converter function end ////////////////////////////////////////////////////////////////////////// -static std::unordered_set s_allGLTexture2D; - -void Texture2D::forceDeleteALLTexture2D() -{ - auto copyMap = s_allGLTexture2D; - for (auto&& it: copyMap) { - delete it; - } - s_allGLTexture2D.clear(); -} Texture2D::Texture2D() : _pixelFormat(Texture2D::PixelFormat::DEFAULT) @@ -458,15 +448,11 @@ Texture2D::Texture2D() , _valid(true) , _alphaTexture(nullptr) { - s_allGLTexture2D.insert(this); _antialiasEnabled = Director::getInstance()->getOpenGLView()->isAntiAliasEnabled(); } Texture2D::~Texture2D() { - if (s_allGLTexture2D.find(this) != s_allGLTexture2D.end()) { - s_allGLTexture2D.erase(this); - } #if CC_ENABLE_CACHE_TEXTURE_DATA VolatileTextureMgr::removeTexture(this); #endif diff --git a/native/cocos/renderer/CCTexture2D.h b/native/cocos/renderer/CCTexture2D.h index 2234775e86..fff2aa3539 100644 --- a/native/cocos/renderer/CCTexture2D.h +++ b/native/cocos/renderer/CCTexture2D.h @@ -180,8 +180,6 @@ public: */ static Texture2D::PixelFormat getDefaultAlphaPixelFormat(); - static void forceDeleteALLTexture2D(); - public: /** * @js ctor diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index b0be744b09..eb69845614 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -42,12 +42,15 @@ THE SOFTWARE. #include "base/ccUtils.h" #include "base/CCNinePatchImageParser.h" - - using namespace std; NS_CC_BEGIN +namespace { + TextureCache::TextureLifeCycleHook __textureCreateHook = nullptr; + TextureCache::TextureLifeCycleHook __textureDestroyHook = nullptr; +} + // implementation TextureCache TextureCache* TextureCache::getInstance() @@ -57,8 +60,6 @@ TextureCache* TextureCache::getInstance() TextureCache::TextureCache() : _loadingThread(nullptr) -, _textureCreateHook(nullptr) -, _textureDestroyHook(nullptr) , _asyncRefCount(0) , _needQuit(false) { @@ -302,8 +303,8 @@ void TextureCache::addImageAsyncCallBack(float dt) texture->autorelease(); - if (_textureCreateHook != nullptr) - _textureCreateHook(this, texture); + if (__textureCreateHook != nullptr) + __textureCreateHook(this, texture); } else { texture = nullptr; CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); @@ -366,8 +367,8 @@ Texture2D * TextureCache::addImage(const std::string &path) // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); - if (_textureCreateHook != nullptr) - _textureCreateHook(this, texture); + if (__textureCreateHook != nullptr) + __textureCreateHook(this, texture); //parse 9-patch info this->parseNinePatchImage(image, texture, path); @@ -420,8 +421,8 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) texture->autorelease(); - if (_textureCreateHook != nullptr) - _textureCreateHook(this, texture); + if (__textureCreateHook != nullptr) + __textureCreateHook(this, texture); } else { @@ -495,8 +496,8 @@ cocos2d::Vector TextureCache::getAllTextures() const void TextureCache::removeAllTextures() { for( auto it=_textures.begin(); it!=_textures.end(); ++it ) { - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, it->second); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, it->second); (it->second)->release(); } @@ -509,8 +510,8 @@ void TextureCache::removeUnusedTextures() Texture2D *tex = it->second; if( tex->getReferenceCount() == 1 ) { CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str()); - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, tex); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, tex); tex->release(); it = _textures.erase(it); @@ -531,8 +532,8 @@ void TextureCache::removeTexture(Texture2D* texture) for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */ ) { if( it->second == texture ) { - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, texture); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, texture); it->second->release(); it = _textures.erase(it); @@ -554,8 +555,8 @@ void TextureCache::removeTextureForKey(const std::string &textureKeyName) } if( it != _textures.end() ) { - if (_textureDestroyHook != nullptr) - _textureDestroyHook(this, it->second); + if (__textureDestroyHook != nullptr) + __textureDestroyHook(this, it->second); (it->second)->release(); _textures.erase(it); @@ -680,14 +681,16 @@ void TextureCache::renameTextureWithKey(const std::string& srcName, const std::s } } +/* static */ void TextureCache::setTextureCreateHook(TextureLifeCycleHook hook) { - _textureCreateHook = hook; + __textureCreateHook = hook; } +/* static */ void TextureCache::setTextureDestroyHook(TextureLifeCycleHook hook) { - _textureDestroyHook = hook; + __textureDestroyHook = hook; } #if CC_ENABLE_CACHE_TEXTURE_DATA diff --git a/native/cocos/renderer/CCTextureCache.h b/native/cocos/renderer/CCTextureCache.h index e7125453be..aea721117e 100644 --- a/native/cocos/renderer/CCTextureCache.h +++ b/native/cocos/renderer/CCTextureCache.h @@ -214,8 +214,8 @@ public: void renameTextureWithKey(const std::string& srcName, const std::string& dstName); using TextureLifeCycleHook = void (*)(TextureCache*, Texture2D*); - void setTextureCreateHook(TextureLifeCycleHook hook); - void setTextureDestroyHook(TextureLifeCycleHook hook); + static void setTextureCreateHook(TextureLifeCycleHook hook); + static void setTextureDestroyHook(TextureLifeCycleHook hook); private: void addImageAsyncCallBack(float dt); @@ -237,9 +237,6 @@ protected: std::thread* _loadingThread; - TextureLifeCycleHook _textureCreateHook; - TextureLifeCycleHook _textureDestroyHook; - int _asyncRefCount; bool _needQuit; }; 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 6909aefa06..6d57869083 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 @@ -467,13 +467,21 @@ Touch : function ( cc.Event = { /** - * @method isStopped - * @return {bool} + * @method reset */ -isStopped : function ( +reset : function ( ) { - return false; +}, + +/** + * @method getCurrentTarget + * @return {cc.Node} + */ +getCurrentTarget : function ( +) +{ + return cc.Node; }, /** @@ -487,13 +495,13 @@ getType : function ( }, /** - * @method getCurrentTarget - * @return {cc.Node} + * @method isStopped + * @return {bool} */ -getCurrentTarget : function ( +isStopped : function ( ) { - return cc.Node; + return false; }, /** @@ -14219,6 +14227,14 @@ GLProgram : function ( */ cc.ShaderCache = { +/** + * @method notifyAllGLProgramsCreated + */ +notifyAllGLProgramsCreated : function ( +) +{ +}, + /** * @method loadDefaultGLPrograms */ diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js index 29e32d4a3b..0752bfef95 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_dragonbones_auto_api.js @@ -1565,6 +1565,24 @@ float return dragonBones::TextureAtlasData; }, +/** + * @method destroyInstance + */ +destroyInstance : function ( +) +{ +}, + +/** + * @method getInstance + * @return {dragonBones::CCFactory} + */ +getInstance : function ( +) +{ + return dragonBones::CCFactory; +}, + /** * @method CCFactory * @constructor 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 10e1bd3fde..ba6e84e40f 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -1197,23 +1197,38 @@ bool js_register_cocos2dx_Touch(se::Object* obj) se::Object* __jsb_cocos2d_Event_proto = nullptr; se::Class* __jsb_cocos2d_Event_class = nullptr; -static bool js_cocos2dx_Event_isStopped(se::State& s) +static bool js_cocos2dx_Event_reset(se::State& s) { cocos2d::Event* cobj = (cocos2d::Event*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_isStopped : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_reset : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; if (argc == 0) { - bool result = cobj->isStopped(); - ok &= boolean_to_seval(result, &s.rval()); - SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_isStopped : Error processing arguments"); + cobj->reset(); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_cocos2dx_Event_isStopped) +SE_BIND_FUNC(js_cocos2dx_Event_reset) + +static bool js_cocos2dx_Event_getCurrentTarget(se::State& s) +{ + cocos2d::Event* cobj = (cocos2d::Event*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_getCurrentTarget : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cocos2d::Node* result = cobj->getCurrentTarget(); + ok &= native_ptr_to_seval((cocos2d::Node*)result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_getCurrentTarget : 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_Event_getCurrentTarget) static bool js_cocos2dx_Event_getType(se::State& s) { @@ -1233,23 +1248,23 @@ static bool js_cocos2dx_Event_getType(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Event_getType) -static bool js_cocos2dx_Event_getCurrentTarget(se::State& s) +static bool js_cocos2dx_Event_isStopped(se::State& s) { cocos2d::Event* cobj = (cocos2d::Event*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_getCurrentTarget : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_Event_isStopped : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - cocos2d::Node* result = cobj->getCurrentTarget(); - ok &= native_ptr_to_seval((cocos2d::Node*)result, &s.rval()); - SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_getCurrentTarget : Error processing arguments"); + bool result = cobj->isStopped(); + ok &= boolean_to_seval(result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_Event_isStopped : 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_Event_getCurrentTarget) +SE_BIND_FUNC(js_cocos2dx_Event_isStopped) static bool js_cocos2dx_Event_stopPropagation(se::State& s) { @@ -1300,9 +1315,10 @@ bool js_register_cocos2dx_Event(se::Object* obj) { auto cls = se::Class::create("Event", obj, nullptr, _SE(js_cocos2dx_Event_constructor)); - cls->defineFunction("isStopped", _SE(js_cocos2dx_Event_isStopped)); - cls->defineFunction("getType", _SE(js_cocos2dx_Event_getType)); + cls->defineFunction("reset", _SE(js_cocos2dx_Event_reset)); cls->defineFunction("getCurrentTarget", _SE(js_cocos2dx_Event_getCurrentTarget)); + cls->defineFunction("getType", _SE(js_cocos2dx_Event_getType)); + cls->defineFunction("isStopped", _SE(js_cocos2dx_Event_isStopped)); cls->defineFunction("stopPropagation", _SE(js_cocos2dx_Event_stopPropagation)); cls->defineFinalizeFunction(_SE(js_cocos2d_Event_finalize)); cls->install(); @@ -32596,6 +32612,21 @@ bool js_register_cocos2dx_GLProgram(se::Object* obj) se::Object* __jsb_cocos2d_GLProgramCache_proto = nullptr; se::Class* __jsb_cocos2d_GLProgramCache_class = nullptr; +static bool js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated(se::State& s) +{ + cocos2d::GLProgramCache* cobj = (cocos2d::GLProgramCache*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->notifyAllGLProgramsCreated(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated) + static bool js_cocos2dx_GLProgramCache_loadDefaultGLPrograms(se::State& s) { cocos2d::GLProgramCache* cobj = (cocos2d::GLProgramCache*)s.nativeThisObject(); @@ -32743,6 +32774,7 @@ bool js_register_cocos2dx_GLProgramCache(se::Object* obj) { auto cls = se::Class::create("ShaderCache", obj, nullptr, _SE(js_cocos2dx_GLProgramCache_constructor)); + cls->defineFunction("notifyAllGLProgramsCreated", _SE(js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated)); cls->defineFunction("loadDefaultShaders", _SE(js_cocos2dx_GLProgramCache_loadDefaultGLPrograms)); cls->defineFunction("reloadDefaultGLProgramsRelativeToLights", _SE(js_cocos2dx_GLProgramCache_reloadDefaultGLProgramsRelativeToLights)); cls->defineFunction("addProgram", _SE(js_cocos2dx_GLProgramCache_addGLProgram)); 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 32d37ce5aa..86ef8a48de 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -68,9 +68,10 @@ extern se::Class* __jsb_cocos2d_Event_class; bool js_register_cocos2d_Event(se::Object* obj); bool register_all_cocos2dx(se::Object* obj); -SE_DECLARE_FUNC(js_cocos2dx_Event_isStopped); -SE_DECLARE_FUNC(js_cocos2dx_Event_getType); +SE_DECLARE_FUNC(js_cocos2dx_Event_reset); SE_DECLARE_FUNC(js_cocos2dx_Event_getCurrentTarget); +SE_DECLARE_FUNC(js_cocos2dx_Event_getType); +SE_DECLARE_FUNC(js_cocos2dx_Event_isStopped); SE_DECLARE_FUNC(js_cocos2dx_Event_stopPropagation); SE_DECLARE_FUNC(js_cocos2dx_Event_Event); @@ -2127,6 +2128,7 @@ extern se::Class* __jsb_cocos2d_GLProgramCache_class; bool js_register_cocos2d_GLProgramCache(se::Object* obj); bool register_all_cocos2dx(se::Object* obj); +SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_notifyAllGLProgramsCreated); SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_loadDefaultGLPrograms); SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_reloadDefaultGLProgramsRelativeToLights); SE_DECLARE_FUNC(js_cocos2dx_GLProgramCache_addGLProgram); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp index 63482ba83d..b2299c07b2 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.cpp @@ -4924,6 +4924,35 @@ static bool js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData(se::State& s } SE_BIND_FUNC(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData) +static bool js_cocos2dx_dragonbones_CCFactory_destroyInstance(se::State& s) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + dragonBones::CCFactory::destroyInstance(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_dragonbones_CCFactory_destroyInstance) + +static bool js_cocos2dx_dragonbones_CCFactory_getInstance(se::State& s) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + dragonBones::CCFactory* result = dragonBones::CCFactory::getInstance(); + ok &= native_ptr_to_seval((dragonBones::CCFactory*)result, &s.rval()); + SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_CCFactory_getInstance : 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_dragonbones_CCFactory_getInstance) + SE_DECLARE_FINALIZE_FUNC(js_dragonBones_CCFactory_finalize) static bool js_cocos2dx_dragonbones_CCFactory_constructor(se::State& s) @@ -4961,6 +4990,8 @@ bool js_register_cocos2dx_dragonbones_CCFactory(se::Object* obj) cls->defineFunction("getSoundEventManater", _SE(js_cocos2dx_dragonbones_CCFactory_getSoundEventManater)); cls->defineFunction("buildArmatureDisplay", _SE(js_cocos2dx_dragonbones_CCFactory_buildArmatureDisplay)); cls->defineFunction("parseTextureAtlasData", _SE(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData)); + cls->defineStaticFunction("destroyInstance", _SE(js_cocos2dx_dragonbones_CCFactory_destroyInstance)); + cls->defineStaticFunction("getInstance", _SE(js_cocos2dx_dragonbones_CCFactory_getInstance)); cls->defineFinalizeFunction(_SE(js_dragonBones_CCFactory_finalize)); cls->install(); JSBClassType::registerClass(cls); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp index 846dabad0f..9091a59ce7 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_dragonbones_auto.hpp @@ -285,5 +285,7 @@ SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getTextureDisplay); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getSoundEventManater); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_buildArmatureDisplay); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_parseTextureAtlasData); +SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_destroyInstance); +SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_getInstance); SE_DECLARE_FUNC(js_cocos2dx_dragonbones_CCFactory_CCFactory); 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 index 1d9db8658a..6b220e2221 100644 --- a/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md +++ b/native/cocos/scripting/js-bindings/docs/JSB2.0-learning-en.md @@ -178,33 +178,45 @@ Under normal circumstances, if CPP object is not a subclass of `cocos2d :: Ref`, ```c++ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ - // The callback of spTrackEntry destruction - auto cleanup = [entry](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { + return; + } + + auto cleanup = [seObj](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->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 - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; - // 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); } }); @@ -221,7 +233,7 @@ In addition, `se::Object` currently supports the manual creation of the followin * 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 +* Uint8 Typed Array Object: Created by `se::Object::createTypedArray`, 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__ @@ -513,6 +525,8 @@ namespace ns { static bool js_SomeClass_finalize(se::State& s) { + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + delete cobj; return true; } SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize) 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 196c64649a..a1f16a1aa1 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 @@ -178,23 +178,38 @@ se::Object 中提供了 root/unroot 方法供开发者调用,root 会把 JS ```c++ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ // spTrackEntry 的销毁回调 - auto cleanup = [entry](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + // 保存 se::Object 指针,用于在下面的 cleanup 函数中释放其内存 + seObj = iter->second; + // Native 对象 entry 的内存已经被释放,因此需要立马解除 Native 对象与 JS 对象的关联。 + // 如果解除引用关系放在下面的 cleanup 函数中处理,有可能触发 se::Object::setPrivateData 中 + // 的断言,因为新生成的 Native 对象的地址可能与当前对象相同,而 cleanup 可能被延迟到帧结束前执行。 + se::NativePtrToObjectMap::erase(iter); + } + else + { + return; + } + + auto cleanup = [seObj](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) 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(); // 解除 mapping 关系 - seObj->unroot(); // unroot,使 JS 对象受 GC 管理 - seObj->decRef(); // 释放 se::Object - } + se->clearException(); + + // 没必要调用 seObj->clearPrivateData ,因为 Native 对象与 JS 对象的引用关系已经在上面被解除。 + // 如果调用,反而会导致把新生成的 Native 对象的引用关系错误解除掉。 + // 设置 seObj 的 privateData 为 nullptr 也无意义,因为在执行 unroot 和 decRef 后, + // 当前 JS 对象即将被回收。 + seObj->unroot(); // unroot,使 JS 对象受 GC 管理 + seObj->decRef(); // 释放 se::Object }; // 确保不再垃圾回收中去操作 JS 引擎的 API @@ -218,7 +233,7 @@ __对象类型__ * 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);` +* Uint8 Typed Array Object : 通过 se::Object::createTypedArray 创建,类似 JS 中的 `var a = new Uint8Array(buffer);` * Array Buffer Object : 通过 se::Object::createArrayBufferObject,类似 JS 中的 `var a = new ArrayBuffer(len);` __手动创建对象的释放__ @@ -504,6 +519,8 @@ namespace ns { static bool js_SomeClass_finalize(se::State& s) { + ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); + delete cobj; return true; } SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize) diff --git a/native/cocos/scripting/js-bindings/jswrapper/Value.cpp b/native/cocos/scripting/js-bindings/jswrapper/Value.cpp index 81f7f2574c..019d05d688 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/Value.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/Value.cpp @@ -510,12 +510,8 @@ namespace se { } else if (_type == Type::Number) { - char tmp[350] = {0}; - double remainder = fmod(_u._number, 1.0); - if (std::abs(remainder) > 0) - snprintf(tmp, sizeof(tmp), "%lf", _u._number); - else - snprintf(tmp, sizeof(tmp), "%d", (int32_t)_u._number); + char tmp[50] = {0}; + snprintf(tmp, sizeof(tmp), "%.17g", _u._number); ret = tmp; } else if (_type == Type::Object) diff --git a/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h index cd809cbe54..dd9572e914 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/chakracore/HelperMacros.h @@ -86,6 +86,11 @@ void funcName##Registry(void* nativeThisObject); +// NOTE: se::Object::createObjectWithClass(cls) will return a se::Object pointer which is watched by garbage collector. +// If there is a '_ctor' function of current class, '_property.toObject->call(...)' will be invoked which is an operation that may +// make garbage collector to mark the created JS object as a garbage and set it to an invalid state. +// If this happens, crash will be triggered. So please take care of the value returned from se::Object::createObjectWithClass. +// HOW TO FIX: Use a rooted se::Value to save the se::Object poiner returned by se::Object::createObjectWithClass. #define SE_BIND_CTOR(funcName, cls, finalizeCb) \ JsValueRef funcName##Registry(JsValueRef _callee, bool _isConstructCall, JsValueRef* _argv, unsigned short argc, void* _callbackState) \ { \ @@ -94,7 +99,8 @@ bool ret = true; \ se::ValueArray args; \ se::internal::jsToSeArgs(argc, _argv+1, &args); \ - se::Object* thisObject = se::Object::createObjectWithClass(cls); \ + se::Value thisVal(se::Object::createObjectWithClass(cls), true); \ + se::Object* thisObject = thisVal.toObject(); \ JsValueRef _jsRet = thisObject->_getJSObject(); \ se::State state(thisObject, args); \ ret = funcName(state); \ diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h b/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h index 61e689e207..d4fe073c67 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/HelperMacros.h @@ -90,13 +90,19 @@ void funcName##Registry(JSObjectRef _obj); +// NOTE: se::Object::createObjectWithClass(cls) will return a se::Object pointer which is watched by garbage collector. +// If there is a '_ctor' function of current class, '_property.toObject->call(...)' will be invoked which is an operation that may +// make garbage collector to mark the created JS object as a garbage and set it to an invalid state. +// If this happens, crash will be triggered. So please take care of the value returned from se::Object::createObjectWithClass. +// HOW TO FIX: Use a rooted se::Value to save the se::Object poiner returned by se::Object::createObjectWithClass. #define SE_BIND_CTOR(funcName, cls, finalizeCb) \ JSObjectRef funcName##Registry(JSContextRef _cx, JSObjectRef _constructor, size_t argc, const JSValueRef _argv[], JSValueRef* _exception) \ { \ bool ret = true; \ se::ValueArray args; \ se::internal::jsToSeArgs(_cx, argc, _argv, &args); \ - se::Object* thisObject = se::Object::createObjectWithClass(cls); \ + se::Value thisVal(se::Object::createObjectWithClass(cls), true); \ + se::Object* thisObject = thisVal.toObject(); \ JSValueRef _jsRet = JSValueMakeUndefined(_cx); \ se::State state(thisObject, args); \ ret = funcName(state); \ diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp index f5e0f098c7..70b2876036 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Object.cpp @@ -293,7 +293,9 @@ namespace se { Value func; bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty(typedArrayCtor, &func); - if (ok && func.isObject() && func.toObject()->isFunction()) + // On <= iOS 9, typed array constructor is an object rather than a function. + // Therefore, don't check whether typed array constructor is a function here. + if (ok && func.isObject()/* && func.toObject()->isFunction() */) { JSValueRef exception = nullptr; JSObjectRef ret = JSObjectCallAsConstructor(__cx, func.toObject()->_obj, 1, &arr->_obj, &exception); diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp index d79594fbbf..58bf0fb6fd 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/ScriptEngine.cpp @@ -355,7 +355,9 @@ namespace se { ScriptEngine::ExceptionInfo ScriptEngine::_formatException(JSValueRef exception) { ExceptionInfo ret; - internal::forceConvertJsValueToStdString(_cx, exception, &ret.message); + + // Ignore Exception in forceConvertJsValueToStdString invocation to avoid infinite loop. + internal::forceConvertJsValueToStdString(_cx, exception, &ret.message, true); JSType type = JSValueGetType(_cx, exception); diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp index 2c63c705e9..79eec58543 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.cpp @@ -218,20 +218,27 @@ namespace se { } } - void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret) + void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret, bool ignoreException/* = false */) { JSValueRef exception = nullptr; JSStringRef jsstr = JSValueToStringCopy(cx, jsval, &exception); if (exception != nullptr) { - ScriptEngine::getInstance()->_clearException(exception); + // NOTE: ignoreException is true in ScriptEngine::_formatException because it's already in the _clearException process. + // Adds this flag to avoid infinite loop of _clearException -> _formatException -> forceConvertJsValueToStdString -> _clearException -> ... + if (!ignoreException) + { + ScriptEngine::getInstance()->_clearException(exception); + } ret->clear(); } else { jsStringToStdString(cx, jsstr, ret); } - JSStringRelease(jsstr); + + if (jsstr != nullptr) + JSStringRelease(jsstr); } void jsStringToStdString(JSContextRef cx, JSStringRef jsStr, std::string* ret) diff --git a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp index 7e0f424fdc..b81133c46c 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp +++ b/native/cocos/scripting/js-bindings/jswrapper/jsc/Utils.hpp @@ -51,7 +51,7 @@ namespace se { void jsToSeValue(JSContextRef cx, JSValueRef jsval, Value* v); void seToJsValue(JSContextRef cx, const Value& v, JSValueRef* jsval); - void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret); + void forceConvertJsValueToStdString(JSContextRef cx, JSValueRef jsval, std::string* ret, bool ignoreException = false); void jsStringToStdString(JSContextRef cx, JSStringRef jsStr, std::string* ret); bool hasPrivate(JSObjectRef obj); diff --git a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp index af09fcb888..79c08e24d7 100644 --- a/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/scripting/js-bindings/jswrapper/v8/Object.cpp @@ -604,67 +604,6 @@ namespace se { return ret.IsJust() && ret.FromJust(); } -// void Object::getAsFloat32Array(float **ptr, unsigned int *length) { -// float *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// len = myarr->Length(); -// pt = (float *) ((char *) myarr->Buffer()->GetContents().Data() + myarr->ByteOffset()); -// -// *length = len; -// *ptr = pt; -// } -// -// void Object::getAsUint8Array(unsigned char **ptr, unsigned int *length) { -// unsigned char *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// -// len = myarr->Length(); -// pt = (unsigned char *) myarr->Buffer()->GetContents().Data() + myarr->ByteOffset(); -// -// *length = len; -// *ptr = pt; -// } -// -// void Object::getAsUint16Array(unsigned short **ptr, unsigned int *length) { -// unsigned short *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// -// len = myarr->Length(); -// pt = (unsigned short *) myarr->Buffer()->GetContents().Data(); -// -// *length = len; -// *ptr = pt; -// } -// -// void Object::getAsUint32Array(unsigned int **ptr, unsigned int *length) { -// unsigned int *pt; -// unsigned int len; -// -// v8::Local value = _obj.handle(__isolate); -// -// v8::Local myarr = _obj.handle(__isolate).As(); -// -// len = myarr->Length(); -// -// //ArrayBuffer::Contents float_c=pt=myarr->Buffer()->GetContents(); -// pt = (unsigned int *) myarr->Buffer()->GetContents().Data(); -// -// *length = len; -// *ptr = pt; -// } - bool Object::getAllKeys(std::vector* allKeys) const { assert(allKeys != nullptr); diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index ffbb6f3534..efe005dae8 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -60,14 +60,28 @@ void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) return; } + // NOTE: If target isn't created from JS, we should return directly here. + // When JS invokes getter method, we should hack the getter method to invoke jsb.registerNativeRef. + // For example, you could refer to jsb_cocos2d.js, there are some code like: + /* + cc.TMXLayer.prototype._getTileAt = cc.TMXLayer.prototype.getTileAt; + cc.TMXLayer.prototype.getTileAt = function(x, y){ + var pos = y !== undefined ? cc.p(x, y) : x; + var ret = this._getTileAt(pos); + jsb.registerNativeRef(this, ret); // Re-attach the target since ret is created in C++ and retainScriptObject failed. + return ret; + }; + */ auto iterTarget = se::NativePtrToObjectMap::find(target); if (iterTarget == se::NativePtrToObjectMap::end()) { return; } + assert(!se::ScriptEngine::getInstance()->isGarbageCollecting()); se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; + iterOwner->second->attachObject(iterTarget->second); } diff --git a/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp index 3bc2ca3a09..3700f5632a 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_box2d_manual.cpp @@ -1106,29 +1106,40 @@ bool register_all_box2d_manual(se::Object* obj) b2SetObjectDestroyNotifier([](void* obj, b2ObjectType type, const char* typeName){ - std::string typeNameStr = typeName; - auto cleanup = [obj, typeNameStr](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(obj); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { +// CCLOG("Didn't find %s, %p in map", typeName, obj); +// assert(false); + return; + } + + std::string typeNameStr = typeName; + auto cleanup = [seObj, typeNameStr](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(obj); - if (iter != se::NativePtrToObjectMap::end()) - { -// CCLOG("%s, %p was recycled!", typeNameStr.c_str(), obj); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); - seObj->unroot(); - seObj->decRef(); - } - else - { -// CCLOG("Didn't find %s, %p in map", typeNameStr.c_str(), obj); -// assert(false); - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index 59573bcb9c..22f682fa93 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -43,6 +43,8 @@ #include "storage/local-storage/LocalStorage.h" #include "cocos2d.h" +#include "renderer/CCGLProgramStateCache.h" + using namespace cocos2d; static bool jsb_cocos2dx_empty_func(se::State& s) @@ -878,8 +880,14 @@ static void onAfterDispatchTouchEvent(Event* event) for (auto&& touch : touches) { auto iter = se::NativePtrToObjectMap::find(touch); - assert(iter != se::NativePtrToObjectMap::end()); - iter->second->unroot(); + if (iter != se::NativePtrToObjectMap::end()) + { + iter->second->unroot(); + } + else + { + CCLOGWARN("Could not find touch %p, it's possible while restarting game and not all touches are released!", touch); + } } } } @@ -931,6 +939,89 @@ static void onTextureDestroy(TextureCache* cache, Texture2D* texture) } } +static void onGLProgramCreate(GLProgramCache* cache, GLProgram* program) +{ + se::AutoHandleScope hs; + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value val; + bool fromCache = false; + native_ptr_to_seval(program, __jsb_cocos2d_GLProgram_class, &val, &fromCache); + if (!fromCache && val.isObject()) + { + iterOwner->second->attachObject(val.toObject()); + } + else + { + assert(false); + } +} + +static void onGLProgramDestroy(GLProgramCache* cache, GLProgram* program) +{ + se::AutoHandleScope hs; + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value val; + bool fromCache = false; + native_ptr_to_seval(program, __jsb_cocos2d_GLProgram_class, &val, &fromCache); + if (fromCache && val.isObject()) + { + iterOwner->second->detachObject(val.toObject()); + } + else + { + assert(false); + } +} + +static void onGLProgramStateCreate(GLProgramStateCache* cache, GLProgramState* state) +{ + se::AutoHandleScope hs; + // NOTE: GLProgramStateCache is a private class in cocos2dx, it isn't included in cocos2d.h and also didn't expose to JS + // Since it's a singleton class, we could attach 'state' argument to global object instead. + se::Object* global = se::ScriptEngine::getInstance()->getGlobalObject(); + se::Value val; + bool fromCache = false; + native_ptr_to_seval(state, __jsb_cocos2d_GLProgramState_class, &val, &fromCache); + if (!fromCache && val.isObject()) + { + global->attachObject(val.toObject()); + } + else + { + assert(false); + } +} + +static void onGLProgramStateDestroy(GLProgramStateCache* cache, GLProgramState* state) +{ + se::AutoHandleScope hs; + // NOTE: 'state' argument is attached to global object, therefore we need to detach it from global object. + se::Object* global = se::ScriptEngine::getInstance()->getGlobalObject(); + se::Value val; + bool fromCache = false; + native_ptr_to_seval(state, __jsb_cocos2d_GLProgramState_class, &val, &fromCache); + if (fromCache && val.isObject()) + { + global->detachObject(val.toObject()); + } + else + { + assert(false); + } +} + static bool register_eventlistener(se::Object* obj) { se::Value v; @@ -962,12 +1053,6 @@ static bool register_eventlistener(se::Object* obj) assert(v.isObject()); v.toObject()->defineFunction("create", _SE(js_EventListenerCustom_create)); - Director::getInstance()->getEventDispatcher()->setBeforeDispatchEventHook(Event::Type::TOUCH, onBeforeDispatchTouchEvent); - Director::getInstance()->getEventDispatcher()->setAfterDispatchEventHook(Event::Type::TOUCH, onAfterDispatchTouchEvent); - - Director::getInstance()->getTextureCache()->setTextureCreateHook(onTextureCreate); - Director::getInstance()->getTextureCache()->setTextureDestroyHook(onTextureDestroy); - se::ScriptEngine::getInstance()->clearException(); return true; @@ -1488,11 +1573,20 @@ static bool js_cocos2dx_CallFunc_create(se::State& s) se::Object* jsobj = se::Object::createObjectWithClass(__jsb_cocos2d_CallFuncN_class); jsobj->setPrivateData(ret); + // Assign jsobj to jsVal and auto root it to avoid jsobj be swept by GC immediately. + // Because there is "jsobj->attachObject(funcVal.toObject());" in "js_cocos2dx_CallFunc_init" function. + // attachObject will do a function invocation which may mark 'jsobj' into an invalid state but without + // invoking CallFuncN's finalize callback immediately. + // AddressSanitizer in Xcode will prompt: heap-use-after-free on address. + se::Value jsVal; + jsVal.setObject(jsobj, true); // Pass true to indicate auto root / unroot by jsVal + if (js_cocos2dx_CallFunc_init(ret, jsobj, args)) { - s.rval().setObject(jsobj); + s.rval() = std::move(jsVal); return true; } + SE_REPORT_ERROR("js_cocos2dx_CallFunc_create: initWithFunction failed!"); return false; } @@ -2011,6 +2105,19 @@ bool register_all_cocos2dx_manual(se::Object* obj) register_empty_retain_release(obj); register_texture2d_manual(obj); register_tilemap_manual(obj); + + Director::getInstance()->getEventDispatcher()->setBeforeDispatchEventHook(Event::Type::TOUCH, onBeforeDispatchTouchEvent); + Director::getInstance()->getEventDispatcher()->setAfterDispatchEventHook(Event::Type::TOUCH, onAfterDispatchTouchEvent); + + TextureCache::setTextureCreateHook(onTextureCreate); + TextureCache::setTextureDestroyHook(onTextureDestroy); + + GLProgramCache::setGLProgramCreateHook(onGLProgramCreate); + GLProgramCache::setGLProgramDestroyHook(onGLProgramDestroy); + + GLProgramStateCache::setGLProgramStateCreateHook(onGLProgramStateCreate); + GLProgramStateCache::setGLProgramStateDestroyHook(onGLProgramStateDestroy); + return true; } diff --git a/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp index 810bf04263..9641f0628f 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_dragonbones_manual.cpp @@ -35,7 +35,6 @@ using namespace cocos2d; - static bool js_cocos2dx_dragonbones_Armature_getAnimation(se::State& s) { if (s.args().size() == 0) @@ -321,8 +320,8 @@ static bool js_cocos2dx_dragonbones_CCFactory_getFactory(se::State& s) { if (s.args().size() == 0) { - const dragonBones::CCFactory& ret = dragonBones::CCFactory::factory; - bool ok = native_ptr_to_rooted_seval((dragonBones::CCFactory*)&ret, __jsb_dragonBones_CCFactory_class, &s.rval()); + auto ret = dragonBones::CCFactory::getInstance(); + bool ok = native_ptr_to_rooted_seval(ret, __jsb_dragonBones_CCFactory_class, &s.rval()); SE_PRECONDITION2(ok, false, "Convert dragonBones::CCFactory to se::Value failed!"); return true; } @@ -531,28 +530,42 @@ bool register_all_dragonbones_manual(se::Object* obj) dragonBones::BaseObject::setObjectRecycleOrDestroyCallback([](dragonBones::BaseObject* obj, int type){ -// std::string typeName = typeid(*obj).name(); - auto cleanup = [=](){ - if (!se::ScriptEngine::getInstance()->isValid()) + std::string typeName = typeid(*obj).name(); + + se::Object* seObj = nullptr; + + auto iter = se::NativePtrToObjectMap::find(obj); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { + // CCLOG("Didn't find %s, %p in map", typeName, obj); + // assert(false); + return; + } + + std::string typeNameStr = typeName; + auto cleanup = [seObj, typeNameStr](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(obj); - if (iter != se::NativePtrToObjectMap::end()) - { -// CCLOG("%s: %p was recycled!", typeName.c_str(), obj); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); - seObj->unroot(); - seObj->decRef(); - } - else - { -// CCLOG("Didn't find %s, %p in map", typeName.c_str(), obj); - // assert(false); - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) @@ -565,6 +578,65 @@ bool register_all_dragonbones_manual(se::Object* obj) } }); + se::ScriptEngine::getInstance()->addAfterCleanupHook([](){ + + // Destroy CCFactory singlton. + dragonBones::CCFactory::destroyInstance(); + + // World clock is a static variable and needs to be cleared and reset. + dragonBones::WorldClock::clock.clear(); + dragonBones::WorldClock::clock.time = 0.0f; + dragonBones::WorldClock::clock.timeScale = 1.0f; + + // Copy the dragonbones object vector since vector element will be deleted in BaseObject destructor. + std::vector allDragonBonesObjects = dragonBones::BaseObject::getAllObjects(); + SE_LOGD("Starting to cleanup dragonbones object, count: %d\n", (int)allDragonBonesObjects.size()); + // Clear dragonBones::Armature objects those are not in the pool because + // dragonBones::Armature controls life cycle for lots of other objects, + // so it needs to be disposed first. + for (auto dbObj : allDragonBonesObjects) + { + if (dynamic_cast(dbObj) != nullptr && !dbObj->isInPool()) + { +// SE_LOGD("1. Force delete not in pool DragonBones Armature object: %s, %p\n", typeid(*dbObj).name(), dbObj); + delete dbObj; + } + } + + // After disposing dragonBones::Armature objects, there will be lots of other kinds of objects returned to pool. + // Therefore, we clean object pool here. + dragonBones::BaseObject::clearPool(0); + + // Copy the dragonbones object vector again. + allDragonBonesObjects = dragonBones::BaseObject::getAllObjects(); + SE_LOGD("After first cleanup, dragonbones object remained count: %d\n", (int)allDragonBonesObjects.size()); + // Check again whether there are some objects still in pool since the releationship of dragonbones objects is really complex. + for (auto dbObj : allDragonBonesObjects) + { + if (!dbObj->isInPool()) + { +// SE_LOGD("2. Force delete not in pool DragonBones object: %s, %p\n", typeid(*dbObj).name(), dbObj); + delete dbObj; + } + } + + // Clear pool again. + dragonBones::BaseObject::clearPool(0); + + // Don't need to use copy operator since we only print leak object below. + auto& refAllDragonBonesObjects = dragonBones::BaseObject::getAllObjects(); + SE_LOGD("After second cleanup, dragonbones object remained count: %d\n", (int)refAllDragonBonesObjects.size()); + + // Print leak objects + for (auto dbObj : refAllDragonBonesObjects) + { + SE_LOGD("Leak dragonbones object: %s, %p\n", typeid(*dbObj).name(), dbObj); + } + + // If there're leak objects, clear vector should be done for restarting game. + refAllDragonBonesObjects.clear(); + }); + se::ScriptEngine::getInstance()->clearException(); return true; diff --git a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp index f861c09285..9a47b873c0 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp @@ -843,6 +843,22 @@ static bool js_performance_now(se::State& s) } SE_BIND_FUNC(js_performance_now) +static bool JSB_getJSBindingObjectCount(se::State& s) +{ + size_t size = se::NativePtrToObjectMap::size(); + s.rval().setUlong(size); + return true; +} +SE_BIND_FUNC(JSB_getJSBindingObjectCount) + +static bool JSB_getJSBindingObjectCountNonRefAndCreatedInJS(se::State& s) +{ + size_t size = se::NonRefNativePtrCreatedByCtorMap::size(); + s.rval().setUlong(size); + return true; +} +SE_BIND_FUNC(JSB_getJSBindingObjectCountNonRefAndCreatedInJS) + bool jsb_register_global_variables(se::Object* global) { global->defineFunction("require", _SE(require)); @@ -857,6 +873,8 @@ bool jsb_register_global_variables(se::Object* global) __jscObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect)); __jscObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap)); + __jscObj->defineFunction("getJSBindingObjectCount", _SE(JSB_getJSBindingObjectCount)); + __jscObj->defineFunction("getJSBindingObjectCountNonRefCreatedInJS", _SE(JSB_getJSBindingObjectCountNonRefAndCreatedInJS)); global->defineFunction("__getPlatform", _SE(JSBCore_platform)); global->defineFunction("__getOS", _SE(JSBCore_os)); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp index f5fc4b740f..be5bd5ff42 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_node.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_node.cpp @@ -201,6 +201,38 @@ static const char* SCHEDULE_FUNC_ID_KEY = "__seScheFuncId"; static std::unordered_map> __js_target_schedulekey_map; static std::unordered_map> __js_target_schedule_update_map; +#if COCOS2D_DEBUG > 1 +static void printElementsInTargetSchedulerMap() +{ + SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); + for (const auto& e1 : __js_target_schedulekey_map) + { + uint32_t targetID = e1.first; + const auto& functions = e1.second; + std::string functionIDStr; + if (!functions.empty()) + functionIDStr.append("["); + + for (const auto& fn : functions) + { + assert(fn.second.getFuncId() == fn.first); + assert(fn.second.getTargetId() == targetID); + char idStr[20] = {0}; + snprintf(idStr, sizeof(idStr), "%u", fn.first); + functionIDStr.append(idStr); + functionIDStr.append(","); + } + if (!functions.empty()) + { + functionIDStr = functionIDStr.substr(0, functionIDStr.size()-1); + functionIDStr.append("]"); + } + SE_LOGD("schedule target: %u, functions: %s\n", e1.first, functionIDStr.c_str()); + } + SE_LOGD("-------------------------- \n"); +} +#endif + static bool isScheduleExist(uint32_t jsFuncId, uint32_t jsTargetId, const ScheduleElement** outElement) { bool found = false; @@ -260,7 +292,7 @@ static bool isScheduleExist(const std::string& key, uint32_t jsTargetId, const S return found; } -static void removeSchedule(uint32_t jsFuncId, uint32_t jsTargetId, bool needDetachChild) +static void removeSchedule(const std::string& key, uint32_t jsFuncId, uint32_t jsTargetId, bool needDetachChild) { auto funcObjKeyMapIter = __js_target_schedulekey_map.find(jsTargetId); if (funcObjKeyMapIter != __js_target_schedulekey_map.end()) @@ -270,17 +302,20 @@ static void removeSchedule(uint32_t jsFuncId, uint32_t jsTargetId, bool needDeta auto iter = funcMap.find(jsFuncId); if (iter != funcMap.end()) { - se::Object* target = iter->second.getTarget(); - se::Object* func = iter->second.getFunc(); - if (needDetachChild) + if (iter->second.getKey() == key) { - target->detachObject(func); + se::Object* target = iter->second.getTarget(); + se::Object* func = iter->second.getFunc(); + if (needDetachChild) + { + target->detachObject(func); + } + + func->decRef(); + target->decRef(); + + funcMap.erase(iter); } - - func->decRef(); - target->decRef(); - - funcMap.erase(iter); } if (funcMap.empty()) @@ -445,22 +480,25 @@ static bool isTargetExistInScheduler(uint32_t targetId) class UnscheduleNotifier { public: - UnscheduleNotifier(uint32_t funcId, uint32_t targetId) - : _funcId(funcId) + UnscheduleNotifier(const std::string& key, uint32_t funcId, uint32_t targetId) + : _key(key) + , _funcId(funcId) , _targetId(targetId) { } ~UnscheduleNotifier() { -// SE_LOGD("~UnscheduleNotifier, targetId: %u, funcId: %u\n", _targetId, _funcId); - +#if COCOS2D_DEBUG > 1 + SE_LOGD("~UnscheduleNotifier, key: %s, targetId: %u, funcId: %u\n", _key.c_str(), _targetId, _funcId); +#endif se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - removeSchedule(_funcId, _targetId, false); + removeSchedule(_key, _funcId, _targetId, false); } private: + std::string _key; uint32_t _funcId; uint32_t _targetId; }; @@ -501,7 +539,7 @@ static bool Scheduler_scheduleCommon(Scheduler* scheduler, const se::Value& jsTh if (found && !key.empty()) { - removeSchedule(funcId, targetId, true); + removeSchedule(key, funcId, targetId, true); scheduler->unschedule(key, reinterpret_cast(targetId)); } } @@ -534,7 +572,7 @@ static bool Scheduler_scheduleCommon(Scheduler* scheduler, const se::Value& jsTh se::Object* target = jsThis.toObject(); insertSchedule(funcId, targetId, ScheduleElement(target, jsFunc.toObject(), key, targetId, funcId)); - std::shared_ptr unscheduleNotifier = std::make_shared(funcId, targetId); + std::shared_ptr unscheduleNotifier = std::make_shared(key, funcId, targetId); if (toRootTarget) { @@ -840,7 +878,7 @@ static bool Scheduler_unscheduleCommon(Scheduler* scheduler, const se::Value& js if (found && !key.empty()) { - removeSchedule(funcId, targetId, true); + removeSchedule(key, funcId, targetId, true); scheduler->unschedule(key, reinterpret_cast(targetId)); } else @@ -1157,17 +1195,13 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) { const auto& args = s.args(); int argc = (int)args.size(); -#if 0//COCOS2D_DEBUG > 0 - SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size()); - for (const auto& e1 : __js_target_schedulekey_map) - { - SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size()); - } - SE_LOGD("-------------------------- \n"); +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_schedule begin ...\n"); + printElementsInTargetSchedulerMap(); #endif // - if (argc >= 4) + if (argc >= 3) { Scheduler* cobj = (Scheduler*)s.nativeThisObject(); @@ -1185,7 +1219,6 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) jsThis = args[0]; } - bool isBindedObject = jsThis.toObject()->getPrivateData() != nullptr; // SE_LOGD("%s, is binded object: %s\n", __FUNCTION__, isBindedObject ? "true" : "false"); @@ -1200,33 +1233,45 @@ static bool js_cocos2dx_Scheduler_schedule(se::State& s) ok = seval_to_float(args[2], &interval); SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed"); - - if (argc == 4) + if (argc == 4 && args[3].isBoolean()) { // callback, target, interval, paused - ok = seval_to_boolean(args[3], &isPaused); - SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); + isPaused = args[3].toBoolean(); } - else if (argc >= 6) + else { // callback, target, interval, repeat, delay, paused - // repeat - ok = seval_to_uint32(args[3], &repeat); - SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed"); + if (argc >= 4) + { + // repeat + ok = seval_to_uint32(args[3], &repeat); + SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed"); + } - // delay - ok = seval_to_float(args[4], &delay); - SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed"); + if (argc >= 5) + { + // delay + ok = seval_to_float(args[4], &delay); + SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed"); + } - // isPaused - ok = seval_to_boolean(args[5], &isPaused); - SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); + if (argc >= 6) + { + // isPaused + ok = seval_to_boolean(args[5], &isPaused); + SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed"); + } } - return Scheduler_scheduleCommon(cobj, jsThis, jsFunc, interval, repeat, delay, isPaused, !isBindedObject, "cc.Scheduler.schedule"); + bool ret = Scheduler_scheduleCommon(cobj, jsThis, jsFunc, interval, repeat, delay, isPaused, !isBindedObject, "cc.Scheduler.schedule"); +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_schedule end ...\n"); + printElementsInTargetSchedulerMap(); +#endif + return ret; } - SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=2"); + SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=3"); return false; } SE_BIND_FUNC(js_cocos2dx_Scheduler_schedule) @@ -1234,6 +1279,10 @@ SE_BIND_FUNC(js_cocos2dx_Scheduler_schedule) static bool js_cocos2dx_Scheduler_unschedule(se::State& s) { +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_unschedule begin ...\n"); + printElementsInTargetSchedulerMap(); +#endif const auto& args = s.args(); int argc = (int)args.size(); @@ -1252,7 +1301,12 @@ static bool js_cocos2dx_Scheduler_unschedule(se::State& s) jsTarget = args[0]; } Scheduler* cobj = (Scheduler*)s.nativeThisObject(); - return Scheduler_unscheduleCommon(cobj, jsTarget, jsFuncOrKey); + bool ret = Scheduler_unscheduleCommon(cobj, jsTarget, jsFuncOrKey); +#if COCOS2D_DEBUG > 1 + SE_LOGD("js_cocos2dx_Scheduler_unschedule end ...\n"); + printElementsInTargetSchedulerMap(); +#endif + return ret; } SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=2"); return false; @@ -1421,6 +1475,74 @@ static bool js_cocos2dx_Scheduler_isTargetPaused(se::State& s) } SE_BIND_FUNC(js_cocos2dx_Scheduler_isTargetPaused) +static void fillScheduleTargetArray(se::Object* ret, const std::set& targets) +{ + uint32_t index = 0; + for (void* target : targets) + { + uint32_t targetID = (uint32_t)reinterpret_cast(target); + auto iter = __js_target_schedulekey_map.find(targetID); + if (iter != __js_target_schedulekey_map.end()) + { + se::Object* targetObj = iter->second.begin()->second.getTarget(); + ret->setArrayElement(index, se::Value(targetObj)); + ++index; + } + else + { + auto updateIter = __js_target_schedule_update_map.find(targetID); + if (updateIter != __js_target_schedule_update_map.end()) + { + se::Object* targetObj = updateIter->second.second; + ret->setArrayElement(index, se::Value(targetObj)); + ++index; + } + } + } +} + +static bool js_cocos2dx_Scheduler_pauseAllTargets(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc == 0) + { + Scheduler* cobj = (Scheduler*)s.nativeThisObject(); + std::set targets = cobj->pauseAllTargets(); + se::HandleObject ret(se::Object::createArrayObject((uint32_t)targets.size())); + fillScheduleTargetArray(ret.get(), targets); + s.rval().setObject(ret); + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Scheduler_pauseAllTargets) + +static bool js_cocos2dx_Scheduler_pauseAllTargetsWithMinPriority(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc == 1) + { + Scheduler* cobj = (Scheduler*)s.nativeThisObject(); + int minPriority = 0; + bool ok = seval_to_int32(args[0], &minPriority); + SE_PRECONDITION2(ok, false, "Converting 'minPriority' argument failed"); + + std::set targets = cobj->pauseAllTargetsWithMinPriority(minPriority); + se::HandleObject ret(se::Object::createArrayObject((uint32_t)targets.size())); + fillScheduleTargetArray(ret.get(), targets); + s.rval().setObject(ret); + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +SE_BIND_FUNC(js_cocos2dx_Scheduler_pauseAllTargetsWithMinPriority) + static void resumeAllSchedulesForTarget(Node* node, se::Object* jsThis) { node->getScheduler()->resumeTarget(jsThis); @@ -1567,6 +1689,8 @@ bool jsb_register_Node_manual(se::Object* global) schedulerProto->defineFunction("pauseTarget", _SE(js_cocos2dx_Scheduler_pauseTarget)); schedulerProto->defineFunction("resumeTarget", _SE(js_cocos2dx_Scheduler_resumeTarget)); schedulerProto->defineFunction("isTargetPaused", _SE(js_cocos2dx_Scheduler_isTargetPaused)); + schedulerProto->defineFunction("pauseAllTargets", _SE(js_cocos2dx_Scheduler_pauseAllTargets)); + schedulerProto->defineFunction("pauseAllTargetsWithMinPriority", _SE(js_cocos2dx_Scheduler_pauseAllTargetsWithMinPriority)); #if STANDALONE_TEST cls->defineFunction("addChild", _SE(Node_addChild)); 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 ec5244d7a9..5e44cce8a1 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_spine_manual.cpp @@ -304,23 +304,37 @@ static bool js_register_spine_TrackEntry(se::Object* obj) __jsb_spine_TrackEntry_proto = cls->getProto(); spTrackEntry_setDisposeCallback([](spTrackEntry* entry){ - auto cleanup = [entry](){ + se::Object* seObj = nullptr; - if (!se::ScriptEngine::getInstance()->isValid()) + auto iter = se::NativePtrToObjectMap::find(entry); + if (iter != se::NativePtrToObjectMap::end()) + { + // Save se::Object pointer for being used in cleanup method. + seObj = iter->second; + // Unmap native and js object since native object was destroyed. + // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later + // since native obj is already released and the new native object may be assigned with + // the same address. + se::NativePtrToObjectMap::erase(iter); + } + else + { + return; + } + + auto cleanup = [seObj](){ + + auto se = se::ScriptEngine::getInstance(); + if (!se->isValid() || se->isInCleanup()) return; se::AutoHandleScope hs; - se::ScriptEngine::getInstance()->clearException(); + se->clearException(); - auto iter = se::NativePtrToObjectMap::find(entry); - if (iter != se::NativePtrToObjectMap::end()) - { - CCLOGINFO("spTrackEntry %p was recycled!", entry); - se::Object* seObj = iter->second; - seObj->clearPrivateData(); - seObj->unroot(); - seObj->decRef(); - } + // The native <-> JS mapping was cleared in the callback above. + // seObj->clearPrivateData isn't needed since the JS object will be garbage collected after unroot and decRef. + seObj->unroot(); + seObj->decRef(); }; if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp b/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp index c982db0dfb..599ab55fb2 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_websocket.cpp @@ -67,7 +67,6 @@ se::Class* __jsb_WebSocket_class = nullptr; class JSB_WebSocketDelegate : public Ref, public WebSocket::Delegate { public: - JSB_WebSocketDelegate() { } @@ -213,6 +212,10 @@ public: SE_REPORT_ERROR("Can't get onclose function!"); } + // Websocket instance is attached to global object in 'WebSocket_close' + // It's safe to detach it here since JS 'onclose' method has been already invoked. + se::ScriptEngine::getInstance()->getGlobalObject()->detachObject(wsObj); + } while(false); ws->release(); @@ -455,6 +458,15 @@ static bool WebSocket_close(se::State& s) { WebSocket* cobj = (WebSocket*)s.nativeThisObject(); cobj->closeAsync(); + // Attach current WebSocket instance to global object to prevent WebSocket instance + // being garbage collected after "ws.close(); ws = null;" + // There is a state that current WebSocket JS instance is being garbaged but its finalize + // callback has not be invoked. Then in "JSB_WebSocketDelegate::onClose", se::Object is + // still be able to be found and while invoking JS 'onclose' method, crash will happen since + // JS instance is invalid and is going to be collected. This bug is easiler reproduced on iOS + // because JavaScriptCore is more GC sensitive. + // Please note that we need to detach it from global object in "JSB_WebSocketDelegate::onClose". + se::ScriptEngine::getInstance()->getGlobalObject()->attachObject(s.thisObject()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 0", argc); diff --git a/native/cocos/scripting/js-bindings/script/jsb_boot.js b/native/cocos/scripting/js-bindings/script/jsb_boot.js index 37b01a4ca4..fa79759fa1 100755 --- a/native/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/native/cocos/scripting/js-bindings/script/jsb_boot.js @@ -75,6 +75,13 @@ cc.view.getTargetDensityDPI = function() {return cc.macro.DENSITYDPI_DEVICE;}; cc.eventManager = cc.director.getEventDispatcher(); +cc.EventDispatcher.prototype._addCustomListener = cc.EventDispatcher.prototype.addCustomListener; +cc.EventDispatcher.prototype.addCustomListener = function(eventName, callback) { + var ret = this._addCustomListener(eventName, callback); + jsb.registerNativeRef(cc.eventManager, ret); + return ret; +}; + cc.eventManager._resizeListener = cc.eventManager.addCustomListener('window-resize', function () { cc.winSize = cc.director.getWinSize(); cc.visibleRect.init(); @@ -83,6 +90,9 @@ cc.eventManager._resizeListener = cc.eventManager.addCustomListener('window-resi cc.configuration = cc.Configuration.getInstance(); cc.textureCache = cc.director.getTextureCache(); cc.shaderCache = cc.ShaderCache.getInstance(); +// The first time we invoke cc.ShaderCache.getInstance, notifyAllGLProgramsCreated needs to be called. +// It should be invoked only once. +cc.shaderCache.notifyAllGLProgramsCreated(); cc.plistParser = cc.PlistParser.getInstance(); // File utils (Temporary, won't be accessible) diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index bb95284fa8..c21947c1aa 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -24,6 +24,7 @@ // // cocos2d constants // +cc.ENGINE_VERSION = "Cocos2d-x-lite v1.10.0"; // Resolution policies @@ -626,15 +627,45 @@ cc.TMXTiledMap.prototype.allLayers = function(){ length = locChildren.length; for(var i = 0; i< length; i++){ var layer = locChildren[i]; - if(layer && layer instanceof cc.TMXLayer) + if(layer && layer instanceof cc.TMXLayer) { + jsb.registerNativeRef(this, layer); retArr.push(layer); + } } return retArr; }; + +cc.TMXTiledMap.prototype._getLayer = cc.TMXTiledMap.prototype.getLayer; +cc.TMXTiledMap.prototype.getLayer = function(layerName) { + var ret = this._getLayer(layerName); + jsb.registerNativeRef(this, ret); + return ret; +}; + +cc.TMXTiledMap.prototype._getObjectGroup = cc.TMXTiledMap.prototype.getObjectGroup; +cc.TMXTiledMap.prototype.getObjectGroup = function(groupName) { + var ret = this._getObjectGroup(groupName); + jsb.registerNativeRef(this, ret); + return ret; +}; + +cc.TMXTiledMap.prototype._getObjectGroups = cc.TMXTiledMap.prototype.getObjectGroups; +cc.TMXTiledMap.prototype.getObjectGroups = function() { + var ret = this._getObjectGroups(); + if (ret && ret instanceof Array) { + for (var i = 0, len = ret.length; i < len; ++i) { + jsb.registerNativeRef(this, ret[i]); + } + } + return ret; +}; + cc.TMXLayer.prototype._getTileAt = cc.TMXLayer.prototype.getTileAt; cc.TMXLayer.prototype.getTileAt = function(x, y){ var pos = y !== undefined ? cc.p(x, y) : x; - return this._getTileAt(pos); + var ret = this._getTileAt(pos); + jsb.registerNativeRef(this, ret); + return ret; }; cc.TMXLayer.prototype._getTileGIDAt = cc.TMXLayer.prototype.getTileGIDAt; cc.TMXLayer.prototype.getTileGIDAt = function(x, y){ @@ -668,6 +699,31 @@ cc.TMXLayer.prototype.getPositonAt = function(x, y){ cc.TMXLayer.prototype.tileFlagsAt = cc.TMXLayer.prototype.getTileFlagsAt; +cc.TMXObjectGroup.prototype._getObject = cc.TMXObjectGroup.prototype.getObject; +cc.TMXObjectGroup.prototype.getObject = function(objectName) { + var ret = this._getObject(objectName); + jsb.registerNativeRef(this, ret); + return ret; +}; + +cc.TMXObjectGroup.prototype._getObjects = cc.TMXObjectGroup.prototype.getObjects; +cc.TMXObjectGroup.prototype.getObjects = function() { + var ret = this._getObjects(); + if (ret && ret instanceof Array) { + for (var i = 0, len = ret.length; i < len; ++i) { + jsb.registerNativeRef(this, ret[i]); + } + } + return ret; +}; + +cc.TMXObject.prototype._getNode = cc.TMXObject.prototype.getNode; +cc.TMXObject.prototype.getNode = function() { + var ret = this._getNode(); + jsb.registerNativeRef(this, ret); + return ret; +}; + // // setBlendFunc JS API Wrapper // diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js b/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js index 26d9563f37..7c9e56aa8b 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js @@ -61,6 +61,10 @@ if (platform === sys.ANDROID) { } }; + cocosAnalytics.isInited = function() { + return jsb.reflection.callStaticMethod(cls_CAAgent, "isInited", "()Z"); + }; + cocosAnalytics.enableDebug = function(enabled) { jsb.reflection.callStaticMethod(cls_CAAgent, "enableDebug", "(Z)V", @@ -351,6 +355,10 @@ if (platform === sys.ANDROID) { } }; + cocosAnalytics.isInited = function() { + return jsb.reflection.callStaticMethod(cls_CAAgent, "isInited"); + }; + cocosAnalytics.enableDebug = function(enabled) { jsb.reflection.callStaticMethod(cls_CAAgent, "enableDebug:", @@ -619,6 +627,10 @@ if (platform === sys.ANDROID) { console.log("Cocos Analytics module isn't available on this platform!"); }; + cocosAnalytics.isInited = function() { + return false; + }; + cocosAnalytics.enableDebug = function(enabled) { }; diff --git a/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp b/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp index 6a1adae474..815b53ecb5 100644 --- a/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp +++ b/native/extensions/anysdk/js-bindings/manualanysdkbindings.cpp @@ -884,6 +884,15 @@ public: std_map.erase(iter); } } + + static void purge() + { + for (auto& e : std_map) + { + delete e.second; + } + std_map.clear(); + } private: se::Value _jsThis; se::Value _jsFunc; @@ -1614,6 +1623,16 @@ bool register_all_anysdk_manual(se::Object* obj) __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("setResultListener", _SE(jsb_anysdk_framework_ProtocolREC_setResultListener)); __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("removeListener", _SE(jsb_anysdk_framework_ProtocolREC_removeListener)); + se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){ + ProtocolAdsResultListener::purge(); + ProtocolYAPResultListener::purge(); + ProtocolPushActionListener::purge(); + ProtocolUserActionListener::purge(); + ProtocolSocialListener::purge(); + ProtocolRECListener::purge(); + ProtocolCustomListener::purge(); + }); + se::ScriptEngine::getInstance()->clearException(); return true; } 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 3efffd2b51..0fad0a1370 100644 --- a/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp +++ b/native/extensions/anysdk/platform/ios/appstore/js-bindings/manualanysdkbindings.cpp @@ -884,6 +884,15 @@ public: std_map.erase(iter); } } + + static void purge() + { + for (auto& e : std_map) + { + delete e.second; + } + std_map.clear(); + } private: se::Value _jsThis; se::Value _jsFunc; @@ -1614,6 +1623,16 @@ bool register_all_anysdk_manual(se::Object* obj) __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("setResultListener", _SE(jsb_anysdk_framework_ProtocolREC_setResultListener)); __jsb_anysdk_framework_ProtocolREC_proto->defineFunction("removeListener", _SE(jsb_anysdk_framework_ProtocolREC_removeListener)); + se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){ + ProtocolAdsResultListener::purge(); + ProtocolYAPResultListener::purge(); + ProtocolPushActionListener::purge(); + ProtocolUserActionListener::purge(); + ProtocolSocialListener::purge(); + ProtocolRECListener::purge(); + ProtocolCustomListener::purge(); + }); + se::ScriptEngine::getInstance()->clearException(); return true; } diff --git a/native/external/config.json b/native/external/config.json index 374c2c2a60..8179ce9089 100644 --- a/native/external/config.json +++ b/native/external/config.json @@ -1,5 +1,5 @@ { - "version": "v3-deps-53", + "version": "v3-deps-54", "zip_file_size": "114318593", "repo_name": "cocos2d-x-lite-external", "repo_parent": "https://github.com/cocos-creator/" 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 0d6831be5d..d00ea8baf8 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 @@ -118,7 +118,9 @@ 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]; + if (CAAgent.isInited) { + [CAAgent onPause]; + } } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -130,7 +132,9 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } - [CAAgent onResume]; + if (CAAgent.isInited) { + [CAAgent onResume]; + } } - (void)applicationWillTerminate:(UIApplication *)application { 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 0d6831be5d..d00ea8baf8 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 @@ -118,7 +118,9 @@ 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]; + if (CAAgent.isInited) { + [CAAgent onPause]; + } } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -130,7 +132,9 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } - [CAAgent onResume]; + if (CAAgent.isInited) { + [CAAgent onResume]; + } } - (void)applicationWillTerminate:(UIApplication *)application { 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 0d6831be5d..d00ea8baf8 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 @@ -118,7 +118,9 @@ 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]; + if (CAAgent.isInited) { + [CAAgent onPause]; + } } - (void)applicationWillEnterForeground:(UIApplication *)application { @@ -130,7 +132,9 @@ static AppDelegate* s_sharedApplication = nullptr; if (glview == currentView) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); } - [CAAgent onResume]; + if (CAAgent.isInited) { + [CAAgent onResume]; + } } - (void)applicationWillTerminate:(UIApplication *)application { diff --git a/native/tools/tojs/cocos2dx_dragonbones.ini b/native/tools/tojs/cocos2dx_dragonbones.ini index b32c38e458..20932ef8ad 100644 --- a/native/tools/tojs/cocos2dx_dragonbones.ini +++ b/native/tools/tojs/cocos2dx_dragonbones.ini @@ -40,7 +40,7 @@ skip = CCFactory::[loadDragonBonesData loadTextureAtlasData], AnimationData::[cacheFrames addBoneTimeline addSlotTimeline addFFDTimeline getBontTimeline getSlotTimeline getFFDTimeline getBoneTimeline], SkinData::[addSlot getSlot], DBCCSprite::[getPolygonInfoModify draw], - BaseObject::[setObjectRecycleOrDestroyCallback], + BaseObject::[setObjectRecycleOrDestroyCallback isInPool getAllObjects], BoneTimelineData::[*], SlotData::[generateColor], TextureData::[generateRectangle]