From f4e3341115d2ce5f496cb62021112f87d256d15d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 14:57:40 +0800 Subject: [PATCH 01/10] Sync js bindings code from cocos2d-x v3.14 --- .../js-bindings/manual/ScriptingCore.cpp | 12 ++++++--- .../js-bindings/manual/ScriptingCore.h | 22 ++++++++++++--- .../js-bindings/manual/cocos2d_specifics.cpp | 27 +++++++------------ .../jsb_cocos2dx_extension_manual.cpp | 23 +++++++++++++--- .../manual/js_manual_conversions.cpp | 17 +----------- .../manual/js_manual_conversions.h | 1 - .../js-bindings/manual/jsb_opengl_manual.cpp | 8 +++--- .../script/ccui/jsb_ccui_create_apis.js | 10 +++---- .../debugger/actors/utils/ScriptStore.js | 4 +-- .../js-bindings/script/debugger/main.js | 2 +- .../js-bindings/script/debugger/transport.js | 1 - .../script/debugger/webconsole/utils.js | 4 +-- .../cocos/scripting/js-bindings/script/jsb.js | 2 +- .../scripting/js-bindings/script/jsb_boot.js | 6 ++++- .../js-bindings/script/jsb_cocos2d.js | 26 +++++++++--------- .../js-bindings/script/jsb_common.js | 4 +-- .../js-bindings/script/jsb_create_apis.js | 2 +- .../script/physicsSprite/jsb_physicsSprite.js | 22 +++++++++++++++ .../script/studio/jsb_studio_property_apis.js | 22 +++++++++++++++ 19 files changed, 137 insertions(+), 78 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 619c13eb35..a55803a71e 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -553,6 +553,7 @@ bool ScriptingCore::evalString(const char *string) void ScriptingCore::start() { + _engineStartTime = std::chrono::steady_clock::now(); // for now just this createGlobalContext(); } @@ -1593,6 +1594,12 @@ bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, cons return bRet; } +std::chrono::steady_clock::time_point ScriptingCore::getEngineStartTime() const +{ + return _engineStartTime; +} + + bool ScriptingCore::handleKeyboardEvent(void* nativeObj, cocos2d::EventKeyboard::KeyCode keyCode, bool isPressed, cocos2d::Event* event) { JSAutoCompartment ac(_cx, _global->get()); @@ -1606,7 +1613,7 @@ bool ScriptingCore::handleKeyboardEvent(void* nativeObj, cocos2d::EventKeyboard: js_type_class_t *typeClass = js_get_type_from_native((cocos2d::EventKeyboard*)event); jsval args[2] = { int32_to_jsval(_cx, (int32_t)keyCode), - OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(_cx, event, typeClass, "cocos2d::EventKeyboard")) + OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(_cx, event, typeClass)) }; if (isPressed) @@ -2320,7 +2327,6 @@ JSObject* jsb_ref_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, js_ty return obj; } - // don't auto-release, don't retain. JS::RootedObject proto(cx, typeClass->proto.ref()); JS::RootedObject parent(cx, typeClass->parentProto.ref()); JS::RootedObject jsObj(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent)); @@ -2333,7 +2339,7 @@ JSObject* jsb_ref_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, js_ty CCLOG("++++++RETAINED++++++ Cpp(%s): %p - JS: %p", debug, ref, jsObj.get()); #endif // COCOS2D_DEBUG #else - // don't autorelease it + // don't auto-release, don't retain. JS::AddNamedObjectRoot(cx, &newproxy->obj, debug); #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h index 04a5fb7cc3..2a6b0251d3 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h @@ -39,8 +39,9 @@ #include #include +#include -#define ENGINE_VERSION "Cocos2d-JS v3.13" +#define ENGINE_VERSION "Cocos2d-JS v3.14" void js_log(const char *format, ...); @@ -90,6 +91,8 @@ private: JSObject *_finalizing; ScriptingCore(); + + std::chrono::steady_clock::time_point _engineStartTime; public: ~ScriptingCore(); @@ -351,6 +354,11 @@ public: */ void cleanAllScript(); + /**@~english + * Gets the time that the ScriptingCore was initalized + */ + std::chrono::steady_clock::time_point getEngineStartTime() const; + /**@~english * Initialize everything, including the js context, js global object etc. */ @@ -529,8 +537,15 @@ public: * Calls the Garbage Collector */ virtual void garbageCollect() override; - + + /** + * Sets the js object that is being finalizing in the script engine, internal use only, please do not call this function + */ void setFinalizing (JSObject *finalizing) {_finalizing = finalizing;}; + + /** + * Gets the js object that is being finalizing in the script engine + */ JSObject *getFinalizing () {return _finalizing;}; private: @@ -565,9 +580,8 @@ bool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret); template js_type_class_t *jsb_register_class(JSContext *cx, JSClass *jsClass, JS::HandleObject proto, JS::HandleObject parentProto) { - TypeTest t; js_type_class_t *p = nullptr; - std::string typeName = t.s_name(); + std::string typeName = TypeTest::s_name(); if (_js_global_type_map.find(typeName) == _js_global_type_map.end()) { JS::RootedObject protoRoot(cx, proto); diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index d16d869e40..25e019be55 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -166,9 +166,8 @@ void JSTouchDelegate::unregisterTouchDelegate() this->release(); } -bool JSTouchDelegate::onTouchBegan(Touch *touch, Event *event) +bool JSTouchDelegate::onTouchBegan(Touch *touch, Event* /*event*/) { - CC_UNUSED_PARAM(event); JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); JS::RootedValue retval(cx); bool bRet = false; @@ -185,52 +184,45 @@ bool JSTouchDelegate::onTouchBegan(Touch *touch, Event *event) }; // optional -void JSTouchDelegate::onTouchMoved(Touch *touch, Event *event) +void JSTouchDelegate::onTouchMoved(Touch *touch, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchEvent(EventTouch::EventCode::MOVED, touch, obj); } -void JSTouchDelegate::onTouchEnded(Touch *touch, Event *event) +void JSTouchDelegate::onTouchEnded(Touch *touch, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchEvent(EventTouch::EventCode::ENDED, touch, obj); } -void JSTouchDelegate::onTouchCancelled(Touch *touch, Event *event) +void JSTouchDelegate::onTouchCancelled(Touch *touch, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchEvent(EventTouch::EventCode::CANCELLED, touch, obj); } // optional -void JSTouchDelegate::onTouchesBegan(const std::vector& touches, Event *event) +void JSTouchDelegate::onTouchesBegan(const std::vector& touches, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchesEvent(EventTouch::EventCode::BEGAN, touches, obj); } -void JSTouchDelegate::onTouchesMoved(const std::vector& touches, Event *event) +void JSTouchDelegate::onTouchesMoved(const std::vector& touches, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchesEvent(EventTouch::EventCode::MOVED, touches, obj); } -void JSTouchDelegate::onTouchesEnded(const std::vector& touches, Event *event) +void JSTouchDelegate::onTouchesEnded(const std::vector& touches, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchesEvent(EventTouch::EventCode::ENDED, touches, obj); } -void JSTouchDelegate::onTouchesCancelled(const std::vector& touches, Event *event) +void JSTouchDelegate::onTouchesCancelled(const std::vector& touches, Event* /*event*/) { - CC_UNUSED_PARAM(event); JS::RootedObject obj(ScriptingCore::getInstance()->getGlobalContext(), _obj); ScriptingCore::getInstance()->executeCustomTouchesEvent(EventTouch::EventCode::CANCELLED, touches, obj); } @@ -1346,7 +1338,7 @@ bool js_CCNode_unschedule(JSContext *cx, uint32_t argc, jsval *vp) auto targetArray = JSScheduleWrapper::getTargetForSchedule(args.get(0)); if (targetArray) { - CCLOGINFO("unschedule target number: %zd", targetArray->size()); + CCLOGINFO("unschedule target number: %ld", static_cast(targetArray->size())); for (const auto& tmp : *targetArray) { @@ -1691,7 +1683,6 @@ bool js_cocos2dx_CCNode_scheduleUpdate(JSContext *cx, uint32_t argc, jsval *vp) cocos2d::Node* cobj = (cocos2d::Node *)(proxy ? proxy->ptr : nullptr); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 0) { - bool isFoundUpdate = false; ok = JS_HasProperty(cx, obj, "update", &isFoundUpdate); JS::RootedValue jsUpdateFunc(cx); diff --git a/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp index 472992564e..1d157aaf61 100644 --- a/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp @@ -22,14 +22,16 @@ */ #include "scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.h" -#include "base/CCDirector.h" -#include "base/CCScheduler.h" -#include "renderer/CCTextureCache.h" #include "extensions/cocos-ext.h" #include "scripting/js-bindings/manual/ScriptingCore.h" #include "scripting/js-bindings/manual/cocos2d_specifics.hpp" #include "scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp" #include +#include + +#include "base/CCDirector.h" +#include "base/CCScheduler.h" +#include "renderer/CCTextureCache.h" USING_NS_CC; USING_NS_CC_EXT; @@ -994,6 +996,17 @@ bool js_load_remote_image(JSContext *cx, uint32_t argc, jsval *vp) return false; } +using namespace std::chrono; + +bool js_performance_now(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + auto now = steady_clock::now(); + auto micro = duration_cast(now - ScriptingCore::getInstance()->getEngineStartTime()).count(); + args.rval().set(DOUBLE_TO_JSVAL((double)micro * 0.001)); + return true; +} + extern JSObject* jsb_cocos2d_extension_ScrollView_prototype; extern JSObject* jsb_cocos2d_extension_TableView_prototype; extern JSObject* jsb_cocos2d_extension_Control_prototype; @@ -1038,4 +1051,8 @@ void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject glob JS_DefineFunction(cx, tmpObj, "create", js_cocos2dx_CCTableView_create, 3, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, jsbObj, "loadRemoteImg", js_load_remote_image, 2, JSPROP_READONLY | JSPROP_PERMANENT); + + JS::RootedObject performance(cx); + get_or_create_js_obj(cx, global, "performance", &performance); + JS_DefineFunction(cx, performance, "now", js_performance_now, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); } diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp index 0dba081643..4631450256 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp @@ -599,7 +599,7 @@ bool jsval_to_long_long(JSContext *cx, JS::HandleValue vp, long long* r) } bool jsval_to_std_string(JSContext *cx, JS::HandleValue v, std::string* ret) { - if(v.isString() || v.isNumber() || v.isBoolean()) + if (v.isString() || v.isBoolean() || v.isNumber()) { JSString *tmp = JS::ToString(cx, v); JSB_PRECONDITION3(tmp, cx, false, "Error processing arguments"); @@ -1963,21 +1963,6 @@ jsval uniform_to_jsval(JSContext* cx, const cocos2d::Uniform* uniform) return JSVAL_NULL; } -// -//jsval meshVertexAttrib_to_jsval(JSContext* cx, const cocos2d::MeshVertexAttrib& q) -//{ -// JS::RootedObject tmp(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr())); -// if(!tmp) return JSVAL_NULL; -// bool ok = JS_DefineProperty(cx, tmp, "size", q.size, JSPROP_ENUMERATE | JSPROP_PERMANENT) && -// JS_DefineProperty(cx, tmp, "type", q.type, JSPROP_ENUMERATE | JSPROP_PERMANENT) && -// JS_DefineProperty(cx, tmp, "vertexAttrib", q.vertexAttrib, JSPROP_ENUMERATE | JSPROP_PERMANENT) && -// JS_DefineProperty(cx, tmp, "attribSizeBytes", q.attribSizeBytes, JSPROP_ENUMERATE | JSPROP_PERMANENT); -// if(ok) -// return OBJECT_TO_JSVAL(tmp); -// -// return JSVAL_NULL; -//} - jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) { JS::RootedObject proto(cx); diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h index 91a98dc79f..1ebb771a5e 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h @@ -281,7 +281,6 @@ jsval ccacceleration_to_jsval(JSContext* cx, const cocos2d::Acceleration& v); jsval ccaffinetransform_to_jsval(JSContext* cx, const cocos2d::AffineTransform& t); jsval FontDefinition_to_jsval(JSContext* cx, const cocos2d::FontDefinition& t); jsval quaternion_to_jsval(JSContext* cx, const cocos2d::Quaternion& q); -//jsval meshVertexAttrib_to_jsval(JSContext* cx, const cocos2d::MeshVertexAttrib& q); jsval uniform_to_jsval(JSContext* cx, const cocos2d::Uniform* uniform); jsval resourcedata_to_jsval(JSContext* cx, const cocos2d::ResourceData& v); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp index 6f0b00a465..507d122b1f 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp @@ -518,8 +518,8 @@ bool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) JSObject *typedArray = NULL; if( utype == GL_FLOAT) { // FIXME: glew on windows will cause array overflow after invoking glGetUniformfv. - // It seems that glGetUniformfv re-assign the memeroy with a wrong size which is 4x than we pass in. - // For temporary solution, we allocate 4x array. + // It seems that glGetUniformfv re-assign the memory with a wrong size which is 4x than we pass in. + // For temporary solution, we allocate 4x array. GLfloat* param = new (std::nothrow) GLfloat[usize*4]; glGetUniformfv(arg0, arg1, param); @@ -529,8 +529,8 @@ bool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) CC_SAFE_DELETE_ARRAY(param); } else if( utype == GL_INT ) { // FIXME: glew on windows will cause array overflow after invoking glGetUniformfv. - // It seems that glGetUniformfv re-assign the memeroy with a wrong size which is 4x than we pass in. - // For temporary solution, we allocate 4x array. + // It seems that glGetUniformfv re-assign the memory with a wrong size which is 4x than we pass in. + // For temporary solution, we allocate 4x array. GLint* param = new (std::nothrow) GLint[usize*4]; glGetUniformiv(arg0, arg1, param); diff --git a/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js b/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js index e18ffae7e8..4ea82acdf7 100644 --- a/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js +++ b/native/cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js @@ -38,7 +38,7 @@ ccui.Widget.prototype._ctor = ccui.ScrollView.prototype._ctor = function(){ this.init(); - } + }; ccui.Button.prototype._ctor = function (normalImage, selectedImage, disableImage, texType) { if(texType !== undefined) @@ -80,7 +80,7 @@ ccui.ImageView.prototype._ctor = function(imageFileName, texType){ } else ccui.Widget.prototype.init.call(this); -} +}; ccui.LoadingBar.prototype._ctor = function(textureName, percentage){ ccui.Widget.prototype.init.call(this); @@ -149,8 +149,7 @@ if (ccui.WebView) { ccui.WebView.prototype._ctor = function(url){ this.init(); - if(url) - this.loadURL(url); + url !== undefined && this.loadURL(url); }; } @@ -158,8 +157,7 @@ if (ccui.VideoPlayer) { ccui.VideoPlayer.prototype._ctor = function(url){ this.init(); - if(url) - this.setURL(url); + url !== undefined && this.setURL(url); }; } diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js index f18adb273f..cbd9830ec1 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js @@ -94,7 +94,7 @@ ScriptStore.prototype = { /** * Get all scripts produced from the given source. * - * @oaram Debugger.Source source + * @param Debugger.Source source * @returns Array of Debugger.Script */ getScriptsBySource: function(source) { @@ -113,7 +113,7 @@ ScriptStore.prototype = { * Get all scripts produced from the given source whose source code definition * spans the given line. * - * @oaram Debugger.Source source + * @param Debugger.Source source * @param Number line * @returns Array of Debugger.Script */ diff --git a/native/cocos/scripting/js-bindings/script/debugger/main.js b/native/cocos/scripting/js-bindings/script/debugger/main.js index 9d6592a705..bf8e81e7c3 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/main.js +++ b/native/cocos/scripting/js-bindings/script/debugger/main.js @@ -1305,7 +1305,7 @@ function DebuggerServerConnection(aPrefix, aTransport) this._actorPool = new ActorPool(this); this._extraPools = [this._actorPool]; - // Responses to a given actor must be returned the the client + // Responses to a given actor must be returned the client // in the same order as the requests that they're replying to, but // Implementations might finish serving requests in a different // order. To keep things in order we generate a promise for each diff --git a/native/cocos/scripting/js-bindings/script/debugger/transport.js b/native/cocos/scripting/js-bindings/script/debugger/transport.js index 4b00ce88c1..a2f50eadb5 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/transport.js +++ b/native/cocos/scripting/js-bindings/script/debugger/transport.js @@ -249,7 +249,6 @@ DebuggerTransport.prototype = { // this._output.asyncWait(this, 0, 0, threadManager.currentThread); // log('send: ' + this._outgoing); _bufferWrite(this._outgoing); - log('send: ' + this._outgoing); } }, diff --git a/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js b/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js index f43e0cfc80..4c85cbea92 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js +++ b/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js @@ -452,7 +452,7 @@ var WebConsoleUtils = { /** * Helper function to deduce the name of the provided function. * - * @param funtion aFunction + * @param function aFunction * The function whose name will be returned. * @return string * Function name. @@ -1527,7 +1527,7 @@ var WebConsoleCommands = { /** * Register a new command. - * @param {string} name The command name (exemple: "$") + * @param {string} name The command name (example: "$") * @param {(function|object)} command The command to register. * It can be a function so the command is a function (like "$()"), * or it can also be a property descriptor to describe a getter / value (like diff --git a/native/cocos/scripting/js-bindings/script/jsb.js b/native/cocos/scripting/js-bindings/script/jsb.js index c1e365fac9..61dacdc64c 100644 --- a/native/cocos/scripting/js-bindings/script/jsb.js +++ b/native/cocos/scripting/js-bindings/script/jsb.js @@ -21,7 +21,7 @@ */ // -// Javascript Bindigns helper file +// JavaScript Bindings helper file // // DO NOT ALTER THE ORDER diff --git a/native/cocos/scripting/js-bindings/script/jsb_boot.js b/native/cocos/scripting/js-bindings/script/jsb_boot.js index 305ececc83..cfefdb74ea 100755 --- a/native/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/native/cocos/scripting/js-bindings/script/jsb_boot.js @@ -1091,7 +1091,7 @@ var _initSys = function () { * @constant * @type {Number} */ - sys.LANGUAGE_UNKNOWN = "unkonwn"; + sys.LANGUAGE_UNKNOWN = "unknown"; /** * @memberof cc.sys @@ -1483,6 +1483,10 @@ var _initSys = function () { sys._application.openURL(url); }; + sys.now = function () { + return Date.now(); + }; + // JS to Native bridges if(window.JavascriptJavaBridge && cc.sys.os == cc.sys.OS_ANDROID){ jsb.reflection = new JavascriptJavaBridge(); diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index ec97489e5c..c2d96cb898 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -26,7 +26,7 @@ // CCConfig.js // -cc.ENGINE_VERSION = "Cocos2d-JS v3.13"; +cc.ENGINE_VERSION = "Cocos2d-JS v3.14"; cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0; cc.DIRECTOR_STATS_POSITION = {x: 0, y: 0}; @@ -128,7 +128,8 @@ cc.MENU_STATE_TRACKING_TOUCH = 1; cc.MENU_HANDLER_PRIORITY = -128; cc.DEFAULT_PADDING = 5; -cc.Scheduler.PRIORITY_SYSTEM = -2147483648; +cc.Scheduler.PRIORITY_SYSTEM = -2147483648; +cc.Scheduler.PRIORITY_NON_SYSTEM = cc.Scheduler.PRIORITY_SYSTEM + 1; var _Class = cc.Texture2D; @@ -229,8 +230,6 @@ cc.stencilBits = -1; //CCClippingNode.js cc.g_NumberOfDraws = 0; //CCDirector.js -cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1; //CCScheduler.js - cc.s_globalOrderOfArrival = 1; cc.Event.TOUCH = 0; //CCEvent.js @@ -615,7 +614,7 @@ cc._reuse_color4b = {r:255, g:255, b:255, a:255 }; // -// Basic sturcture : Point +// Basic structure : Point // cc.p = function( x, y ) { @@ -1122,7 +1121,7 @@ cc._g = function( x, y ) }; // -// Basic sturcture : Size +// Basic structure : Size // cc.size = function(w,h) { @@ -1263,7 +1262,7 @@ cc.RectZero = function () { return cc.rect(0, 0, 0, 0); }; -// Basic sturcture : Color +// Basic structure : Color cc.Color = function (r, g, b, a) { this.r = r || 0; this.g = g || 0; @@ -1275,7 +1274,7 @@ cc.Color = function (r, g, b, a) { * Generate a color object based on multiple forms of parameters * @example * - * // 1. All channels seperately as parameters + * // 1. All channels separately as parameters * var color1 = cc.color(255, 255, 255, 255); * * // 2. Convert a hex string to a color @@ -1869,7 +1868,7 @@ cc.arrayVerifyType = function (arr, type) { }; /** - * Searches for the first occurance of object and removes it. If object is not found the function has no effect. + * Searches for the first occurrence of object and removes it. If object is not found the function has no effect. * @function * @param {Array} arr Source Array * @param {*} delObj remove object @@ -1950,6 +1949,8 @@ cc.DrawNode = cc._DrawNode.extend({ _drawColor: cc.color(255, 255, 255, 255), _lineWidth: 1, + release: function () {}, + setLineWidth: function (width) { this._lineWidth = width; }, @@ -2950,7 +2951,7 @@ cc.Texture2D.prototype.setTexParameters = function (texParams, magFilter, wrapS, this._setTexParameters(minFilter, magFilter, wrapS, wrapT); }; -cc.Texture2D.prototype.handleLoadedTexture = function (premultipled) {}; +cc.Texture2D.prototype.handleLoadedTexture = function (premultiplied) {}; // @@ -2962,7 +2963,7 @@ cc.MenuItem.prototype.setCallback = function (callback, target) { }; // -// MenuItemImage support sprite frame name as paramter +// MenuItemImage support sprite frame name as parameter // var _p = cc.MenuItemImage.prototype; _p._setNormalSpriteFrame = _p.setNormalSpriteFrame; @@ -3060,7 +3061,8 @@ _p.schedule = function (callback, target, interval, repeat, delay, paused, key) key = target.__instanceId + ""; } this._schedule(callback, target, interval, repeat, delay, paused, key); -} +}; + cc._NodeGrid = cc.NodeGrid; cc.NodeGrid = function(rect){ diff --git a/native/cocos/scripting/js-bindings/script/jsb_common.js b/native/cocos/scripting/js-bindings/script/jsb_common.js index b5be3a1f80..dfed986bd8 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_common.js +++ b/native/cocos/scripting/js-bindings/script/jsb_common.js @@ -105,7 +105,7 @@ cc.KEY = { '-':109, 'numdel':110, '/':111, - f1:112, //f1-f12 dont work on ie + f1:112, //f1-f12 don't work on ie f2:113, f3:114, f4:115, @@ -139,7 +139,7 @@ cc.KEY = { closebracket:221, quote:222, - // gamepad controll + // gamepad control dpadLeft:1000, dpadRight:1001, dpadUp:1003, diff --git a/native/cocos/scripting/js-bindings/script/jsb_create_apis.js b/native/cocos/scripting/js-bindings/script/jsb_create_apis.js index 216afe8176..5acacbbada 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_create_apis.js +++ b/native/cocos/scripting/js-bindings/script/jsb_create_apis.js @@ -850,7 +850,7 @@ cc.GLProgram.prototype._ctor = function(vShaderFileName, fShaderFileName) { * var spriteFrame = cc.spriteFrameCache.getSpriteFrame('grossini_dance_01.png'); * var sprite = cc.Sprite.create(spriteFrame); * - * 4.Create a sprite with an exsiting texture contained in a CCTexture2D object + * 4.Create a sprite with an existing texture contained in a CCTexture2D object * After creation, the rect will be the size of the texture, and the offset will be (0,0). * var texture = cc.textureCache.addImage('HelloHTML5World.png'); * var sprite1 = cc.Sprite.create(texture); diff --git a/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js b/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js index 631eec64a5..3673ef54b4 100644 --- a/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js +++ b/native/cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js @@ -1,3 +1,25 @@ +/* + * Copyright (c) 2013-2016 Chukong Technologies Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + // move from extension // start //PhysicsDebugNode diff --git a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js b/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js index 9fe033856e..a7b6795b15 100644 --- a/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js +++ b/native/cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js @@ -1,3 +1,25 @@ +/* + * Copyright (c) 2016 Chukong Technologies Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + var _proto = ccs.Bone.prototype; cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor); cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity); From 8600224c426fd1f72e4364d631130478071aad53 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 15:28:46 +0800 Subject: [PATCH 02/10] Fix chipmunk potential crash issues --- .../chipmunk/js_bindings_chipmunk_manual.cpp | 143 +++++++++++++----- 1 file changed, 104 insertions(+), 39 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_manual.cpp b/native/cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_manual.cpp index 0ac44eec6f..3f5d667a15 100644 --- a/native/cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_manual.cpp @@ -845,39 +845,72 @@ struct collision_handler { unsigned int is_oo; // Objected oriented API ? UT_hash_handle hh; + + bool is_default; - collision_handler() + collision_handler () { begin = nullptr; pre = nullptr; post = nullptr; separate = nullptr; jsthis = nullptr; + is_default = false; + } + + ~collision_handler () + { + JS::RootedValue jsspace(cx, OBJECT_TO_JSVAL(jsthis)); + if (!is_default && jsspace.isObject()) + { + JS::RootedValue callback(cx); + callback.set(OBJECT_TO_JSVAL(begin)); + if (callback.isObject()) + { + js_remove_object_reference(jsspace, callback); + } + callback.set(OBJECT_TO_JSVAL(pre)); + if (callback.isObject()) + { + js_remove_object_reference(jsspace, callback); + } + callback.set(OBJECT_TO_JSVAL(post)); + if (callback.isObject()) + { + js_remove_object_reference(jsspace, callback); + } + callback.set(OBJECT_TO_JSVAL(separate)); + if (callback.isObject()) + { + js_remove_object_reference(jsspace, callback); + } + } } + // Space must be set after set handles void setJSSpace(JS::HandleValue jsspace) { - if (!jsspace.isNullOrUndefined()) + if (jsspace.isObject()) { jsthis = jsspace.toObjectOrNull(); - JS::RootedValue callback(ScriptingCore::getInstance()->getGlobalContext()); + JS::RootedValue callback(cx); callback.set(OBJECT_TO_JSVAL(begin)); - if (!callback.isNullOrUndefined()) + if (callback.isObject()) { js_add_object_reference(jsspace, callback); } callback.set(OBJECT_TO_JSVAL(pre)); - if (!callback.isNullOrUndefined()) + if (callback.isObject()) { js_add_object_reference(jsspace, callback); } callback.set(OBJECT_TO_JSVAL(post)); - if (!callback.isNullOrUndefined()) + if (callback.isObject()) { js_add_object_reference(jsspace, callback); } callback.set(OBJECT_TO_JSVAL(separate)); - if (!callback.isNullOrUndefined()) + if (callback.isObject()) { js_add_object_reference(jsspace, callback); } @@ -900,7 +933,12 @@ static unsigned long pair_ints( unsigned long A, unsigned long B ) static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) { + if (data == nullptr) { + return cpTrue; + } struct collision_handler *handler = (struct collision_handler*) data; + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval args[2]; if( handler->is_oo ) { @@ -913,8 +951,6 @@ static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) args[1] = opaque_to_jsval(handler->cx, space ); } - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - JS::RootedValue rval(handler->cx); JS::RootedObject jsthis(handler->cx, handler->jsthis); JS::RootedValue jsbegin(handler->cx, OBJECT_TO_JSVAL(handler->begin)); @@ -930,7 +966,12 @@ static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) { + if (data == nullptr) { + return cpTrue; + } struct collision_handler *handler = (struct collision_handler*) data; + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval args[2]; if( handler->is_oo ) { @@ -943,8 +984,6 @@ static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) args[1] = opaque_to_jsval( handler->cx, space ); } - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - JS::RootedValue rval(handler->cx); JS::RootedObject jsthis(handler->cx, handler->jsthis); JS::RootedValue jspre(handler->cx, OBJECT_TO_JSVAL(handler->pre)); @@ -960,7 +999,12 @@ static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) { + if (data == nullptr) { + return; + } struct collision_handler *handler = (struct collision_handler*) data; + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval args[2]; @@ -974,8 +1018,6 @@ static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) args[1] = opaque_to_jsval( handler->cx, space ); } - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - JS::RootedValue ignore(handler->cx); JS::RootedObject jsthis(handler->cx, handler->jsthis); JS::RootedValue jspost(handler->cx, OBJECT_TO_JSVAL(handler->post)); @@ -986,27 +1028,35 @@ static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) { struct collision_handler *handler = (struct collision_handler*) data; - if(! handler->cx || !handler->space) + if (handler == nullptr || !handler->cx || !handler->space) return; - + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + + JS::RootedValue jssep(handler->cx, OBJECT_TO_JSVAL(handler->separate)); + if (!jssep.isObject()) + { + return; + } + jsval args[2]; - if( handler->is_oo ) { + if (handler->is_oo) + { JS::RootedObject arbiterProto(handler->cx, JSB_cpArbiter_object); JS::RootedObject spaceProto(handler->cx, JSB_cpSpace_object); args[0] = c_class_to_jsval(handler->cx, arb, arbiterProto, JSB_cpArbiter_class, "cpArbiter"); args[1] = c_class_to_jsval(handler->cx, space, spaceProto, JSB_cpSpace_class, "cpArbiter"); - } else { + } else + { args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - JS::RootedValue ignore(handler->cx); JS::RootedObject jsthis(handler->cx, handler->jsthis); - JS::RootedValue jssep(handler->cx, OBJECT_TO_JSVAL(handler->separate)); bool ok = JS_CallFunctionValue( handler->cx, jsthis, jssep, JS::HandleValueArray::fromMarkedLocation(2, args), &ignore); - JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Separate");} + JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Separate"); +} #pragma mark - cpSpace @@ -1015,7 +1065,8 @@ static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *jsthis) { struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - if ( proxy ) { + if ( proxy ) + { CCLOGINFO("jsbindings: finalizing JS object %p (cpSpace), handle: %p", jsthis, proxy->handle); // space @@ -1024,8 +1075,19 @@ void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *jsthis) // Remove collision handlers, since the user might have forgotten to manually remove them struct collision_handler *current = nullptr, *tmp = nullptr; - HASH_ITER(hh, collision_handler_hash, current, tmp) { - if( current->space == space ) { + HASH_ITER(hh, collision_handler_hash, current, tmp) + { + if( current->space == space ) + { + if (current->is_default) + { + cpCollisionHandler* defaultHandler = cpSpaceAddDefaultCollisionHandler(space); + defaultHandler->userData = nullptr; + defaultHandler->beginFunc = cpCollisionHandlerDoNothing.beginFunc; + defaultHandler->preSolveFunc = cpCollisionHandlerDoNothing.preSolveFunc; + defaultHandler->postSolveFunc = cpCollisionHandlerDoNothing.postSolveFunc; + defaultHandler->separateFunc = cpCollisionHandlerDoNothing.separateFunc; + } HASH_DEL(collision_handler_hash,current); /* delete; users advances to next */ delete current; /* optional- if you want to free */ } @@ -1064,13 +1126,13 @@ bool __jsb_cpSpace_addCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, J ok &= jsval_to_int(cx, jstypeA, (int32_t*) &handler->typeA ); ok &= jsval_to_int(cx, jstypeB, (int32_t*) &handler->typeB ); - handler->begin = argvp->toObjectOrNull(); + handler->begin = argvp->isObject() ? argvp->toObjectOrNull() : nullptr; argvp++; - handler->pre = argvp->toObjectOrNull(); + handler->pre = argvp->isObject() ? argvp->toObjectOrNull() : nullptr; argvp++; - handler->post = argvp->toObjectOrNull(); + handler->post = argvp->isObject() ? argvp->toObjectOrNull() : nullptr; argvp++; - handler->separate = argvp->toObjectOrNull(); + handler->separate = argvp->isObject() ? argvp->toObjectOrNull() : nullptr; argvp++; JS::RootedValue spaceVal(cx, OBJECT_TO_JSVAL(jsspace)); @@ -1154,25 +1216,28 @@ bool JSB_cpSpace_setDefaultCollisionHandler(JSContext *cx, uint32_t argc, jsval handler->typeA = 0; handler->typeB = 0; - handler->begin = args.get(0).toObjectOrNull(); - handler->pre = args.get(1).toObjectOrNull(); - handler->post = args.get(2).toObjectOrNull(); - handler->separate = args.get(3).toObjectOrNull(); + handler->begin = args.get(0).isObject() ? args.get(0).toObjectOrNull() : nullptr; + handler->pre = args.get(1).isObject() ? args.get(1).toObjectOrNull() : nullptr; + handler->post = args.get(2).isObject() ? args.get(2).toObjectOrNull() : nullptr; + handler->separate = args.get(3).isObject() ? args.get(3).toObjectOrNull() : nullptr; JS::RootedValue spaceVal(cx, OBJECT_TO_JSVAL(jsthis)); + // Space must be set after set handles handler->setJSSpace(spaceVal); // Object Oriented API ? handler->is_oo = 1; + // Default handler shouldn't be removed + handler->is_default = true; // owner of the collision handler handler->space = space; handler->cx = cx; cpCollisionHandler* defaultHandler = cpSpaceAddDefaultCollisionHandler(space); - defaultHandler->beginFunc = !handler->begin ? NULL : &myCollisionBegin; - defaultHandler->preSolveFunc = !handler->pre ? NULL : &myCollisionPre; - defaultHandler->postSolveFunc = !handler->post ? NULL : &myCollisionPost; - defaultHandler->separateFunc = !handler->separate ? NULL : &myCollisionSeparate; + defaultHandler->beginFunc = !handler->begin ? cpCollisionHandlerDoNothing.beginFunc : &myCollisionBegin; + defaultHandler->preSolveFunc = !handler->pre ? cpCollisionHandlerDoNothing.preSolveFunc : &myCollisionPre; + defaultHandler->postSolveFunc = !handler->post ? cpCollisionHandlerDoNothing.postSolveFunc : &myCollisionPost; + defaultHandler->separateFunc = !handler->separate ? cpCollisionHandlerDoNothing.separateFunc : &myCollisionSeparate; defaultHandler->userData = handler; // // Already added ? If so, remove it. @@ -2553,7 +2618,7 @@ static void unroot_jsobject_from_handle(void *handle) static void shapeFreeWrap(cpSpace *space, cpShape *shape, void *unused){ cpSpaceRemoveShape(space, shape); unroot_jsobject_from_handle(shape); - // cpShapeFree(shape); +// cpShapeFree(shape); } static void postShapeFree(cpShape *shape, cpSpace *space){ @@ -2563,7 +2628,7 @@ static void postShapeFree(cpShape *shape, cpSpace *space){ static void constraintFreeWrap(cpSpace *space, cpConstraint *constraint, void *unused){ cpSpaceRemoveConstraint(space, constraint); unroot_jsobject_from_handle(constraint); - // cpConstraintFree(constraint); +// cpConstraintFree(constraint); } static void postConstraintFree(cpConstraint *constraint, cpSpace *space){ @@ -2573,7 +2638,7 @@ static void postConstraintFree(cpConstraint *constraint, cpSpace *space){ static void bodyFreeWrap(cpSpace *space, cpBody *body, void *unused){ cpSpaceRemoveBody(space, body); unroot_jsobject_from_handle(body); - // cpBodyFree(body); +// cpBodyFree(body); } static void postBodyFree(cpBody *body, cpSpace *space){ From c47a7708775d60e3142f073d808ca6d230fbc0a1 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 15:29:18 +0800 Subject: [PATCH 03/10] Adapt websocket to new memory model --- native/cocos/network/WebSocket.cpp | 12 ++++++---- .../manual/network/jsb_websocket.cpp | 24 +++++++++++++++---- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/native/cocos/network/WebSocket.cpp b/native/cocos/network/WebSocket.cpp index b547c8e011..2735bd4907 100644 --- a/native/cocos/network/WebSocket.cpp +++ b/native/cocos/network/WebSocket.cpp @@ -338,6 +338,7 @@ WebSocket::~WebSocket() { LOGD("In the destructor of WebSocket (%p)\n", this); CC_SAFE_DELETE(_wsHelper); + CC_SAFE_DELETE(_delegate); if (_wsProtocols != nullptr) { @@ -411,7 +412,7 @@ bool WebSocket::init(const Delegate& delegate, LOGD("[WebSocket::init] _host: %s, _port: %d, _path: %s\n", _host.c_str(), _port, _path.c_str()); size_t protocolCount = 0; - if (protocols && !protocols->empty()) + if (protocols && protocols->size() > 0) { protocolCount = protocols->size(); } @@ -423,16 +424,17 @@ bool WebSocket::init(const Delegate& delegate, _wsProtocols = new (std::nothrow) lws_protocols[protocolCount+1]; memset(_wsProtocols, 0, sizeof(lws_protocols)*(protocolCount+1)); - if (protocols && !protocols->empty()) + if (protocols && protocols->size() > 0) { int i = 0; - for (std::vector::const_iterator iter = protocols->begin(); iter != protocols->end(); ++iter, ++i) + for (auto& protocol : *protocols) { - char* name = new (std::nothrow) char[(*iter).length()+1]; - strcpy(name, (*iter).c_str()); + char* name = new (std::nothrow) char[protocol.length()+1]; + strcpy(name, protocol.c_str()); _wsProtocols[i].name = name; _wsProtocols[i].callback = WebSocketCallbackWrapper::onSocketCallback; _wsProtocols[i].rx_buffer_size = WS_RX_BUFFER_SIZE; + ++i; } } else diff --git a/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp b/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp index 3449d51bcc..0382a107f9 100644 --- a/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp +++ b/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp @@ -166,13 +166,15 @@ public: auto copy = &p->obj; JS::RemoveObjectRoot(cx, copy); +#if not CC_ENABLE_GC_FOR_NATIVE_OBJECTS jsb_remove_proxy(p); } // Delete WebSocket instance CC_SAFE_DELETE(ws); - // Delete self at last while websocket was closed. - delete this; +#else + } +#endif } virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error) @@ -201,7 +203,7 @@ public: _JSDelegate.ref() = pJSDelegate; } private: - mozilla::Maybe _JSDelegate; + mozilla::Maybe _JSDelegate; }; JSClass *js_cocos2dx_websocket_class; @@ -209,6 +211,18 @@ JSObject *js_cocos2dx_websocket_prototype; void js_cocos2dx_WebSocket_finalize(JSFreeOp *fop, JSObject *obj) { CCLOG("jsbindings: finalizing JS object %p (WebSocket)", obj); + +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + JS::RootedObject jsobj(ScriptingCore::getInstance()->getGlobalContext(), obj); + js_proxy_t *p = jsb_get_js_proxy(jsobj); + if (p) + { + WebSocket *ws = (WebSocket *)(p->ptr); + jsb_remove_proxy(p); + // Delete WebSocket instance + CC_SAFE_DELETE(ws); + } +#endif } bool js_cocos2dx_extension_WebSocket_send(JSContext *cx, uint32_t argc, jsval *vp) @@ -360,8 +374,10 @@ bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, j // link the native object with the javascript object js_proxy_t *p = jsb_new_proxy(cobj, obj); +#if not CC_ENABLE_GC_FOR_NATIVE_OBJECTS JS::AddNamedObjectRoot(cx, &p->obj, "WebSocket"); - +#endif + args.rval().set(OBJECT_TO_JSVAL(obj)); return true; } From 3001b99909571c1457d15af039072cc6d8ab7882 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:34:08 +0800 Subject: [PATCH 04/10] Improve wrappers bindings --- .../js-bindings/manual/cocos2d_specifics.cpp | 94 ++++++++++--------- .../js-bindings/manual/cocos2d_specifics.hpp | 1 - .../manual/js_manual_conversions.cpp | 5 +- .../manual/js_manual_conversions.h | 1 - 4 files changed, 52 insertions(+), 49 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index 25e019be55..135ebb5cd7 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -590,7 +590,7 @@ jsval anonEvaluate(JSContext *cx, JS::HandleObject thisObj, const char* string) void js_add_object_reference(JS::HandleValue owner, JS::HandleValue target) { - if (!owner.isObject() || !target.isObject()) + if (!owner.isObject() || !target.isObject() || owner == target) { return; } @@ -598,6 +598,7 @@ void js_add_object_reference(JS::HandleValue owner, JS::HandleValue target) ScriptingCore *engine = ScriptingCore::getInstance(); JSContext *cx = engine->getGlobalContext(); JS::RootedObject global(cx, engine->getGlobalObject()); + JSAutoCompartment(cx, global); JS::RootedObject jsbObj(cx); get_or_create_js_obj(cx, global, "jsb", &jsbObj); JS::RootedValue jsbVal(cx, OBJECT_TO_JSVAL(jsbObj)); @@ -622,10 +623,11 @@ void js_remove_object_reference(JS::HandleValue owner, JS::HandleValue target) } ScriptingCore *engine = ScriptingCore::getInstance(); JSContext *cx = engine->getGlobalContext(); + JS::RootedObject global(cx, engine->getGlobalObject()); + JSAutoCompartment(cx, global); JS::RootedObject ownerObj(cx, owner.toObjectOrNull()); JS::RootedObject targetObj(cx, target.toObjectOrNull()); - JS::RootedObject global(cx, engine->getGlobalObject()); JS::RootedObject jsbObj(cx); get_or_create_js_obj(cx, global, "jsb", &jsbObj); JS::RootedValue jsbVal(cx, OBJECT_TO_JSVAL(jsbObj)); @@ -652,6 +654,7 @@ void js_add_object_root(JS::HandleValue target) ScriptingCore *engine = ScriptingCore::getInstance(); JSContext *cx = engine->getGlobalContext(); JS::RootedObject global(cx, engine->getGlobalObject()); + JSAutoCompartment(cx, global); JS::RootedObject jsbObj(cx); get_or_create_js_obj(cx, global, "jsb", &jsbObj); JS::RootedValue jsbVal(cx, OBJECT_TO_JSVAL(jsbObj)); @@ -680,6 +683,8 @@ void js_remove_object_root(JS::HandleValue target) } ScriptingCore *engine = ScriptingCore::getInstance(); JSContext *cx = engine->getGlobalContext(); + JS::RootedObject global(cx, engine->getGlobalObject()); + JSAutoCompartment(cx, global); JS::RootedObject targetObj(cx, target.toObjectOrNull()); js_proxy_t *pTarget = jsb_get_js_proxy(targetObj); if (!pTarget) @@ -687,7 +692,6 @@ void js_remove_object_root(JS::HandleValue target) return; } - JS::RootedObject global(cx, engine->getGlobalObject()); JS::RootedObject jsbObj(cx); get_or_create_js_obj(cx, global, "jsb", &jsbObj); JS::RootedValue jsbVal(cx, OBJECT_TO_JSVAL(jsbObj)); @@ -710,7 +714,6 @@ void js_remove_object_root(JS::HandleValue target) } JSCallbackWrapper::JSCallbackWrapper() -: _rooted(true) { JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); _jsCallback = JS::NullValue(); @@ -724,7 +727,6 @@ JSCallbackWrapper::JSCallbackWrapper() } JSCallbackWrapper::JSCallbackWrapper(JS::HandleValue owner) -: _rooted(false) { _owner = owner; _jsCallback = JS::NullValue(); @@ -734,9 +736,10 @@ JSCallbackWrapper::JSCallbackWrapper(JS::HandleValue owner) JSCallbackWrapper::~JSCallbackWrapper() { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + ScriptingCore* sc = ScriptingCore::getInstance(); + JSContext* cx = sc->getGlobalContext(); JS::RootedValue ownerVal(cx, _owner); - if (_rooted && !ownerVal.isNullOrUndefined()) + if (!sc->getFinalizing() && !ownerVal.isNullOrUndefined()) { JS::RootedValue target(cx, _jsCallback); if (!target.isNullOrUndefined()) @@ -757,55 +760,55 @@ JSCallbackWrapper::~JSCallbackWrapper() } void JSCallbackWrapper::setJSCallbackFunc(JS::HandleValue func) { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS::RootedValue ownerVal(cx, _owner); - if (!ownerVal.isNullOrUndefined()) - { - JS::RootedValue target(cx, _jsCallback); - if (!target.isNullOrUndefined()) - { - js_remove_object_reference(ownerVal, target); - } - js_add_object_reference(ownerVal, func); - } if (!func.isNullOrUndefined()) { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS::RootedValue ownerVal(cx, _owner); + if (!ownerVal.isNullOrUndefined()) + { + JS::RootedValue target(cx, _jsCallback); + if (!target.isNullOrUndefined()) + { + js_remove_object_reference(ownerVal, target); + } + js_add_object_reference(ownerVal, func); + } _jsCallback = func; } } void JSCallbackWrapper::setJSCallbackThis(JS::HandleValue thisObj) { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS::RootedValue ownerVal(cx, _owner); - if (!ownerVal.isNullOrUndefined()) - { - JS::RootedValue target(cx, _jsThisObj); - if (!target.isNullOrUndefined()) - { - js_remove_object_reference(ownerVal, target); - } - js_add_object_reference(ownerVal, thisObj); - } if (!thisObj.isNullOrUndefined()) { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS::RootedValue ownerVal(cx, _owner); + if (!ownerVal.isNullOrUndefined()) + { + JS::RootedValue target(cx, _jsThisObj); + if (!target.isNullOrUndefined()) + { + js_remove_object_reference(ownerVal, target); + } + js_add_object_reference(ownerVal, thisObj); + } _jsThisObj = thisObj; } } void JSCallbackWrapper::setJSExtraData(JS::HandleValue data) { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS::RootedValue ownerVal(cx, _owner); - if (!ownerVal.isNullOrUndefined()) - { - JS::RootedValue target(cx, _extraData); - if (!target.isNullOrUndefined()) - { - js_remove_object_reference(ownerVal, target); - } - js_add_object_reference(ownerVal, data); - } if (!data.isNullOrUndefined()) { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS::RootedValue ownerVal(cx, _owner); + if (!ownerVal.isNullOrUndefined()) + { + JS::RootedValue target(cx, _extraData); + if (!target.isNullOrUndefined()) + { + js_remove_object_reference(ownerVal, target); + } + js_add_object_reference(ownerVal, data); + } _extraData = data; } } @@ -1280,8 +1283,13 @@ void JSScheduleWrapper::scheduleFunc(float dt) void JSScheduleWrapper::update(float dt) { jsval data = DOUBLE_TO_JSVAL(dt); + + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - ScriptingCore::getInstance()->executeFunctionWithOwner(getJSCallbackThis(), "update", 1, &data); + JS::RootedValue targetVal(cx, getJSCallbackThis()); + ScriptingCore::getInstance()->executeFunctionWithOwner(targetVal, "update", 1, &data); } Ref* JSScheduleWrapper::getTarget() @@ -1614,7 +1622,7 @@ bool js_cocos2dx_CCNode_scheduleUpdateWithPriority(JSContext *cx, uint32_t argc, if (!bFound) { - tmpCobj = new (std::nothrow) JSScheduleWrapper(thisValue); + tmpCobj = new (std::nothrow) JSScheduleWrapper(JS::NullHandleValue); tmpCobj->autorelease(); tmpCobj->setJSCallbackThis(thisValue); tmpCobj->setJSCallbackFunc(jsUpdateFunc); @@ -1716,7 +1724,7 @@ bool js_cocos2dx_CCNode_scheduleUpdate(JSContext *cx, uint32_t argc, jsval *vp) if (!bFound) { - tmpCobj = new (std::nothrow) JSScheduleWrapper(thisValue); + tmpCobj = new (std::nothrow) JSScheduleWrapper(JS::NullHandleValue); tmpCobj->autorelease(); tmpCobj->setJSCallbackThis(thisValue); tmpCobj->setJSCallbackFunc(jsUpdateFunc); diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp index 7edafe0773..ba5ac118be 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp @@ -172,7 +172,6 @@ protected: JS::Heap _jsCallback; JS::Heap _jsThisObj; JS::Heap _extraData; - bool _rooted; }; diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp index 4631450256..5d077c355b 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp @@ -101,7 +101,6 @@ const char* JSStringWrapper::get() // JSFunctionWrapper JSFunctionWrapper::JSFunctionWrapper(JSContext* cx, JS::HandleObject jsthis, JS::HandleValue fval) : _cx(cx) -, _rooted(false) { _jsthis = jsthis; _fval = fval; @@ -123,12 +122,10 @@ JSFunctionWrapper::JSFunctionWrapper(JSContext* cx, JS::HandleObject jsthis, JS: { js_add_object_reference(valRoot, funcVal); } - _rooted = true; } } JSFunctionWrapper::JSFunctionWrapper(JSContext* cx, JS::HandleObject jsthis, JS::HandleValue fval, JS::HandleValue owner) : _cx(cx) -, _rooted(false) { _jsthis = jsthis; _fval = fval; @@ -151,7 +148,7 @@ JSFunctionWrapper::~JSFunctionWrapper() { JS::RootedValue ownerVal(_cx, _owner); - if (_rooted && !ownerVal.isNullOrUndefined()) + if (!ScriptingCore::getInstance()->getFinalizing() && !ownerVal.isNullOrUndefined()) { JS::RootedValue thisVal(_cx, OBJECT_TO_JSVAL(_jsthis)); if (!thisVal.isNullOrUndefined()) diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h index 1ebb771a5e..fc15878f2f 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h @@ -82,7 +82,6 @@ private: JS::Heap _jsthis; JS::Heap _fval; JS::Heap _owner; - bool _rooted; private: CC_DISALLOW_COPY_AND_ASSIGN(JSFunctionWrapper); }; From 62abb3a1d96b3339637976d8417e7c8f2d6e8ccc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:35:39 +0800 Subject: [PATCH 05/10] Fix issue with get_or_create_js_object function --- .../cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index 135ebb5cd7..1993700b24 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -4846,8 +4846,9 @@ void get_or_create_js_obj(const std::string &name, JS::MutableHandleObject jsObj { subProp = name.substr(start); get_or_create_js_obj(cx, obj, subProp, &prop); - jsObj.set(obj); + obj.set(prop); } + jsObj.set(obj); } JSClass *jsb_cocos2d_PolygonInfo_class; From ed180996ac03dc043e8aa81ca63a7c266dd4e216 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:36:06 +0800 Subject: [PATCH 06/10] Use JS Function bind to avoid memory tracking issues --- .../scripting/js-bindings/script/jsb_boot.js | 70 ++++++++++++------- 1 file changed, 45 insertions(+), 25 deletions(-) diff --git a/native/cocos/scripting/js-bindings/script/jsb_boot.js b/native/cocos/scripting/js-bindings/script/jsb_boot.js index cfefdb74ea..547eefcc87 100755 --- a/native/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/native/cocos/scripting/js-bindings/script/jsb_boot.js @@ -708,35 +708,32 @@ cc.defineGetterSetter(cc.loader, "audioPath", function(){ cc.formatStr = function(){ var args = arguments; var l = args.length; - if(l < 1) - return ""; + if (l < 1) return ''; + var REGEXP_NUM_OR_STR = /(%d)|(%s)/; + var i = 1; var str = args[0]; - var needToFormat = true; - if(typeof str === "object"){ - needToFormat = false; + var hasSubstitution = typeof str === 'string' && REGEXP_NUM_OR_STR.test(str); + if (hasSubstitution) { + var REGEXP_STR = /%s/; + for (; i < l; ++i) { + var arg = args[i]; + var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR; + if (regExpToTest.test(str)) + str = str.replace(regExpToTest, arg); + else + str += ' ' + arg; + } } - for(var i = 1; i < l; ++i){ - var arg = args[i]; - if(needToFormat){ - while(true){ - var result = null; - if(typeof arg === "number"){ - result = str.match(/(%d)|(%s)/); - if(result){ - str = str.replace(/(%d)|(%s)/, arg); - break; - } - } - result = str.match(/%s/); - if(result) - str = str.replace(/%s/, arg); - else - str += " " + arg; - break; + else { + if (l > 1) { + for (; i < l; ++i) { + str += ' ' + args[i]; } - }else - str += " " + arg; + } + else { + str = '' + str; + } } return str; }; @@ -1780,6 +1777,29 @@ cc.game = { //+++++++++++++++++++++++++something about CCGame end+++++++++++++++++++++++++++++ +// Original bind in Spidermonkey v33 will trigger object life cycle track issue in our memory model and cause crash +Function.prototype.bind = function (oThis) { + if (!cc.isFunction(this)) { + // closest thing possible to the ECMAScript 5 + // internal IsCallable function + throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function () {}, + fBound = function () { + return fToBind.apply(this instanceof fNOP && oThis + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + fNOP.prototype = this.prototype; + fBound.prototype = new fNOP(); + + return fBound; +}; jsb.urlRegExp = new RegExp( "^" + From 58bf1434011998a2a1919135fc81eee2e79b8e9b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:40:47 +0800 Subject: [PATCH 07/10] Improve memory related API usage in JSFunctionWrapper::invoke --- .../js-bindings/manual/js_manual_conversions.cpp | 9 +++++++++ .../scripting/js-bindings/manual/js_manual_conversions.h | 1 + .../js-bindings/manual/jsb_event_dispatcher_manual.cpp | 4 ++-- native/tools/bindings-generator | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp index 5d077c355b..3bf49819fc 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp @@ -172,6 +172,15 @@ bool JSFunctionWrapper::invoke(unsigned int argc, jsval *argv, JS::MutableHandle return JS_CallFunctionValue(_cx, thisObj, fval, JS::HandleValueArray::fromMarkedLocation(argc, argv), rval); } +bool JSFunctionWrapper::invoke(JS::HandleValueArray args, JS::MutableHandleValue rval) +{ + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + + JS::RootedObject thisObj(_cx, _jsthis); + JS::RootedValue fval(_cx, _fval); + return JS_CallFunctionValue(_cx, thisObj, fval, args, rval); +} + static Color3B getColorFromJSObject(JSContext *cx, JS::HandleObject colorObject) { JS::RootedValue jsr(cx); diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h index fc15878f2f..988aea4290 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.h @@ -77,6 +77,7 @@ public: ~JSFunctionWrapper(); bool invoke(unsigned int argc, jsval *argv, JS::MutableHandleValue rval); + bool invoke(JS::HandleValueArray args, JS::MutableHandleValue rval); private: JSContext *_cx; JS::Heap _jsthis; diff --git a/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp index 89634b19df..51eae8ede6 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp @@ -255,7 +255,7 @@ bool js_EventListenerCustom_create(JSContext *cx, uint32_t argc, jsval *vp) largv[0] = JSVAL_NULL; }; JS::RootedValue rval(cx); - bool succeed = func->invoke(1, &largv[0], &rval); + bool succeed = func->invoke(JS::HandleValueArray::fromMarkedLocation(1, largv), &rval); if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } @@ -308,7 +308,7 @@ bool js_EventDispatcher_addCustomEventListener(JSContext *cx, uint32_t argc, jsv largv[0] = JSVAL_NULL; }; JS::RootedValue rval(cx); - bool succeed = func->invoke(1, &largv[0], &rval); + bool succeed = func->invoke(JS::HandleValueArray::fromMarkedLocation(1, largv), &rval); if (!succeed && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } diff --git a/native/tools/bindings-generator b/native/tools/bindings-generator index 6f4c19808d..9a35f9e741 160000 --- a/native/tools/bindings-generator +++ b/native/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 6f4c19808d7a737f55485419a6f5a710d10bde29 +Subproject commit 9a35f9e7419ed57de5527307c6333ff96b8a048f From 3eee19339ae7417d5eb69e1bb39ecc9b2256a7e3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:43:08 +0800 Subject: [PATCH 08/10] Fix download resuming issue on Android --- .../org/cocos2dx/lib/Cocos2dxDownloader.java | 90 ++++++++++++++++++- 1 file changed, 88 insertions(+), 2 deletions(-) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java index c2597eda62..d566139c21 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java @@ -10,6 +10,10 @@ import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.message.BasicHeader; import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; import java.util.*; class DataTaskHandler extends BinaryHttpResponseHandler { @@ -60,6 +64,51 @@ class DataTaskHandler extends BinaryHttpResponseHandler { } } +class HeadTaskHandler extends AsyncHttpResponseHandler { + int _id; + String _host; + String _url; + String _path; + private Cocos2dxDownloader _downloader; + + void LogD(String msg) { + android.util.Log.d("Cocos2dxDownloader", msg); + } + + public HeadTaskHandler(Cocos2dxDownloader downloader, int id, String host, String url, String path) { + super(); + _downloader = downloader; + _id = id; + _host = host; + _url = url; + _path = path; + } + + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + Boolean acceptRanges = false; + for (int i = 0; i < headers.length; ++i) { + Header elem = headers[i]; + if (elem.getName().equals("Accept-Ranges")) { + acceptRanges = elem.getValue().equals("bytes"); + break; + } + } + Cocos2dxDownloader.setResumingSupport(_host, acceptRanges); + Cocos2dxDownloader.createTask(_downloader, _id, _url, _path); + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) { + LogD("onFailure(code:" + statusCode + " headers:" + headers + " throwable:" + throwable + " id:" + _id); + String errStr = ""; + if (null != throwable) { + errStr = throwable.toString(); + } + _downloader.onFinish(_id, statusCode, errStr, null); + } +} + class FileTaskHandler extends FileAsyncHttpResponseHandler { int _id; File _finalFile; @@ -171,6 +220,7 @@ public class Cocos2dxDownloader { private HashMap _taskMap = new HashMap(); private Queue _taskQueue = new LinkedList(); private int _runningTaskCount = 0; + private static HashMap _resumingSupport = new HashMap(); void onProgress(final int id, final long downloadBytes, final long downloadNow, final long downloadTotal) { DownloadTask task = (DownloadTask)_taskMap.get(id); @@ -206,6 +256,10 @@ public class Cocos2dxDownloader { }); } + public static void setResumingSupport(String host, Boolean support) { + Cocos2dxDownloader._resumingSupport.put(host, support); + } + public static Cocos2dxDownloader createDownloader(int id, int timeoutInSeconds, String tempFileNameSufix, int countOfMaxProcessingTasks) { Cocos2dxDownloader downloader = new Cocos2dxDownloader(); downloader._id = id; @@ -239,6 +293,29 @@ public class Cocos2dxDownloader { do { if (0 == path.length()) break; + + String domain; + try { + URI uri = new URI(url); + domain = uri.getHost(); + } + catch (URISyntaxException e) { + break; + } + final String host = domain.startsWith("www.") ? domain.substring(4) : domain; + Boolean supportResuming = false; + Boolean requestHeader = true; + if (_resumingSupport.containsKey(host)) { + supportResuming = _resumingSupport.get(host); + requestHeader = false; + } + + if (requestHeader) { + task.handler = new HeadTaskHandler(downloader, id, host, url, path); + task.handle = downloader._httpClient.head(Cocos2dxHelper.getActivity(), url, null, null, task.handler); + break; + } + // file task File tempFile = new File(path + downloader._tempFileNameSufix); if (tempFile.isDirectory()) break; @@ -252,14 +329,23 @@ public class Cocos2dxDownloader { task.handler = new FileTaskHandler(downloader, id, tempFile, finalFile); Header[] headers = null; long fileLen = tempFile.length(); - if (fileLen > 0) { + if (supportResuming && fileLen > 0) { // continue download List
list = new ArrayList
(); list.add(new BasicHeader("Range", "bytes=" + fileLen + "-")); headers = list.toArray(new Header[list.size()]); } + else if (fileLen > 0) { + // Remove previous downloaded context + try { + PrintWriter writer = new PrintWriter(tempFile); + writer.print(""); + writer.close(); + } + // Not found then nothing to do + catch (FileNotFoundException e) {} + } task.handle = downloader._httpClient.get(Cocos2dxHelper.getActivity(), url, headers, null, task.handler); - //task.handle = downloader._httpClient.get(url, task.handler); } while (false); if (null == task.handle) { From 74667913c6b91f92ba23fd7049d36854e3c535cb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:45:49 +0800 Subject: [PATCH 09/10] Upgrade AssetsManagerEx 1. Support size parameter to collect total byte size before update process 2. Remove temporary assets when temporary manifest is invalid or out of date 3. Support customized version compare handle to compare manifests versions 4. Support downloaded file verification callback 5. Support max concurrent tasks setting and set default to 32 --- .../assets-manager/AssetsManagerEx.cpp | 273 +++++++++++++----- .../assets-manager/AssetsManagerEx.h | 54 +++- native/extensions/assets-manager/Manifest.cpp | 72 ++++- native/extensions/assets-manager/Manifest.h | 14 + 4 files changed, 315 insertions(+), 98 deletions(-) diff --git a/native/extensions/assets-manager/AssetsManagerEx.cpp b/native/extensions/assets-manager/AssetsManagerEx.cpp index e7d0fee7c0..e96ffe2a62 100644 --- a/native/extensions/assets-manager/AssetsManagerEx.cpp +++ b/native/extensions/assets-manager/AssetsManagerEx.cpp @@ -35,9 +35,6 @@ #endif #include "base/CCAsyncTaskPool.h" -using namespace cocos2d; -using namespace std; - NS_CC_EXT_BEGIN #define VERSION_FILENAME "version.manifest" @@ -65,11 +62,15 @@ AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::stri , _localManifest(nullptr) , _tempManifest(nullptr) , _remoteManifest(nullptr) -, _waitToUpdate(false) +, _updateEntry(UpdateEntry::NONE) , _percent(0) , _percentByFile(0) , _totalToDownload(0) , _totalWaitToDownload(0) +, _maxConcurrentTask(32) +, _currConcurrentTask(0) +, _versionCompareHandle(nullptr) +, _verifyCallback(nullptr) , _inited(false) { // Init variables @@ -77,13 +78,12 @@ AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::stri std::string pointer = StringUtils::format("%p", this); _eventName = EventListenerAssetsManagerEx::LISTENER_ID + pointer; _fileUtils = FileUtils::getInstance(); - _updateState = State::UNCHECKED; _downloader = std::shared_ptr(new network::Downloader); // _downloader->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); - _downloader->onTaskError = bind(&AssetsManagerEx::onError, this, placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4); + _downloader->onTaskError = std::bind(&AssetsManagerEx::onError, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4); _downloader->onTaskProgress = [this](const network::DownloadTask& task, - int64_t bytesReceived, + int64_t /*bytesReceived*/, int64_t totalBytesReceived, int64_t totalBytesExpected) { @@ -142,7 +142,9 @@ void AssetsManagerEx::initManifests(const std::string& manifestUrl) { _tempManifest->parse(_tempManifestPath); if (!_tempManifest->isLoaded() && _fileUtils->isFileExist(_tempManifestPath)) + { _fileUtils->removeFile(_tempManifestPath); + } } else { @@ -178,7 +180,7 @@ void AssetsManagerEx::prepareLocalManifest() _localManifest->prependSearchPaths(); } -void AssetsManagerEx::loadLocalManifest(const std::string& manifestUrl) +void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/) { Manifest *cachedManifest = nullptr; // Find the cached manifest file @@ -202,7 +204,8 @@ void AssetsManagerEx::loadLocalManifest(const std::string& manifestUrl) { // Compare with cached manifest to determine which one to use if (cachedManifest) { - if (strcmp(_localManifest->getVersion().c_str(), cachedManifest->getVersion().c_str()) > 0) + bool localNewer = _localManifest->versionGreater(cachedManifest, _versionCompareHandle); + if (localNewer) { // Recreate storage, to empty the content _fileUtils->removeDirectory(_storagePath); @@ -347,6 +350,16 @@ bool AssetsManagerEx::decompress(const std::string &zip) } else { + // Create all directories in advance to avoid issue + std::string dir = basename(fullPath); + if (!_fileUtils->isDirectoryExist(dir)) { + if (!_fileUtils->createDirectory(dir)) { + // Failed to create directory + CCLOG("AssetsManagerEx : can not create directory %s\n", fullPath.c_str()); + unzClose(zipfile); + return false; + } + } // Entry is a file, so extract it. // Open current file. if (unzOpenCurrentFile(zipfile) != UNZ_OK) @@ -360,7 +373,7 @@ bool AssetsManagerEx::decompress(const std::string &zip) FILE *out = fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), "wb"); if (!out) { - CCLOG("AssetsManagerEx : can not create decompress destination file %s\n", fullPath.c_str()); + CCLOG("AssetsManagerEx : can not create decompress destination file %s (errno: %d)\n", fullPath.c_str(), errno); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; @@ -423,6 +436,32 @@ void AssetsManagerEx::decompressDownloadedZip() void AssetsManagerEx::dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, const std::string &assetId/* = ""*/, const std::string &message/* = ""*/, int curle_code/* = CURLE_OK*/, int curlm_code/* = CURLM_OK*/) { + switch (code) + { + case EventAssetsManagerEx::EventCode::ERROR_UPDATING: + case EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST: + case EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST: + case EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS: + case EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST: + case EventAssetsManagerEx::EventCode::UPDATE_FAILED: + case EventAssetsManagerEx::EventCode::UPDATE_FINISHED: + case EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE: + _updateEntry = UpdateEntry::NONE; + break; + case EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION: + break; + case EventAssetsManagerEx::EventCode::ASSET_UPDATED: + break; + case EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND: + if (_updateEntry == UpdateEntry::CHECK_UPDATE) + { + _updateEntry = UpdateEntry::NONE; + } + break; + default: + break; + } + EventAssetsManagerEx event(_eventName, this, code, _percent, _percentByFile, assetId, message, curle_code, curlm_code); _eventDispatcher->dispatchEvent(&event); } @@ -469,18 +508,21 @@ void AssetsManagerEx::parseVersion() } else { - if (_localManifest->versionEquals(_remoteManifest)) + if (_localManifest->versionGreater(_remoteManifest, _versionCompareHandle)) { _updateState = State::UP_TO_DATE; dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE); } else { + // Save the old update entry type since its value may be changed in event listener. + UpdateEntry oldUpdateEntry = _updateEntry; + _updateState = State::NEED_UPDATE; dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND); // Wait to update so continue the process - if (_waitToUpdate) + if (oldUpdateEntry == UpdateEntry::DO_UPDATE) { _updateState = State::PREDOWNLOAD_MANIFEST; downloadManifest(); @@ -525,13 +567,13 @@ void AssetsManagerEx::parseManifest() if (!_remoteManifest->isLoaded()) { - CCLOG("AssetsManagerEx : Error parsing manifest file\n"); + CCLOG("AssetsManagerEx : Error parsing manifest file, %s", _tempManifestPath.c_str()); dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST); _updateState = State::UNCHECKED; } else { - if (_localManifest->versionEquals(_remoteManifest)) + if (_localManifest->versionGreater(_remoteManifest, _versionCompareHandle)) { _updateState = State::UP_TO_DATE; dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE); @@ -541,7 +583,7 @@ void AssetsManagerEx::parseManifest() _updateState = State::NEED_UPDATE; dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND); - if (_waitToUpdate) + if (_updateEntry == UpdateEntry::DO_UPDATE) { startUpdate(); } @@ -577,10 +619,11 @@ void AssetsManagerEx::startUpdate() // Check difference else { - // Temporary manifest not exists or out of date, - // it will be used to register the download states of each asset, - // in this case, it equals remote manifest. + // Remove all temp files + _tempManifest->cleanupDownloadingAssets(); _tempManifest->release(); + // Temporary manifest will be used to register the download states of each asset, + // in this case, it equals remote manifest. _tempManifest = _remoteManifest; std::unordered_map diff_map = _localManifest->genDiff(_remoteManifest); @@ -610,10 +653,11 @@ void AssetsManagerEx::startUpdate() unit.customId = it->first; unit.srcUrl = packageUrl + path; unit.storagePath = _storagePath + path; + unit.size = diff.asset.size; _downloadUnits.emplace(unit.customId, unit); } } - // Set other assets' downloadState to SUCCESSED + // Set other assets' downloadState to SUCCEED auto &assets = _remoteManifest->getAssets(); for (auto it = assets.cbegin(); it != assets.cend(); ++it) { @@ -631,8 +675,6 @@ void AssetsManagerEx::startUpdate() dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, "", msg); } } - - _waitToUpdate = false; } void AssetsManagerEx::updateSucceed() @@ -695,6 +737,12 @@ void AssetsManagerEx::updateSucceed() void AssetsManagerEx::checkUpdate() { + if (_updateEntry != UpdateEntry::NONE) + { + CCLOGERROR("AssetsManagerEx::checkUpdate, updateEntry isn't NONE"); + return; + } + if (!_inited){ CCLOG("AssetsManagerEx : Manifests uninited.\n"); dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); @@ -707,6 +755,8 @@ void AssetsManagerEx::checkUpdate() return; } + _updateEntry = UpdateEntry::CHECK_UPDATE; + switch (_updateState) { case State::UNCHECKED: case State::PREDOWNLOAD_VERSION: @@ -732,6 +782,12 @@ void AssetsManagerEx::checkUpdate() void AssetsManagerEx::update() { + if (_updateEntry != UpdateEntry::NONE) + { + CCLOGERROR("AssetsManagerEx::update, updateEntry isn't NONE"); + return; + } + if (!_inited){ CCLOG("AssetsManagerEx : Manifests uninited.\n"); dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST); @@ -744,7 +800,7 @@ void AssetsManagerEx::update() return; } - _waitToUpdate = true; + _updateEntry = UpdateEntry::DO_UPDATE; switch (_updateState) { case State::UNCHECKED: @@ -777,7 +833,6 @@ void AssetsManagerEx::update() // Manifest not loaded yet if (!_remoteManifest->isLoaded()) { - _waitToUpdate = true; _updateState = State::PREDOWNLOAD_MANIFEST; downloadManifest(); } @@ -790,7 +845,7 @@ void AssetsManagerEx::update() case State::UP_TO_DATE: case State::UPDATING: case State::UNZIPPING: - _waitToUpdate = false; + _updateEntry = UpdateEntry::NONE; break; default: break; @@ -807,16 +862,18 @@ void AssetsManagerEx::updateAssets(const DownloadUnits& assets) if (_updateState != State::UPDATING && _localManifest->isLoaded() && _remoteManifest->isLoaded()) { - int size = (int)(assets.size()); - if (size > 0) + _updateState = State::UPDATING; + _downloadUnits.clear(); + _downloadedSize.clear(); + _percent = _percentByFile = _sizeCollected = _totalSize = 0; + _totalWaitToDownload = _totalToDownload = (int)assets.size(); + _totalEnabled = false; + if (_totalToDownload > 0) { - _updateState = State::UPDATING; - _downloadUnits.clear(); _downloadUnits = assets; - _totalWaitToDownload = _totalToDownload = (int)_downloadUnits.size(); this->batchDownload(); } - else if (size == 0 && _totalWaitToDownload == 0) + else if (_totalToDownload == 0) { updateSucceed(); } @@ -834,6 +891,58 @@ void AssetsManagerEx::downloadFailedAssets() updateAssets(_failedUnits); } +void AssetsManagerEx::fileError(const std::string& identifier, const std::string& errorStr, int errorCode, int errorCodeInternal) +{ + auto unitIt = _downloadUnits.find(identifier); + // Found unit and add it to failed units + if (unitIt != _downloadUnits.end()) + { + _totalWaitToDownload--; + + DownloadUnit unit = unitIt->second; + _failedUnits.emplace(unit.customId, unit); + } + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_UPDATING, identifier, errorStr, errorCode, errorCodeInternal); + _tempManifest->setAssetDownloadState(identifier, Manifest::DownloadState::UNSTARTED); + + _currConcurrentTask = MAX(0, _currConcurrentTask-1); + queueDowload(); +} + +void AssetsManagerEx::fileSuccess(const std::string &customId, const std::string &storagePath, bool compressed) +{ + // Set download state to SUCCESSED + _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED); + + // Add file to need decompress list + if (compressed) { + _compressedFiles.push_back(storagePath); + } + + auto unitIt = _failedUnits.find(customId); + // Found unit and delete it + if (unitIt != _failedUnits.end()) + { + // Remove from failed units list + _failedUnits.erase(unitIt); + } + + unitIt = _downloadUnits.find(customId); + if (unitIt != _downloadUnits.end()) + { + // Reduce count only when unit found in _downloadUnits + _totalWaitToDownload--; + + _percentByFile = 100 * (float)(_totalToDownload - _totalWaitToDownload) / _totalToDownload; + // Notify progression event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, ""); + } + // Notify asset updated event + dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ASSET_UPDATED, customId); + + _currConcurrentTask = MAX(0, _currConcurrentTask-1); + queueDowload(); +} void AssetsManagerEx::onError(const network::DownloadTask& task, int errorCode, @@ -853,25 +962,11 @@ void AssetsManagerEx::onError(const network::DownloadTask& task, } else { - auto unitIt = _downloadUnits.find(task.identifier); - // Found unit and add it to failed units - if (unitIt != _downloadUnits.end()) - { - _totalWaitToDownload--; - - DownloadUnit unit = unitIt->second; - _failedUnits.emplace(unit.customId, unit); - } - dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_UPDATING, task.identifier, errorStr, errorCode, errorCodeInternal); - - if (_totalWaitToDownload <= 0) - { - this->onDownloadUnitsFinished(); - } + fileError(task.identifier, errorStr, errorCode, errorCodeInternal); } } -void AssetsManagerEx::onProgress(double total, double downloaded, const std::string &url, const std::string &customId) +void AssetsManagerEx::onProgress(double total, double downloaded, const std::string& /*url*/, const std::string &customId) { if (customId == VERSION_ID || customId == MANIFEST_ID) { @@ -901,12 +996,16 @@ void AssetsManagerEx::onProgress(double total, double downloaded, const std::str _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::DOWNLOADING); // Register the download size information _downloadedSize.emplace(customId, downloaded); - _totalSize += total; - _sizeCollected++; - // All collected, enable total size - if (_sizeCollected == _totalToDownload) + // Check download unit size existance, if not exist collect size in total size + if (_downloadUnits[customId].size == 0) { - _totalEnabled = true; + _totalSize += total; + _sizeCollected++; + // All collected, enable total size + if (_sizeCollected == _totalToDownload) + { + _totalEnabled = true; + } } } @@ -923,7 +1022,7 @@ void AssetsManagerEx::onProgress(double total, double downloaded, const std::str } } -void AssetsManagerEx::onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId) +void AssetsManagerEx::onSuccess(const std::string &/*srcUrl*/, const std::string &storagePath, const std::string &customId) { if (customId == VERSION_ID) { @@ -937,43 +1036,26 @@ void AssetsManagerEx::onSuccess(const std::string &srcUrl, const std::string &st } else { + bool ok = true; auto &assets = _remoteManifest->getAssets(); auto assetIt = assets.find(customId); if (assetIt != assets.end()) { - // Set download state to SUCCESSED - _tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED); - - // Add file to need decompress list - if (assetIt->second.compressed) { - _compressedFiles.push_back(storagePath); + Manifest::Asset asset = assetIt->second; + if (_verifyCallback != nullptr) + { + ok = _verifyCallback(storagePath, asset); } } - auto unitIt = _downloadUnits.find(customId); - if (unitIt != _downloadUnits.end()) + if (ok) { - // Reduce count only when unit found in _downloadUnits - _totalWaitToDownload--; - - _percentByFile = 100 * (float)(_totalToDownload - _totalWaitToDownload) / _totalToDownload; - // Notify progression event - dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, ""); + bool compressed = assetIt != assets.end() ? assetIt->second.compressed : false; + fileSuccess(customId, storagePath, compressed); } - // Notify asset updated event - dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ASSET_UPDATED, customId); - - unitIt = _failedUnits.find(customId); - // Found unit and delete it - if (unitIt != _failedUnits.end()) + else { - // Remove from failed units list - _failedUnits.erase(unitIt); - } - - if (_totalWaitToDownload <= 0) - { - this->onDownloadUnitsFinished(); + fileError(customId, "Asset file verification failed after downloaded"); } } } @@ -986,9 +1068,42 @@ void AssetsManagerEx::destroyDownloadedVersion() void AssetsManagerEx::batchDownload() { + _queue.clear(); for(auto iter : _downloadUnits) { DownloadUnit& unit = iter.second; + if (unit.size > 0) + { + _totalSize += unit.size; + _sizeCollected++; + } + + _queue.push_back(iter.first); + } + // All collected, enable total size + if (_sizeCollected == _totalToDownload) + { + _totalEnabled = true; + } + + queueDowload(); +} + +void AssetsManagerEx::queueDowload() +{ + if (_totalWaitToDownload == 0) + { + this->onDownloadUnitsFinished(); + return; + } + + while (_currConcurrentTask < _maxConcurrentTask && _queue.size() > 0) + { + std::string key = _queue.back(); + _queue.pop_back(); + + _currConcurrentTask++; + DownloadUnit& unit = _downloadUnits[key]; _downloader->createDownloadFileTask(unit.srcUrl, unit.storagePath, unit.customId); } } diff --git a/native/extensions/assets-manager/AssetsManagerEx.h b/native/extensions/assets-manager/AssetsManagerEx.h index ec8b17e80d..703cf58287 100644 --- a/native/extensions/assets-manager/AssetsManagerEx.h +++ b/native/extensions/assets-manager/AssetsManagerEx.h @@ -100,14 +100,32 @@ public: */ const std::string& getStoragePath() const; - /** @brief Function for retrieve the local manifest object + /** @brief Function for retrieving the local manifest object */ const Manifest* getLocalManifest() const; - /** @brief Function for retrieve the remote manifest object + /** @brief Function for retrieving the remote manifest object */ const Manifest* getRemoteManifest() const; + /** @brief Function for retrieving the max concurrent task count + */ + const int getMaxConcurrentTask() const {return _maxConcurrentTask;}; + + /** @brief Function for setting the max concurrent task count + */ + void setMaxConcurrentTask(const int max) {_maxConcurrentTask = max;}; + + /** @brief Set the handle function for comparing manifests versions + * @param handle The compare function + */ + void setVersionCompareHandle(const std::function& handle) {_versionCompareHandle = handle;}; + + /** @brief Set the verification function for checking whether downloaded asset is correct, e.g. using md5 verification + * @param callback The verify callback function + */ + void setVerifyCallback(const std::function& callback) {_verifyCallback = callback;}; + CC_CONSTRUCTOR_ACCESS: AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath); @@ -153,6 +171,14 @@ protected: */ void destroyDownloadedVersion(); + /** @brief Download items in queue with max concurrency setting + */ + void queueDowload(); + + void fileError(const std::string& identifier, const std::string& errorStr, int errorCode = 0, int errorCodeInternal = 0); + + void fileSuccess(const std::string &customId, const std::string &storagePath, bool compressed); + /** @brief Call back function for error handling, the error will then be reported to user's listener registed in addUpdateEventListener @param error The error object contains ErrorCode, message, asset url, asset key @@ -235,7 +261,14 @@ private: Manifest *_remoteManifest; //! Whether user have requested to update - bool _waitToUpdate; + enum class UpdateEntry : char + { + NONE, + CHECK_UPDATE, + DO_UPDATE + }; + + UpdateEntry _updateEntry; //! All assets unit to download DownloadUnits _downloadUnits; @@ -243,6 +276,15 @@ private: //! All failed units DownloadUnits _failedUnits; + //! Download queue + std::vector _queue; + + //! Max concurrent task count for downloading + int _maxConcurrentTask; + + //! Current concurrent task count + int _currConcurrentTask; + //! All files to be decompressed std::vector _compressedFiles; @@ -269,6 +311,12 @@ private: //! Total number of assets still waiting to be downloaded int _totalWaitToDownload; + //! Handle function to compare versions between different manifests + std::function _versionCompareHandle; + + //! Callback function to verify the downloaded assets + std::function _verifyCallback; + //! Marker for whether the assets manager is inited bool _inited; }; diff --git a/native/extensions/assets-manager/Manifest.cpp b/native/extensions/assets-manager/Manifest.cpp index dbc18972f7..05faf3a08a 100644 --- a/native/extensions/assets-manager/Manifest.cpp +++ b/native/extensions/assets-manager/Manifest.cpp @@ -42,6 +42,7 @@ #define KEY_MD5 "md5" #define KEY_GROUP "group" #define KEY_COMPRESSED "compressed" +#define KEY_SIZE "size" #define KEY_COMPRESSED_FILE "compressedFile" #define KEY_DOWNLOAD_STATE "downloadState" @@ -156,16 +157,36 @@ bool Manifest::versionEquals(const Manifest *b) const return true; } +bool Manifest::versionGreater(const Manifest *b, const std::function& handle) const +{ + std::string localVersion = getVersion(); + std::string bVersion = b->getVersion(); + bool greater; + if (handle) + { + greater = handle(localVersion, bVersion); + } + else + { + greater = strcmp(localVersion.c_str(), bVersion.c_str()) >= 0; + } + return greater; +} + std::unordered_map Manifest::genDiff(const Manifest *b) const { std::unordered_map diff_map; const std::unordered_map &bAssets = b->getAssets(); + std::string key; + Asset valueA; + Asset valueB; + std::unordered_map::const_iterator valueIt, it; for (it = _assets.begin(); it != _assets.end(); ++it) { - const auto &key = it->first; - const auto &valueA = it->second; + key = it->first; + valueA = it->second; // Deleted valueIt = bAssets.find(key); @@ -178,7 +199,7 @@ std::unordered_map Manifest::genDiff(const Man } // Modified - auto &valueB = valueIt->second; + valueB = valueIt->second; if (valueA.md5 != valueB.md5) { AssetDiff diff; diff.asset = valueB; @@ -189,8 +210,8 @@ std::unordered_map Manifest::genDiff(const Man for (it = bAssets.begin(); it != bAssets.end(); ++it) { - const auto &key = it->first; - const auto &valueB = it->second; + key = it->first; + valueB = it->second; // Added valueIt = _assets.find(key); @@ -217,11 +238,26 @@ void Manifest::genResumeAssetsList(DownloadUnits *units) const unit.customId = it->first; unit.srcUrl = _packageUrl + asset.path; unit.storagePath = _manifestRoot + asset.path; + unit.size = asset.size; units->emplace(unit.customId, unit); } } } +void Manifest::cleanupDownloadingAssets() const +{ + for (auto it = _assets.begin(); it != _assets.end(); ++it) + { + Asset asset = it->second; + + if (asset.downloadState == DownloadState::DOWNLOADING) + { + std::string storagePath = _manifestRoot + asset.path; + _fileUtils->removeFile(storagePath); + } + } +} + std::vector Manifest::getSearchPaths() const { std::vector searchPaths; @@ -321,18 +357,16 @@ void Manifest::setAssetDownloadState(const std::string &key, const Manifest::Dow rapidjson::Value &assets = _json[KEY_ASSETS]; if (assets.IsObject()) { - for (rapidjson::Value::MemberIterator itr = assets.MemberBegin(); itr != assets.MemberEnd(); ++itr) + if (assets.HasMember(key.c_str())) { - if (key.compare(itr->name.GetString()) == 0) { - rapidjson::Value &entry = itr->value; - if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) - { - entry[KEY_DOWNLOAD_STATE].SetInt((int) state); - } - else - { - entry.AddMember(KEY_DOWNLOAD_STATE, (int)state, _json.GetAllocator()); - } + rapidjson::Value &entry = assets[key.c_str()]; + if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) + { + entry[KEY_DOWNLOAD_STATE].SetInt((int) state); + } + else + { + entry.AddMember(KEY_DOWNLOAD_STATE, (int)state, _json.GetAllocator()); } } } @@ -386,6 +420,12 @@ Manifest::Asset Manifest::parseAsset(const std::string &path, const rapidjson::V } else asset.compressed = false; + if ( json.HasMember(KEY_SIZE) && json[KEY_SIZE].IsFloat() ) + { + asset.size = json[KEY_COMPRESSED].GetFloat(); + } + else asset.size = 0; + if ( json.HasMember(KEY_DOWNLOAD_STATE) && json[KEY_DOWNLOAD_STATE].IsInt() ) { asset.downloadState = (DownloadState)(json[KEY_DOWNLOAD_STATE].GetInt()); diff --git a/native/extensions/assets-manager/Manifest.h b/native/extensions/assets-manager/Manifest.h index 437ffbdb1e..1bcc479379 100644 --- a/native/extensions/assets-manager/Manifest.h +++ b/native/extensions/assets-manager/Manifest.h @@ -43,6 +43,7 @@ struct DownloadUnit std::string srcUrl; std::string storagePath; std::string customId; + float size; }; typedef std::unordered_map DownloadUnits; @@ -71,6 +72,7 @@ public: std::string md5; std::string path; bool compressed; + float size; DownloadState downloadState; }; @@ -132,9 +134,17 @@ protected: /** @brief Check whether the version of this manifest equals to another. * @param b The other manifest + * @return Equal or not */ bool versionEquals(const Manifest *b) const; + /** @brief Check whether the version of this manifest is greater than another. + * @param b The other manifest + * @param [handle] Customized comparasion handle function + * @return Greater or not + */ + bool versionGreater(const Manifest *b, const std::function& handle) const; + /** @brief Generate difference between this Manifest and another. * @param b The other manifest */ @@ -145,6 +155,10 @@ protected: */ void genResumeAssetsList(DownloadUnits *units) const; + /** @brief Cleanup assets that is in downloading state for resuming + */ + void cleanupDownloadingAssets() const; + /** @brief Prepend all search paths to the FileUtils. */ void prependSearchPaths(); From a151dc2b44e50473532f5b53e01c5b82e29e8d20 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Jan 2017 16:46:57 +0800 Subject: [PATCH 10/10] Fix spTrackEntry binding cause native proxy assert fail --- .../spine/jsb_cocos2dx_spine_manual.cpp | 142 ++++++++++++------ 1 file changed, 100 insertions(+), 42 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/spine/jsb_cocos2dx_spine_manual.cpp b/native/cocos/scripting/js-bindings/manual/spine/jsb_cocos2dx_spine_manual.cpp index 1279ea7c48..decc8e8832 100644 --- a/native/cocos/scripting/js-bindings/manual/spine/jsb_cocos2dx_spine_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/spine/jsb_cocos2dx_spine_manual.cpp @@ -28,6 +28,8 @@ using namespace spine; +std::unordered_map _spTrackEntryMap; + jsval speventdata_to_jsval(JSContext* cx, spEventData& v) { JS::RootedObject tmp(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr())); @@ -273,9 +275,13 @@ jsval spanimation_to_jsval(JSContext* cx, spAnimation& v) return JSVAL_NULL; } -bool jsb_spine_TrackEntry_get_next(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) +JSClass *jsb_spine_TrackEntry_class; +JSObject *jsb_spine_TrackEntry_prototype; + +bool jsb_spine_TrackEntry_get_next(JSContext *cx, uint32_t argc, jsval *vp) { - JS::RootedObject jsthis(cx, obj); + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject jsthis(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(jsthis); spTrackEntry* cobj = (spTrackEntry *)(proxy ? proxy->ptr : NULL); if (cobj) { @@ -284,7 +290,7 @@ bool jsb_spine_TrackEntry_get_next(JSContext *cx, JS::HandleObject obj, JS::Hand { jsret = sptrackentry_to_jsval(cx, *cobj->next); } - vp.set(jsret); + args.rval().set(jsret); return true; } else { @@ -293,9 +299,10 @@ bool jsb_spine_TrackEntry_get_next(JSContext *cx, JS::HandleObject obj, JS::Hand } } -bool jsb_spine_TrackEntry_get_mixingFrom(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) +bool jsb_spine_TrackEntry_get_mixingFrom(JSContext *cx, uint32_t argc, jsval *vp) { - JS::RootedObject jsthis(cx, obj); + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject jsthis(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(jsthis); spTrackEntry* cobj = (spTrackEntry *)(proxy ? proxy->ptr : NULL); if (cobj) { @@ -304,7 +311,7 @@ bool jsb_spine_TrackEntry_get_mixingFrom(JSContext *cx, JS::HandleObject obj, JS { jsret = sptrackentry_to_jsval(cx, *cobj->mixingFrom); } - vp.set(jsret); + args.rval().set(jsret); return true; } else { @@ -313,51 +320,100 @@ bool jsb_spine_TrackEntry_get_mixingFrom(JSContext *cx, JS::HandleObject obj, JS } } +void js_spine_TrackEntry_finalize(JSFreeOp *fop, JSObject *obj) { + std::unordered_map::iterator existed = _spTrackEntryMap.begin(); + while (existed != _spTrackEntryMap.end()) { + if (existed->second == obj) + { + _spTrackEntryMap.erase(existed); + break; + } + ++existed; + } +} + +void js_register_spine_TrackEntry(JSContext *cx, JS::HandleObject global) +{ + jsb_spine_TrackEntry_class = (JSClass *)calloc(1, sizeof(JSClass)); + jsb_spine_TrackEntry_class->name = "TrackEntry"; + jsb_spine_TrackEntry_class->addProperty = JS_PropertyStub; + jsb_spine_TrackEntry_class->delProperty = JS_DeletePropertyStub; + jsb_spine_TrackEntry_class->getProperty = JS_PropertyStub; + jsb_spine_TrackEntry_class->setProperty = JS_StrictPropertyStub; + jsb_spine_TrackEntry_class->enumerate = JS_EnumerateStub; + jsb_spine_TrackEntry_class->resolve = JS_ResolveStub; + jsb_spine_TrackEntry_class->convert = JS_ConvertStub; + jsb_spine_TrackEntry_class->finalize = js_spine_TrackEntry_finalize; + jsb_spine_TrackEntry_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); + + static JSPropertySpec properties[] = + { + JS_PSG("mixingFrom", jsb_spine_TrackEntry_get_mixingFrom, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_PSG("next", jsb_spine_TrackEntry_get_next, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_PS_END + }; + + jsb_spine_TrackEntry_prototype = JS_InitClass(cx, global, JS::NullPtr(), jsb_spine_TrackEntry_class, nullptr, 0, properties, nullptr, nullptr, nullptr); +} + jsval sptrackentry_to_jsval(JSContext* cx, spTrackEntry& v) { - js_proxy_t *proxy = jsb_get_native_proxy(&v); - if (proxy) + JS::RootedObject entry(cx); + std::unordered_map::iterator existed = _spTrackEntryMap.find(&v); + bool found = existed != _spTrackEntryMap.end(); + if (found) { - JS::RootedObject entry(cx, proxy->obj); - return OBJECT_TO_JSVAL(entry); + entry.set(existed->second); } else { - JS::RootedObject tmp(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr())); - if (!tmp) return JSVAL_NULL; - - jsb_new_proxy(&v, tmp); - js_add_FinalizeHook(cx, tmp, false); - -#if COCOS2D_DEBUG > 1 - CCLOG("++++++WEAK_REF++++++ Cpp(spine::TrackEntry): %p - JS: %p", &v, tmp.get()); -#endif // COCOS2D_DEBUG - - JS::RootedValue jsanimation(cx, spanimation_to_jsval(cx, *v.animation)); - bool ok = JS_DefineProperty(cx, tmp, "delay", v.delay, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "trackIndex", v.trackIndex, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "trackTime", v.trackTime, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "trackLast", v.trackLast, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "trackEnd", v.trackEnd, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "nextTrackLast", v.nextTrackLast, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "timeScale", v.timeScale, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "mixTime", v.mixTime, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "mixDuration", v.mixDuration, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "animationStart", v.animationStart, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "animationEnd", v.animationEnd, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "animationLast", v.animationLast, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "nextAnimationLast", v.nextAnimationLast, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "animation", jsanimation, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "next", JS::UndefinedHandleValue, JSPROP_ENUMERATE | JSPROP_PERMANENT, jsb_spine_TrackEntry_get_next) && - JS_DefineProperty(cx, tmp, "mixingFrom", JS::UndefinedHandleValue, JSPROP_ENUMERATE | JSPROP_PERMANENT, jsb_spine_TrackEntry_get_mixingFrom); + JS::RootedObject proto(cx, jsb_spine_TrackEntry_prototype); + entry.set(JS_NewObject(cx, jsb_spine_TrackEntry_class, proto, JS::NullPtr())); + } + + JS::RootedValue entryVal(cx, OBJECT_TO_JSVAL(entry)); + if (entryVal.isObject()) + { + JS::RootedValue val(cx, DOUBLE_TO_JSVAL(v.delay)); + bool ok = JS_SetProperty(cx, entry, "delay", val); + val.set(DOUBLE_TO_JSVAL(v.trackIndex)); + ok &= JS_SetProperty(cx, entry, "trackIndex", val); + val.set(DOUBLE_TO_JSVAL(v.trackTime)); + ok &= JS_SetProperty(cx, entry, "trackTime", val); + val.set(DOUBLE_TO_JSVAL(v.trackLast)); + ok &= JS_SetProperty(cx, entry, "trackLast", val); + val.set(DOUBLE_TO_JSVAL(v.trackEnd)); + ok &= JS_SetProperty(cx, entry, "trackEnd", val); + val.set(DOUBLE_TO_JSVAL(v.nextTrackLast)); + ok &= JS_SetProperty(cx, entry, "nextTrackLast", val); + val.set(DOUBLE_TO_JSVAL(v.timeScale)); + ok &= JS_SetProperty(cx, entry, "timeScale", val); + val.set(DOUBLE_TO_JSVAL(v.mixTime)); + ok &= JS_SetProperty(cx, entry, "mixTime", val); + val.set(DOUBLE_TO_JSVAL(v.mixDuration)); + ok &= JS_SetProperty(cx, entry, "mixDuration", val); + val.set(DOUBLE_TO_JSVAL(v.animationStart)); + ok &= JS_SetProperty(cx, entry, "animationStart", val); + val.set(DOUBLE_TO_JSVAL(v.animationEnd)); + ok &= JS_SetProperty(cx, entry, "animationEnd", val); + val.set(DOUBLE_TO_JSVAL(v.animationLast)); + ok &= JS_SetProperty(cx, entry, "animationLast", val); + val.set(DOUBLE_TO_JSVAL(v.nextAnimationLast)); + ok &= JS_SetProperty(cx, entry, "nextAnimationLast", val); + val.set(spanimation_to_jsval(cx, *v.animation)); + ok &= JS_SetProperty(cx, entry, "animation", val); if (ok) { - return OBJECT_TO_JSVAL(tmp); + if (!found) + { + _spTrackEntryMap.emplace(&v, entry); + } + return entryVal; } - - return JSVAL_NULL; } + + return JSVAL_NULL; } bool jsb_cocos2dx_spine_findBone(JSContext *cx, uint32_t argc, jsval *vp) @@ -621,8 +677,8 @@ bool jsb_cocos2dx_spine_addAnimation(JSContext *cx, uint32_t argc, jsval *vp) args.rval().set(jsret); return true; - } - + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); return false; } @@ -633,6 +689,8 @@ extern JSObject* jsb_spine_SkeletonAnimation_prototype; void register_all_cocos2dx_spine_manual(JSContext* cx, JS::HandleObject global) { + js_register_spine_TrackEntry(cx, global); + JS::RootedObject skeletonRenderer(cx, jsb_spine_SkeletonRenderer_prototype); JS_DefineFunction(cx, skeletonRenderer, "findBone", jsb_cocos2dx_spine_findBone, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, skeletonRenderer, "findSlot", jsb_cocos2dx_spine_findSlot, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT);