From 769628d4144f6610dfb7df8d8db7a93cb8cab08f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 20 Sep 2017 00:08:17 +0800 Subject: [PATCH] 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();