From 769628d4144f6610dfb7df8d8db7a93cb8cab08f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 20 Sep 2017 00:08:17 +0800 Subject: [PATCH 1/6] load image for existing texture --- native/cocos/renderer/CCTextureCache.cpp | 130 ++++++++++++------ native/cocos/renderer/CCTextureCache.h | 12 +- .../auto/api/jsb_cocos2dx_auto_api.js | 18 ++- .../js-bindings/auto/jsb_cocos2dx_auto.cpp | 67 ++++++++- .../js-bindings/auto/jsb_cocos2dx_auto.hpp | 3 +- .../manual/jsb_cocos2dx_extension_manual.cpp | 78 +++++++++++ 6 files changed, 257 insertions(+), 51 deletions(-) diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index 30ef33b4fe..a90b1d137b 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -83,16 +83,43 @@ std::string TextureCache::getDescription() const struct TextureCache::AsyncStruct { public: - AsyncStruct(const std::string& fn, std::function f) : filename(fn), callback(f), pixelFormat(Texture2D::getDefaultAlphaPixelFormat()), loadSuccess(false) {} + AsyncStruct(const std::string& fn, std::function f) : filename(fn), callback(f), pixelFormat(Texture2D::getDefaultAlphaPixelFormat()), texture(nullptr), loadSuccess(false) {} std::string filename; std::function callback; Image image; Image imageAlpha; Texture2D::PixelFormat pixelFormat; + Texture2D* texture; // optional, existing texture to init bool loadSuccess; }; +void TextureCache::enqueueAsyncStruct(AsyncStruct* data) +{ + // lazy init + if (_loadingThread == nullptr) + { + // create a new thread to load images + _loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this); + _needQuit = false; + } + + if (0 == _asyncRefCount) + { + Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false); + } + + ++_asyncRefCount; + + // add async struct into queue + _asyncStructQueue.push_back(data); + _requestMutex.lock(); + _requestQueue.push_back(data); + _requestMutex.unlock(); + + _sleepCondition.notify_one(); +} + /** The addImageAsync logic follow the steps: - find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread) @@ -141,31 +168,30 @@ void TextureCache::addImageAsync(const std::string &path, const std::functiongetScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false); - } - - ++_asyncRefCount; - // generate async struct AsyncStruct *data = new (std::nothrow) AsyncStruct(fullpath, callback); - // add async struct into queue - _asyncStructQueue.push_back(data); - _requestMutex.lock(); - _requestQueue.push_back(data); - _requestMutex.unlock(); + enqueueAsyncStruct(data); +} - _sleepCondition.notify_one(); +void TextureCache::initImageAsync(Texture2D* texture, const std::string &path, const std::function& callback) +{ + CCASSERT(texture != nullptr, "TextureCache: texture MUST not be nil"); + + std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path); + + // check if file exists + if ( fullpath.empty() || ! FileUtils::getInstance()->isFileExist( fullpath ) ) + { + if (callback) callback(nullptr); + return; + } + + // generate async struct + AsyncStruct *data = new (std::nothrow) AsyncStruct(fullpath, callback); + data->texture = texture; + + enqueueAsyncStruct(data); } void TextureCache::unbindImageAsync(const std::string& filename) @@ -259,21 +285,14 @@ void TextureCache::addImageAsyncCallBack(float dt) break; } - // check the image has been convert to texture or not - auto it = _textures.find(asyncStruct->filename); - if(it != _textures.end()) - { - texture = it->second; - } - else + // check the texture has been provided or not + if (asyncStruct->texture != nullptr) { // convert image to texture if (asyncStruct->loadSuccess) { + texture = asyncStruct->texture; Image* image = &(asyncStruct->image); - // generate texture in render thread - texture = new (std::nothrow) Texture2D(); - texture->initWithImage(image, asyncStruct->pixelFormat); //parse 9-patch info this->parseNinePatchImage(image, texture, asyncStruct->filename); @@ -281,16 +300,49 @@ void TextureCache::addImageAsyncCallBack(float dt) // cache the texture file name VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename); #endif - // cache the texture. retain it, since it is added in the map - _textures.insert( std::make_pair(asyncStruct->filename, texture) ); - texture->retain(); - - texture->autorelease(); - } else { - texture = nullptr; + } + else + { CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); } } + else + { + // check the image has been convert to texture or not + auto it = _textures.find(asyncStruct->filename); + if(it != _textures.end()) + { + texture = it->second; + } + else + { + // convert image to texture + if (asyncStruct->loadSuccess) + { + Image* image = &(asyncStruct->image); + // generate texture in render thread + texture = new (std::nothrow) Texture2D(); + + texture->initWithImage(image, asyncStruct->pixelFormat); + //parse 9-patch info + this->parseNinePatchImage(image, texture, asyncStruct->filename); + #if CC_ENABLE_CACHE_TEXTURE_DATA + // cache the texture file name + VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename); + #endif + // cache the texture. retain it, since it is added in the map + _textures.insert( std::make_pair(asyncStruct->filename, texture) ); + texture->retain(); + + texture->autorelease(); + } + else + { + texture = nullptr; + CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); + } + } + } // call callback function if (asyncStruct->callback) diff --git a/native/cocos/renderer/CCTextureCache.h b/native/cocos/renderer/CCTextureCache.h index 52fdebd64b..51d2e77e76 100644 --- a/native/cocos/renderer/CCTextureCache.h +++ b/native/cocos/renderer/CCTextureCache.h @@ -115,6 +115,14 @@ public: */ virtual void addImageAsync(const std::string &filepath, const std::function& callback); + /** Init a given Texture2D object with a file image. + * It is much the same as addImageAsync, except an existing texture is provided. + @param texture An existing texture. + @param filepath A null terminated string. + @param callback A callback function would be invoked after the image is loaded. + */ + virtual void initImageAsync(Texture2D* texture, const std::string& filepath, const std::function& callback); + /** Unbind a specified bound image asynchronous callback. * In the case an object who was bound to an image asynchronous callback was destroyed before the callback is invoked, * the object always need to unbind this callback manually. @@ -214,13 +222,13 @@ public: private: + struct AsyncStruct; + void enqueueAsyncStruct(AsyncStruct* data); void addImageAsyncCallBack(float dt); void loadImage(); void parseNinePatchImage(Image* image, Texture2D* texture, const std::string& path); public: protected: - struct AsyncStruct; - std::thread* _loadingThread; std::deque _asyncStructQueue; diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index 2f02fd6492..6a79b01176 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -14377,6 +14377,14 @@ texture2d return ; }, +/** + * @method waitForQuit + */ +waitForQuit : function ( +) +{ +}, + /** * @method renameTextureWithKey * @param {String} arg0 @@ -14408,9 +14416,15 @@ texture2d }, /** - * @method waitForQuit + * @method initImageAsync + * @param {cc.Texture2D} arg0 + * @param {String} arg1 + * @param {function} arg2 */ -waitForQuit : function ( +initImageAsync : function ( +texture2d, +str, +func ) { }, diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index 90db4d72df..54a344864f 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -32540,6 +32540,21 @@ static bool js_cocos2dx_TextureCache_getTextureFilePath(se::State& s) } SE_BIND_FUNC(js_cocos2dx_TextureCache_getTextureFilePath) +static bool js_cocos2dx_TextureCache_waitForQuit(se::State& s) +{ + cocos2d::TextureCache* cobj = (cocos2d::TextureCache*)s.nativeThisObject(); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_TextureCache_waitForQuit : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->waitForQuit(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_cocos2dx_TextureCache_waitForQuit) + static bool js_cocos2dx_TextureCache_renameTextureWithKey(se::State& s) { cocos2d::TextureCache* cobj = (cocos2d::TextureCache*)s.nativeThisObject(); @@ -32595,20 +32610,57 @@ static bool js_cocos2dx_TextureCache_removeTexture(se::State& s) } SE_BIND_FUNC(js_cocos2dx_TextureCache_removeTexture) -static bool js_cocos2dx_TextureCache_waitForQuit(se::State& s) +static bool js_cocos2dx_TextureCache_initImageAsync(se::State& s) { cocos2d::TextureCache* cobj = (cocos2d::TextureCache*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_TextureCache_waitForQuit : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_TextureCache_initImageAsync : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - if (argc == 0) { - cobj->waitForQuit(); + CC_UNUSED bool ok = true; + if (argc == 3) { + cocos2d::Texture2D* arg0 = nullptr; + std::string arg1; + std::function arg2; + ok &= seval_to_native_ptr(args[0], &arg0); + ok &= seval_to_std_string(args[1], &arg1); + do { + if (args[2].isObject() && args[2].toObject()->isFunction()) + { + se::Value jsThis(s.thisObject()); + se::Value jsFunc(args[2]); + jsFunc.toObject()->root(); + auto lambda = [=](cocos2d::Texture2D* larg0) -> void { + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + CC_UNUSED bool ok = true; + se::ValueArray args; + args.resize(1); + ok &= native_ptr_to_seval((cocos2d::Texture2D*)larg0, &args[0]); + se::Value rval; + se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; + se::Object* funcObj = jsFunc.toObject(); + bool succeed = funcObj->call(args, thisObj, &rval); + if (!succeed) { + se::ScriptEngine::getInstance()->clearException(); + } + }; + arg2 = lambda; + } + else + { + arg2 = nullptr; + } + } while(false) + ; + SE_PRECONDITION2(ok, false, "js_cocos2dx_TextureCache_initImageAsync : Error processing arguments"); + cobj->initImageAsync(arg0, arg1, arg2); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); return false; } -SE_BIND_FUNC(js_cocos2dx_TextureCache_waitForQuit) +SE_BIND_FUNC(js_cocos2dx_TextureCache_initImageAsync) SE_DECLARE_FINALIZE_FUNC(js_cocos2d_TextureCache_finalize) @@ -32651,10 +32703,11 @@ bool js_register_cocos2dx_TextureCache(se::Object* obj) cls->defineFunction("unbindImageAsync", _SE(js_cocos2dx_TextureCache_unbindImageAsync)); cls->defineFunction("getTextureForKey", _SE(js_cocos2dx_TextureCache_getTextureForKey)); cls->defineFunction("getTextureFilePath", _SE(js_cocos2dx_TextureCache_getTextureFilePath)); + cls->defineFunction("waitForQuit", _SE(js_cocos2dx_TextureCache_waitForQuit)); cls->defineFunction("renameTextureWithKey", _SE(js_cocos2dx_TextureCache_renameTextureWithKey)); cls->defineFunction("removeUnusedTextures", _SE(js_cocos2dx_TextureCache_removeUnusedTextures)); cls->defineFunction("removeTexture", _SE(js_cocos2dx_TextureCache_removeTexture)); - cls->defineFunction("waitForQuit", _SE(js_cocos2dx_TextureCache_waitForQuit)); + cls->defineFunction("initImageAsync", _SE(js_cocos2dx_TextureCache_initImageAsync)); cls->defineFinalizeFunction(_SE(js_cocos2d_TextureCache_finalize)); cls->install(); JSBClassType::registerClass(cls); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp index 3edc087a2d..0bdf9b769d 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -2148,10 +2148,11 @@ SE_DECLARE_FUNC(js_cocos2dx_TextureCache_addImage); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_unbindImageAsync); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_getTextureForKey); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_getTextureFilePath); +SE_DECLARE_FUNC(js_cocos2dx_TextureCache_waitForQuit); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_renameTextureWithKey); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_removeUnusedTextures); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_removeTexture); -SE_DECLARE_FUNC(js_cocos2dx_TextureCache_waitForQuit); +SE_DECLARE_FUNC(js_cocos2dx_TextureCache_initImageAsync); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_TextureCache); extern se::Object* __jsb_cocos2d_Device_proto; diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp index 84ab77ee34..bc5af35a76 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp @@ -126,6 +126,83 @@ static bool js_cocos2dx_extension_loadRemoteImage(se::State& s) } SE_BIND_FUNC(js_cocos2dx_extension_loadRemoteImage) +static bool js_cocos2dx_extension_initRemoteImage(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc != 3) + { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 3); + return false; + } + + bool ok = false; + + // get texture + cocos2d::Texture2D* texture = nullptr; + ok = seval_to_native_ptr(args[0], &texture); + SE_PRECONDITION2(ok, false, "Converting 'texture' failed!"); + + // get url + std::string url; + ok = seval_to_std_string(args[1], &url); + SE_PRECONDITION2(ok, false, "Converting 'url' failed!"); + + // get callback + se::Value func = args[2]; + assert(func.isObject() && func.toObject()->isFunction()); + + func.toObject()->root(); + + auto onCallback = [=](bool success){ + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + se::ValueArray args; + args.resize(1); + + args[0].setBoolean(success); + func.toObject()->call(args, nullptr); + }; + + auto downloader = new (std::nothrow) cocos2d::network::Downloader(); + downloader->onDataTaskSuccess = [=](const cocos2d::network::DownloadTask& task, std::vector& data) + { + bool success = false; + + Image* image = new (std::nothrow) Image(); + if (image->initWithImageData(data.data(), data.size())) + { + if (texture->initWithImage(image)) + { + success = true; + } + else + { + CCLOGERROR("js_cocos2dx_extension_loadRemoteImageOn: Failed to initWithImage."); + } + } + CC_SAFE_RELEASE(image); + + onCallback(success); + Director::getInstance()->getScheduler()->performFunctionInCocosThread([downloader](){ + delete downloader; + }); + }; + + downloader->onTaskError = [=](const cocos2d::network::DownloadTask& task, int errorCode, int errorCodeInternal, const std::string& errorStr) + { + onCallback(false); + Director::getInstance()->getScheduler()->performFunctionInCocosThread([downloader](){ + delete downloader; + }); + }; + + downloader->createDownloadDataTask(url); + return true; +} +SE_BIND_FUNC(js_cocos2dx_extension_initRemoteImage) + bool register_all_cocos2dx_extension_manual(se::Object* obj) { @@ -141,6 +218,7 @@ bool register_all_cocos2dx_extension_manual(se::Object* obj) e->defineFunction("release", _SE(jsb_cocos2d_extension_empty_func)); } __jsbObj->defineFunction("loadRemoteImg", _SE(js_cocos2dx_extension_loadRemoteImage)); + __jsbObj->defineFunction("initRemoteImg", _SE(js_cocos2dx_extension_initRemoteImage)); se::ScriptEngine::getInstance()->clearException(); From 1ea2fc171592159de7cf26bb6395df1701588f0c Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 25 Sep 2017 14:30:01 +0800 Subject: [PATCH 2/6] revert TextureCache, use ThreadPool instead --- .../cocos2d_libs.xcodeproj/project.pbxproj | 8 ++ native/cocos/Android.mk | 1 + native/cocos/audio/android/Android.mk | 1 - .../audio/android/AudioPlayerProvider.cpp | 2 +- .../{audio/android => base}/CCThreadPool.cpp | 2 +- .../{audio/android => base}/CCThreadPool.h | 0 native/cocos/renderer/CCTextureCache.cpp | 126 +++++------------- native/cocos/renderer/CCTextureCache.h | 12 +- .../auto/api/jsb_cocos2dx_auto_api.js | 18 +-- .../js-bindings/auto/jsb_cocos2dx_auto.cpp | 67 +--------- .../js-bindings/auto/jsb_cocos2dx_auto.hpp | 3 +- .../manual/jsb_cocos2dx_extension_manual.cpp | 109 ++++++++++++++- native/templates/cocos2dx_files.json | 10 +- 13 files changed, 169 insertions(+), 190 deletions(-) rename native/cocos/{audio/android => base}/CCThreadPool.cpp (99%) rename native/cocos/{audio/android => base}/CCThreadPool.h (100%) diff --git a/native/build/cocos2d_libs.xcodeproj/project.pbxproj b/native/build/cocos2d_libs.xcodeproj/project.pbxproj index 3d43724020..38fa727920 100644 --- a/native/build/cocos2d_libs.xcodeproj/project.pbxproj +++ b/native/build/cocos2d_libs.xcodeproj/project.pbxproj @@ -1155,6 +1155,8 @@ 826294331AAF001C00CB7CF7 /* HttpAsynConnection-apple.m in Sources */ = {isa = PBXBuildFile; fileRef = 52B47A2A1A5349A3004E4C60 /* HttpAsynConnection-apple.m */; }; 826294341AAF003E00CB7CF7 /* HttpClient-apple.mm in Sources */ = {isa = PBXBuildFile; fileRef = 52B47A2B1A5349A3004E4C60 /* HttpClient-apple.mm */; }; 826294351AAF004C00CB7CF7 /* HttpCookie.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 52B47A2C1A5349A3004E4C60 /* HttpCookie.cpp */; }; + 844EB11F1F78D4CB00EFE4CD /* CCThreadPool.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 844EB11D1F78D4CA00EFE4CD /* CCThreadPool.cpp */; }; + 844EB1201F78D4CB00EFE4CD /* CCThreadPool.h in Headers */ = {isa = PBXBuildFile; fileRef = 844EB11E1F78D4CA00EFE4CD /* CCThreadPool.h */; }; A0534A651B872FFD006B03E5 /* CCDownloader-apple.h in Headers */ = {isa = PBXBuildFile; fileRef = A0534A631B872FFD006B03E5 /* CCDownloader-apple.h */; }; A0534A661B872FFD006B03E5 /* CCDownloader-apple.h in Headers */ = {isa = PBXBuildFile; fileRef = A0534A631B872FFD006B03E5 /* CCDownloader-apple.h */; }; A0534A671B872FFD006B03E5 /* CCDownloader-apple.mm in Sources */ = {isa = PBXBuildFile; fileRef = A0534A641B872FFD006B03E5 /* CCDownloader-apple.mm */; }; @@ -2229,6 +2231,8 @@ 52B47A2B1A5349A3004E4C60 /* HttpClient-apple.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "HttpClient-apple.mm"; sourceTree = ""; }; 52B47A2C1A5349A3004E4C60 /* HttpCookie.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HttpCookie.cpp; sourceTree = ""; }; 52B47A2D1A5349A3004E4C60 /* HttpCookie.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HttpCookie.h; sourceTree = ""; }; + 844EB11D1F78D4CA00EFE4CD /* CCThreadPool.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCThreadPool.cpp; path = ../base/CCThreadPool.cpp; sourceTree = ""; }; + 844EB11E1F78D4CA00EFE4CD /* CCThreadPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCThreadPool.h; path = ../base/CCThreadPool.h; sourceTree = ""; }; A0534A631B872FFD006B03E5 /* CCDownloader-apple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCDownloader-apple.h"; sourceTree = ""; }; A0534A641B872FFD006B03E5 /* CCDownloader-apple.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCDownloader-apple.mm"; sourceTree = ""; }; A0534A691B87306E006B03E5 /* CCIDownloaderImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCIDownloaderImpl.h; sourceTree = ""; }; @@ -2734,6 +2738,8 @@ 1A5700A2180BC5E60088DEC7 /* base */ = { isa = PBXGroup; children = ( + 844EB11D1F78D4CA00EFE4CD /* CCThreadPool.cpp */, + 844EB11E1F78D4CA00EFE4CD /* CCThreadPool.h */, A6F0D79F1C2796020029CC44 /* CCStencilStateManager.cpp */, A6F0D7A01C2796020029CC44 /* CCStencilStateManager.hpp */, 291901411B05895600F8B4BA /* CCNinePatchImageParser.h */, @@ -4529,6 +4535,7 @@ 50ABBEBD1925AB6F00A911A9 /* ccUtils.h in Headers */, 4DED486E1DFFA4AF0070C5C4 /* b2MouseJoint.h in Headers */, A0534A651B872FFD006B03E5 /* CCDownloader-apple.h in Headers */, + 844EB1201F78D4CB00EFE4CD /* CCThreadPool.h in Headers */, BA679B361CEC373000F875FA /* CCEventAssetsManagerEx.h in Headers */, 50ABC0231926664800A911A9 /* CCGLViewImpl-desktop.h in Headers */, A63CF0081CD9CF3500A6971D /* CCUIPasswordTextField.h in Headers */, @@ -5164,6 +5171,7 @@ 1A570081180BC5A10088DEC7 /* CCActionManager.cpp in Sources */, 1A570085180BC5A10088DEC7 /* CCActionPageTurn3D.cpp in Sources */, FAC8F66A1E1DF15D002B17E8 /* SkeletonBinary.c in Sources */, + 844EB11F1F78D4CB00EFE4CD /* CCThreadPool.cpp in Sources */, 1A570089180BC5A10088DEC7 /* CCActionProgressTimer.cpp in Sources */, 1A57008D180BC5A10088DEC7 /* CCActionTiledGrid.cpp in Sources */, 1A570091180BC5A10088DEC7 /* CCActionTween.cpp in Sources */, diff --git a/native/cocos/Android.mk b/native/cocos/Android.mk index 949a7e218c..f0a2e137c2 100644 --- a/native/cocos/Android.mk +++ b/native/cocos/Android.mk @@ -126,6 +126,7 @@ base/CCProfiling.cpp \ base/CCRef.cpp \ base/CCScheduler.cpp \ base/CCScriptSupport.cpp \ +base/CCThreadPool.cpp \ base/CCTouch.cpp \ base/CCUserDefault-android.cpp \ base/CCUserDefault.cpp \ diff --git a/native/cocos/audio/android/Android.mk b/native/cocos/audio/android/Android.mk index b3db2cc6df..8d07da968c 100644 --- a/native/cocos/audio/android/Android.mk +++ b/native/cocos/audio/android/Android.mk @@ -9,7 +9,6 @@ LOCAL_MODULE_FILENAME := libaudioengine LOCAL_SRC_FILES := AudioEngine-inl.cpp \ ../AudioEngine.cpp \ - CCThreadPool.cpp \ AssetFd.cpp \ AudioDecoder.cpp \ AudioDecoderProvider.cpp \ diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 0027cdf2af..9c0d9652be 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -24,6 +24,7 @@ THE SOFTWARE. #define LOG_TAG "AudioPlayerProvider" +#include "base/CCThreadPool.h" #include "audio/android/AudioPlayerProvider.h" #include "audio/android/UrlAudioPlayer.h" #include "audio/android/PcmAudioPlayer.h" @@ -31,7 +32,6 @@ THE SOFTWARE. #include "audio/android/AudioDecoderProvider.h" #include "audio/android/AudioMixerController.h" #include "audio/android/PcmAudioService.h" -#include "audio/android/CCThreadPool.h" #include "audio/android/ICallerThreadUtils.h" #include "audio/android/utils/Utils.h" diff --git a/native/cocos/audio/android/CCThreadPool.cpp b/native/cocos/base/CCThreadPool.cpp similarity index 99% rename from native/cocos/audio/android/CCThreadPool.cpp rename to native/cocos/base/CCThreadPool.cpp index 6f5cbe6895..4c7974cd60 100644 --- a/native/cocos/audio/android/CCThreadPool.cpp +++ b/native/cocos/base/CCThreadPool.cpp @@ -25,7 +25,7 @@ ****************************************************************************/ -#include "audio/android/CCThreadPool.h" +#include "base/CCThreadPool.h" #include diff --git a/native/cocos/audio/android/CCThreadPool.h b/native/cocos/base/CCThreadPool.h similarity index 100% rename from native/cocos/audio/android/CCThreadPool.h rename to native/cocos/base/CCThreadPool.h diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index a90b1d137b..30ef33b4fe 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -83,43 +83,16 @@ std::string TextureCache::getDescription() const struct TextureCache::AsyncStruct { public: - AsyncStruct(const std::string& fn, std::function f) : filename(fn), callback(f), pixelFormat(Texture2D::getDefaultAlphaPixelFormat()), texture(nullptr), loadSuccess(false) {} + AsyncStruct(const std::string& fn, std::function f) : filename(fn), callback(f), pixelFormat(Texture2D::getDefaultAlphaPixelFormat()), loadSuccess(false) {} std::string filename; std::function callback; Image image; Image imageAlpha; Texture2D::PixelFormat pixelFormat; - Texture2D* texture; // optional, existing texture to init bool loadSuccess; }; -void TextureCache::enqueueAsyncStruct(AsyncStruct* data) -{ - // lazy init - if (_loadingThread == nullptr) - { - // create a new thread to load images - _loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this); - _needQuit = false; - } - - if (0 == _asyncRefCount) - { - Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false); - } - - ++_asyncRefCount; - - // add async struct into queue - _asyncStructQueue.push_back(data); - _requestMutex.lock(); - _requestQueue.push_back(data); - _requestMutex.unlock(); - - _sleepCondition.notify_one(); -} - /** The addImageAsync logic follow the steps: - find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread) @@ -168,30 +141,31 @@ void TextureCache::addImageAsync(const std::string &path, const std::function& callback) -{ - CCASSERT(texture != nullptr, "TextureCache: texture MUST not be nil"); - - std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path); - - // check if file exists - if ( fullpath.empty() || ! FileUtils::getInstance()->isFileExist( fullpath ) ) + // lazy init + if (_loadingThread == nullptr) { - if (callback) callback(nullptr); - return; + // create a new thread to load images + _loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this); + _needQuit = false; } + if (0 == _asyncRefCount) + { + Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false); + } + + ++_asyncRefCount; + // generate async struct AsyncStruct *data = new (std::nothrow) AsyncStruct(fullpath, callback); - data->texture = texture; - enqueueAsyncStruct(data); + // add async struct into queue + _asyncStructQueue.push_back(data); + _requestMutex.lock(); + _requestQueue.push_back(data); + _requestMutex.unlock(); + + _sleepCondition.notify_one(); } void TextureCache::unbindImageAsync(const std::string& filename) @@ -285,14 +259,21 @@ void TextureCache::addImageAsyncCallBack(float dt) break; } - // check the texture has been provided or not - if (asyncStruct->texture != nullptr) + // check the image has been convert to texture or not + auto it = _textures.find(asyncStruct->filename); + if(it != _textures.end()) + { + texture = it->second; + } + else { // convert image to texture if (asyncStruct->loadSuccess) { - texture = asyncStruct->texture; Image* image = &(asyncStruct->image); + // generate texture in render thread + texture = new (std::nothrow) Texture2D(); + texture->initWithImage(image, asyncStruct->pixelFormat); //parse 9-patch info this->parseNinePatchImage(image, texture, asyncStruct->filename); @@ -300,49 +281,16 @@ void TextureCache::addImageAsyncCallBack(float dt) // cache the texture file name VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename); #endif - } - else - { + // cache the texture. retain it, since it is added in the map + _textures.insert( std::make_pair(asyncStruct->filename, texture) ); + texture->retain(); + + texture->autorelease(); + } else { + texture = nullptr; CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); } } - else - { - // check the image has been convert to texture or not - auto it = _textures.find(asyncStruct->filename); - if(it != _textures.end()) - { - texture = it->second; - } - else - { - // convert image to texture - if (asyncStruct->loadSuccess) - { - Image* image = &(asyncStruct->image); - // generate texture in render thread - texture = new (std::nothrow) Texture2D(); - - texture->initWithImage(image, asyncStruct->pixelFormat); - //parse 9-patch info - this->parseNinePatchImage(image, texture, asyncStruct->filename); - #if CC_ENABLE_CACHE_TEXTURE_DATA - // cache the texture file name - VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename); - #endif - // cache the texture. retain it, since it is added in the map - _textures.insert( std::make_pair(asyncStruct->filename, texture) ); - texture->retain(); - - texture->autorelease(); - } - else - { - texture = nullptr; - CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); - } - } - } // call callback function if (asyncStruct->callback) diff --git a/native/cocos/renderer/CCTextureCache.h b/native/cocos/renderer/CCTextureCache.h index 51d2e77e76..52fdebd64b 100644 --- a/native/cocos/renderer/CCTextureCache.h +++ b/native/cocos/renderer/CCTextureCache.h @@ -115,14 +115,6 @@ public: */ virtual void addImageAsync(const std::string &filepath, const std::function& callback); - /** Init a given Texture2D object with a file image. - * It is much the same as addImageAsync, except an existing texture is provided. - @param texture An existing texture. - @param filepath A null terminated string. - @param callback A callback function would be invoked after the image is loaded. - */ - virtual void initImageAsync(Texture2D* texture, const std::string& filepath, const std::function& callback); - /** Unbind a specified bound image asynchronous callback. * In the case an object who was bound to an image asynchronous callback was destroyed before the callback is invoked, * the object always need to unbind this callback manually. @@ -222,13 +214,13 @@ public: private: - struct AsyncStruct; - void enqueueAsyncStruct(AsyncStruct* data); void addImageAsyncCallBack(float dt); void loadImage(); void parseNinePatchImage(Image* image, Texture2D* texture, const std::string& path); public: protected: + struct AsyncStruct; + std::thread* _loadingThread; std::deque _asyncStructQueue; diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index 6a79b01176..2f02fd6492 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -14377,14 +14377,6 @@ texture2d return ; }, -/** - * @method waitForQuit - */ -waitForQuit : function ( -) -{ -}, - /** * @method renameTextureWithKey * @param {String} arg0 @@ -14416,15 +14408,9 @@ texture2d }, /** - * @method initImageAsync - * @param {cc.Texture2D} arg0 - * @param {String} arg1 - * @param {function} arg2 + * @method waitForQuit */ -initImageAsync : function ( -texture2d, -str, -func +waitForQuit : function ( ) { }, diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index 54a344864f..90db4d72df 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -32540,21 +32540,6 @@ static bool js_cocos2dx_TextureCache_getTextureFilePath(se::State& s) } SE_BIND_FUNC(js_cocos2dx_TextureCache_getTextureFilePath) -static bool js_cocos2dx_TextureCache_waitForQuit(se::State& s) -{ - cocos2d::TextureCache* cobj = (cocos2d::TextureCache*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_TextureCache_waitForQuit : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->waitForQuit(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_cocos2dx_TextureCache_waitForQuit) - static bool js_cocos2dx_TextureCache_renameTextureWithKey(se::State& s) { cocos2d::TextureCache* cobj = (cocos2d::TextureCache*)s.nativeThisObject(); @@ -32610,57 +32595,20 @@ static bool js_cocos2dx_TextureCache_removeTexture(se::State& s) } SE_BIND_FUNC(js_cocos2dx_TextureCache_removeTexture) -static bool js_cocos2dx_TextureCache_initImageAsync(se::State& s) +static bool js_cocos2dx_TextureCache_waitForQuit(se::State& s) { cocos2d::TextureCache* cobj = (cocos2d::TextureCache*)s.nativeThisObject(); - SE_PRECONDITION2(cobj, false, "js_cocos2dx_TextureCache_initImageAsync : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_cocos2dx_TextureCache_waitForQuit : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 3) { - cocos2d::Texture2D* arg0 = nullptr; - std::string arg1; - std::function arg2; - ok &= seval_to_native_ptr(args[0], &arg0); - ok &= seval_to_std_string(args[1], &arg1); - do { - if (args[2].isObject() && args[2].toObject()->isFunction()) - { - se::Value jsThis(s.thisObject()); - se::Value jsFunc(args[2]); - jsFunc.toObject()->root(); - auto lambda = [=](cocos2d::Texture2D* larg0) -> void { - se::ScriptEngine::getInstance()->clearException(); - se::AutoHandleScope hs; - - CC_UNUSED bool ok = true; - se::ValueArray args; - args.resize(1); - ok &= native_ptr_to_seval((cocos2d::Texture2D*)larg0, &args[0]); - se::Value rval; - se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; - se::Object* funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); - if (!succeed) { - se::ScriptEngine::getInstance()->clearException(); - } - }; - arg2 = lambda; - } - else - { - arg2 = nullptr; - } - } while(false) - ; - SE_PRECONDITION2(ok, false, "js_cocos2dx_TextureCache_initImageAsync : Error processing arguments"); - cobj->initImageAsync(arg0, arg1, arg2); + if (argc == 0) { + cobj->waitForQuit(); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_cocos2dx_TextureCache_initImageAsync) +SE_BIND_FUNC(js_cocos2dx_TextureCache_waitForQuit) SE_DECLARE_FINALIZE_FUNC(js_cocos2d_TextureCache_finalize) @@ -32703,11 +32651,10 @@ bool js_register_cocos2dx_TextureCache(se::Object* obj) cls->defineFunction("unbindImageAsync", _SE(js_cocos2dx_TextureCache_unbindImageAsync)); cls->defineFunction("getTextureForKey", _SE(js_cocos2dx_TextureCache_getTextureForKey)); cls->defineFunction("getTextureFilePath", _SE(js_cocos2dx_TextureCache_getTextureFilePath)); - cls->defineFunction("waitForQuit", _SE(js_cocos2dx_TextureCache_waitForQuit)); cls->defineFunction("renameTextureWithKey", _SE(js_cocos2dx_TextureCache_renameTextureWithKey)); cls->defineFunction("removeUnusedTextures", _SE(js_cocos2dx_TextureCache_removeUnusedTextures)); cls->defineFunction("removeTexture", _SE(js_cocos2dx_TextureCache_removeTexture)); - cls->defineFunction("initImageAsync", _SE(js_cocos2dx_TextureCache_initImageAsync)); + cls->defineFunction("waitForQuit", _SE(js_cocos2dx_TextureCache_waitForQuit)); cls->defineFinalizeFunction(_SE(js_cocos2d_TextureCache_finalize)); cls->install(); JSBClassType::registerClass(cls); diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp index 0bdf9b769d..3edc087a2d 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -2148,11 +2148,10 @@ SE_DECLARE_FUNC(js_cocos2dx_TextureCache_addImage); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_unbindImageAsync); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_getTextureForKey); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_getTextureFilePath); -SE_DECLARE_FUNC(js_cocos2dx_TextureCache_waitForQuit); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_renameTextureWithKey); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_removeUnusedTextures); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_removeTexture); -SE_DECLARE_FUNC(js_cocos2dx_TextureCache_initImageAsync); +SE_DECLARE_FUNC(js_cocos2dx_TextureCache_waitForQuit); SE_DECLARE_FUNC(js_cocos2dx_TextureCache_TextureCache); extern se::Object* __jsb_cocos2d_Device_proto; diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp index bc5af35a76..864ee0a100 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp @@ -11,12 +11,14 @@ #include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp" #include "cocos/scripting/js-bindings/manual/jsb_global.h" #include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.hpp" +#include "cocos/base/CCThreadPool.h" #include "cocos2d.h" #include "extensions/cocos-ext.h" using namespace cocos2d; using namespace cocos2d::extension; +using namespace cocos2d::experimental; static bool jsb_cocos2d_extension_empty_func(se::State& s) { @@ -151,7 +153,6 @@ static bool js_cocos2dx_extension_initRemoteImage(se::State& s) // get callback se::Value func = args[2]; assert(func.isObject() && func.toObject()->isFunction()); - func.toObject()->root(); auto onCallback = [=](bool success){ @@ -170,10 +171,10 @@ static bool js_cocos2dx_extension_initRemoteImage(se::State& s) { bool success = false; - Image* image = new (std::nothrow) Image(); - if (image->initWithImageData(data.data(), data.size())) + Image image; + if (image.initWithImageData(data.data(), data.size())) { - if (texture->initWithImage(image)) + if (texture->initWithImage(&image)) { success = true; } @@ -182,7 +183,6 @@ static bool js_cocos2dx_extension_initRemoteImage(se::State& s) CCLOGERROR("js_cocos2dx_extension_loadRemoteImageOn: Failed to initWithImage."); } } - CC_SAFE_RELEASE(image); onCallback(success); Director::getInstance()->getScheduler()->performFunctionInCocosThread([downloader](){ @@ -203,6 +203,104 @@ static bool js_cocos2dx_extension_initRemoteImage(se::State& s) } SE_BIND_FUNC(js_cocos2dx_extension_initRemoteImage) +static ThreadPool* _threadPool = nullptr; +static EventListenerCustom* _resetThreadPoolListener = nullptr; +static ThreadPool* getThreadPool() +{ + if (_threadPool == nullptr) + { + _threadPool = ThreadPool::newSingleThreadPool(); + _resetThreadPoolListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_RESET, [](cocos2d::EventCustom*){ + CC_SAFE_DELETE(_threadPool); + cocos2d::Director::getInstance()->getEventDispatcher()->removeEventListener(_resetThreadPoolListener); + _resetThreadPoolListener = nullptr; + }); + } + return _threadPool; +} + +static bool js_cocos2dx_extension_initTextureAsync(se::State& s) +{ + const auto& args = s.args(); + int argc = (int)args.size(); + if (argc != 3) + { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 3); + return false; + } + + bool ok = false; + + // get texture + cocos2d::Texture2D* texture = nullptr; + ok = seval_to_native_ptr(args[0], &texture); + SE_PRECONDITION2(ok, false, "Converting 'texture' failed!"); + + // get url + std::string url; + ok = seval_to_std_string(args[1], &url); + SE_PRECONDITION2(ok, false, "Converting 'url' failed!"); + + // get callback + se::Value func = args[2]; + assert(func.isObject() && func.toObject()->isFunction()); + func.toObject()->root(); + + auto onCallback = [=](bool success){ + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + se::ValueArray args; + args.resize(1); + + args[0].setBoolean(success); + func.toObject()->call(args, nullptr); + }; + + getThreadPool()->pushTask([=](int tid){ + bool success = false; + + Data data = FileUtils::getInstance()->getDataFromFile(url); + if (data.isNull() == false) + { + Image* image = new (std::nothrow) Image(); + if (image->initWithImageData(data.getBytes(), data.getSize())) + { + Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]() mutable { + if (texture->initWithImage(image)) + { + // Director::getInstance()->getTextureCache()->parseNinePatchImage(image, texture, url); + onCallback(true); + } + else + { + CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to init texture with image."); + onCallback(false); + } + CC_SAFE_DELETE(image); + }); + return; + } + else + { + CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to load image."); + CC_SAFE_DELETE(image); + } + } + else + { + CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to load file."); + } + + Director::getInstance()->getScheduler()->performFunctionInCocosThread([=](){ + onCallback(false); + }); + }); + + return true; +} +SE_BIND_FUNC(js_cocos2dx_extension_initTextureAsync) + bool register_all_cocos2dx_extension_manual(se::Object* obj) { @@ -219,6 +317,7 @@ bool register_all_cocos2dx_extension_manual(se::Object* obj) } __jsbObj->defineFunction("loadRemoteImg", _SE(js_cocos2dx_extension_loadRemoteImage)); __jsbObj->defineFunction("initRemoteImg", _SE(js_cocos2dx_extension_initRemoteImage)); + __jsbObj->defineFunction("initTextureAsync", _SE(js_cocos2dx_extension_initTextureAsync)); se::ScriptEngine::getInstance()->clearException(); diff --git a/native/templates/cocos2dx_files.json b/native/templates/cocos2dx_files.json index 797d22aa7e..501fdf0f97 100644 --- a/native/templates/cocos2dx_files.json +++ b/native/templates/cocos2dx_files.json @@ -176,9 +176,7 @@ "cocos/audio/android/AudioResamplerCubic.cpp", "cocos/audio/android/AudioResamplerCubic.h", "cocos/audio/android/AudioResamplerPublic.h", - "cocos/audio/android/CCThreadPool.cpp", - "cocos/audio/android/CCThreadPool.h", - "cocos/audio/android/IAudioPlayer.h", + "cocos/audio/android/IAudioPlayer.h", "cocos/audio/android/ICallerThreadUtils.h", "cocos/audio/android/IVolumeProvider.h", "cocos/audio/android/OpenSLHelper.h", @@ -305,8 +303,10 @@ "cocos/base/CCScriptSupport.cpp", "cocos/base/CCScriptSupport.h", "cocos/base/CCStencilStateManager.cpp", - "cocos/base/CCStencilStateManager.hpp", - "cocos/base/CCTouch.cpp", + "cocos/base/CCStencilStateManager.hpp", + "cocos/base/CCThreadPool.cpp", + "cocos/base/CCThreadPool.h", + "cocos/base/CCTouch.cpp", "cocos/base/CCTouch.h", "cocos/base/CCUserDefault-android.cpp", "cocos/base/CCUserDefault-apple.mm", From c001b9db630f15d6e71e663f63eb5f065895745c Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 26 Sep 2017 11:30:15 +0800 Subject: [PATCH 3/6] sync develop branch --- .../manual/jsb_cocos2dx_extension_manual.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp index 7387d05db0..f44edc65c1 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp @@ -177,10 +177,10 @@ static bool js_cocos2dx_extension_initRemoteImage(se::State& s) { bool success = false; - Image image; - if (image.initWithImageData(data.data(), data.size())) + Image* image = new (std::nothrow) Image(); + if (image->initWithImageData(data.data(), data.size())) { - if (texture->initWithImage(&image)) + if (texture->initWithImage(image)) { success = true; } @@ -189,6 +189,7 @@ static bool js_cocos2dx_extension_initRemoteImage(se::State& s) CCLOGERROR("js_cocos2dx_extension_loadRemoteImageOn: Failed to initWithImage."); } } + CC_SAFE_RELEASE_NULL(image); onCallback(success); Director::getInstance()->getScheduler()->performFunctionInCocosThread([downloader](){ @@ -283,14 +284,14 @@ static bool js_cocos2dx_extension_initTextureAsync(se::State& s) CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to init texture with image."); onCallback(false); } - CC_SAFE_DELETE(image); + CC_SAFE_RELEASE_NULL(image); }); return; } else { CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to load image."); - CC_SAFE_DELETE(image); + CC_SAFE_RELEASE_NULL(image); } } else From 7ffb0d40db75f568419afd0b2dd500a7402149f5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 26 Sep 2017 14:24:04 +0800 Subject: [PATCH 4/6] avoid multi-thread issue --- .../manual/jsb_cocos2dx_extension_manual.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp index f44edc65c1..c83cc26eab 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp @@ -264,11 +264,13 @@ static bool js_cocos2dx_extension_initTextureAsync(se::State& s) func.toObject()->call(args, nullptr); }; - getThreadPool()->pushTask([=](int tid){ - bool success = false; + // getDataFromFile isn't thread safe since fullPathForFilename usage in getDataFromFile isn't. + // So we should pass full path to getDataFromFile to avoid multi-thread issues. + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(url); - Data data = FileUtils::getInstance()->getDataFromFile(url); - if (data.isNull() == false) + getThreadPool()->pushTask([texture, onCallback, fullPath](int tid){ + Data data = FileUtils::getInstance()->getDataFromFile(fullPath); + if (!data.isNull()) { Image* image = new (std::nothrow) Image(); if (image->initWithImageData(data.getBytes(), data.getSize())) From 5c5a0a257ad019f02cd640d2de404cf4e00336ef Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Sep 2017 14:30:53 +0800 Subject: [PATCH 5/6] Adds CCThreadPool.cpp/.h to vs project. --- native/cocos/2d/libcocos2d.vcxproj | 2 ++ native/cocos/2d/libcocos2d.vcxproj.filters | 11 ++++++----- native/cocos/base/CCThreadPool.cpp | 5 ++--- native/cocos/base/CCThreadPool.h | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/native/cocos/2d/libcocos2d.vcxproj b/native/cocos/2d/libcocos2d.vcxproj index 156e7c2f61..9bfda52fc5 100644 --- a/native/cocos/2d/libcocos2d.vcxproj +++ b/native/cocos/2d/libcocos2d.vcxproj @@ -233,6 +233,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)" + @@ -481,6 +482,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)" + diff --git a/native/cocos/2d/libcocos2d.vcxproj.filters b/native/cocos/2d/libcocos2d.vcxproj.filters index afad616311..80d22e9074 100644 --- a/native/cocos/2d/libcocos2d.vcxproj.filters +++ b/native/cocos/2d/libcocos2d.vcxproj.filters @@ -689,9 +689,6 @@ base - - ui\UIWidgets\ScrollWidget - creator @@ -786,6 +783,9 @@ network\Source Files + + base + @@ -1480,8 +1480,6 @@ - - creator @@ -1545,6 +1543,9 @@ ui\UIWidgets\EditBox + + base + diff --git a/native/cocos/base/CCThreadPool.cpp b/native/cocos/base/CCThreadPool.cpp index 4c7974cd60..d51ed50c82 100644 --- a/native/cocos/base/CCThreadPool.cpp +++ b/native/cocos/base/CCThreadPool.cpp @@ -26,7 +26,6 @@ ****************************************************************************/ #include "base/CCThreadPool.h" -#include #ifdef __ANDROID__ @@ -165,7 +164,7 @@ bool ThreadPool::tryShrinkPool() for (int i = 0; i < _maxThreadNum; ++i) { - if (threadIDsToJoin.size() >= maxThreadNumToJoin) + if ((int)threadIDsToJoin.size() >= maxThreadNumToJoin) { break; } @@ -330,7 +329,7 @@ void ThreadPool::stopTasksByType(TaskType type) void ThreadPool::joinThread(int tid) { - if (tid < 0 || tid >= _threads.size()) + if (tid < 0 || tid >= (int)_threads.size()) { LOGD("Invalid thread id %d\n", tid); return; diff --git a/native/cocos/base/CCThreadPool.h b/native/cocos/base/CCThreadPool.h index 5498bbfd9f..7f19e7b1a3 100644 --- a/native/cocos/base/CCThreadPool.h +++ b/native/cocos/base/CCThreadPool.h @@ -26,7 +26,7 @@ ****************************************************************************/ #pragma once -//#include "platform/CCPlatformMacros.h" +#include "platform/CCStdC.h" #include #include @@ -44,7 +44,7 @@ namespace cocos2d { namespace experimental { * @{ */ -class ThreadPool +class CC_DLL ThreadPool { public: From 2cca661439169264e9f6f18c874932c269b553b2 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 26 Sep 2017 14:57:46 +0800 Subject: [PATCH 6/6] tweaks --- .../js-bindings/manual/jsb_cocos2dx_extension_manual.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp index c83cc26eab..21882981e9 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_extension_manual.cpp @@ -275,10 +275,9 @@ static bool js_cocos2dx_extension_initTextureAsync(se::State& s) Image* image = new (std::nothrow) Image(); if (image->initWithImageData(data.getBytes(), data.getSize())) { - Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]() mutable { + Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]() { if (texture->initWithImage(image)) { - // Director::getInstance()->getTextureCache()->parseNinePatchImage(image, texture, url); onCallback(true); } else @@ -286,14 +285,14 @@ static bool js_cocos2dx_extension_initTextureAsync(se::State& s) CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to init texture with image."); onCallback(false); } - CC_SAFE_RELEASE_NULL(image); + CC_SAFE_RELEASE(image); }); return; } else { CCLOGERROR("js_cocos2dx_extension_initTextureAsync: Failed to load image."); - CC_SAFE_RELEASE_NULL(image); + CC_SAFE_RELEASE(image); } } else