Cocos2d-x 3.0多线程异步资源加载

Cocos2d-x2.x版本到上周刚刚才发布的 Cocos2d-x 3.0 Final版,其引擎驱动核心依旧是一个单线程的“死循环”,一旦某一帧遇到了“大活儿”,比如Size很大的纹理资源加载或网络IO或大量计算,画面将 不可避免出现卡顿以及响应迟缓的现象。从古老的Win32 GUI编程那时起,Guru们就告诉我们:别阻塞主线程(UI线程),让Worker线程去做那些“大活儿”吧。
 
手机游戏,即便是休闲类的小游戏,往往也涉及大量纹理资源、音视频资源、文件读写以及网络通信,处理的稍有不甚就会出现画面卡顿,交互不畅的情况。虽然引 擎在某些方面提供了一些支持,但有些时候还是自己祭出Worker线程这个法宝比较灵活,下面就以Cocos2d-x 3.0 Final版游戏初始化为例(针对Android平台),说说如何进行多线程资源加载。
 
我们经常看到一些手机游戏,启动之后首先会显示一个带有公司Logo的闪屏画面(Flash Screen),然后才会进入一个游戏Welcome场景,点击“开始”才正式进入游戏主场景。而这里Flash Screen的展示环节往往在后台还会做另外一件事,那就是加载游戏的图片资源,音乐音效资源以及配置数据读取,这算是一个“障眼法”吧,目的就是提高用 户体验,这样后续场景渲染以及场景切换直接使用已经cache到内存中的数据即可,无需再行加载。
 
一、为游戏添加FlashScene
在游戏App初始化时,我们首先创建FlashScene,让游戏尽快显示FlashScene画面:
 
 
  1. // AppDelegate.cpp 
  2. bool AppDelegate::applicationDidFinishLaunching() { 
  3.     … … 
  4.     FlashScene* scene = FlashScene::create(); 
  5.     pDirector->runWithScene(scene); 
  6.   
  7.     return true
 
在FlashScene init时,我们创建一个Resource Load Thread,我们用一个ResourceLoadIndicator作为渲染线程与Worker线程之间交互的媒介。
 
 
  1. //FlashScene.h 
  2.   
  3. struct ResourceLoadIndicator { 
  4.     pthread_mutex_t mutex; 
  5.     bool load_done; 
  6.     void *context; 
  7. }; 
  8.   
  9. class FlashScene : public Scene 
  10. public
  11.     FlashScene(void); 
  12.     ~FlashScene(void); 
  13.   
  14.     virtual bool init(); 
  15.   
  16.     CREATE_FUNC(FlashScene); 
  17.     bool getResourceLoadIndicator(); 
  18.     void setResourceLoadIndicator(bool flag); 
  19.   
  20. private
  21.      void updateScene(float dt); 
  22.   
  23. private
  24.      ResourceLoadIndicator rli; 
  25. }; 
  26.   
  27. // FlashScene.cpp 
  28. bool FlashScene::init() 
  29.     bool bRet = false
  30.     do { 
  31.         CC_BREAK_IF(!CCScene::init()); 
  32.         Size winSize = Director::getInstance()->getWinSize(); 
  33.   
  34.         //FlashScene自己的资源只能同步加载了 
  35.         Sprite *bg = Sprite::create("FlashSceenBg.png"); 
  36.         CC_BREAK_IF(!bg); 
  37.         bg->setPosition(ccp(winSize.width/2, winSize.height/2)); 
  38.         this->addChild(bg, 0); 
  39.   
  40.         this->schedule(schedule_selector(FlashScene::updateScene) 
  41.                        , 0.01f); 
  42.   
  43.         //start the resource loading thread 
  44.         rli.load_done = false
  45.         rli.context = (void*)this
  46.         pthread_mutex_init(&rli.mutex, NULL); 
  47.         pthread_attr_t attr; 
  48.         pthread_attr_init(&attr); 
  49.         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
  50.         pthread_t thread; 
  51.         pthread_create(&thread, &attr, 
  52.                     resource_load_thread_entry, &rli); 
  53.   
  54.         bRet=true
  55.     } while(0); 
  56.   
  57.     return bRet; 
  58.   
  59. static void* resource_load_thread_entry(void* param) 
  60.     AppDelegate *app = (AppDelegate*)Application::getInstance(); 
  61.     ResourceLoadIndicator *rli = (ResourceLoadIndicator*)param; 
  62.     FlashScene *scene = (FlashScene*)rli->context; 
  63.   
  64.     //load music effect resource 
  65.     … … 
  66.   
  67.     //init from config files 
  68.     … … 
  69.   
  70.     //load images data in worker thread 
  71.     SpriteFrameCache::getInstance()->addSpriteFramesWithFile( 
  72.                                        "All-Sprites.plist"); 
  73.     … … 
  74.   
  75.     //set loading done 
  76.     scene->setResourceLoadIndicator(true); 
  77.     return NULL; 
  78.   
  79. bool FlashScene::getResourceLoadIndicator() 
  80.     bool flag; 
  81.     pthread_mutex_lock(&rli.mutex); 
  82.     flag = rli.load_done; 
  83.     pthread_mutex_unlock(&rli.mutex); 
  84.     return flag; 
  85.   
  86. void FlashScene::setResourceLoadIndicator(bool flag) 
  87.     pthread_mutex_lock(&rli.mutex); 
  88.     rli.load_done = flag; 
  89.     pthread_mutex_unlock(&rli.mutex); 
  90.     return
 
我们在定时器回调函数中对indicator标志位进行检查,当发现加载ok后,切换到接下来的游戏开始场景: 
 
 
  1. void FlashScene::updateScene(float dt) 
  2.     if (getResourceLoadIndicator()) { 
  3.         Director::getInstance()->replaceScene( 
  4.                               WelcomeScene::create()); 
  5.     } 
 
到此,FlashScene的初始设计和实现完成了。Run一下试试吧。
 
二、崩溃
GenyMotion的4.4.2模拟器上,游戏运行的结果并没有如我期望,FlashScreen显现后游戏就异常崩溃退出了。
 
通过monitor分析游戏的运行日志,我们看到了如下一些异常日志: 
 
 
  1. threadid=24: thread exiting, not yet detached (count=0) 
  2. threadid=24: thread exiting, not yet detached (count=1) 
  3. threadid=24: native thread exited without detaching 
 
很是奇怪啊,我们在创建线程时,明明设置了 PTHREAD_CREATE_DETACHED属性了啊:
 
 
  1. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
 
怎么还会出现这个问题,而且居然有三条日志。翻看了一下引擎内核的代码TextureCache::addImageAsync,在线程创建以及线程主函数中也没有发现什么特别的设置。为何内核可以创建线程,我自己创建就会崩溃呢。Debug多个来回,问题似乎聚焦在resource_load_thread_entry中执行的任务。在我的代码里,我利用SimpleAudioEngine加载了音效资源、利用UserDefault读取了一些持久化的数据,把这两个任务去掉,游戏就会进入到下一个环节而不会崩溃。
 
SimpleAudioEngine和UserDefault能有什么共同点呢?Jni调用。没错,这两个接口底层要适配多个平台,而对于Android 平台,他们都用到了Jni提供的接口去调用Java中的方法。而Jni对多线程是有约束的。 Android开发者官网上有这么一段话: 
 All threads are Linux threads, scheduled by the kernel. They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then attached to the JavaVM. For example, a thread started with pthread_create can be attached with the JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv, and cannot make JNI calls.
 
由此看来pthread_create创建的新线程默认情况下是不能进行Jni接口调用的,除非Attach到Vm,获得一个JniEnv对象,并且在线 程exit前要Detach Vm。好,我们来尝试一下,Cocos2d-x引擎提供了一些JniHelper方法,可以方便进行Jni相关操作。
 
 
  1. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) 
  2. #include "platform/android/jni/JniHelper.h" 
  3. #include <jni.h> 
  4. #endif 
  5.   
  6. static void* resource_load_thread_entry(void* param) 
  7.     … … 
  8.   
  9.     JavaVM *vm; 
  10.     JNIEnv *env; 
  11.     vm = JniHelper::getJavaVM(); 
  12.   
  13.     JavaVMAttachArgs thread_args; 
  14.   
  15.     thread_args.name = "Resource Load"
  16.     thread_args.version = JNI_VERSION_1_4; 
  17.     thread_args.group = NULL; 
  18.   
  19.     vm->AttachCurrentThread(&env, &thread_args); 
  20.     … … 
  21.     //Your Jni Calls 
  22.     … … 
  23.   
  24.     vm->DetachCurrentThread(); 
  25.     … … 
  26.     return NULL; 
 
关于什么是JavaVM,什么是JniEnv,Android Developer官方文档中是这样描述的:
 The JavaVM provides the "invocation interface" functions, which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, but Android only allows one.
The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as the first argument.
The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads.
 
三、黑屏
上面的代码成功解决了线程崩溃的问题,但问题还没完,因为接下来我们又遇到了“黑屏”事件。所谓的“黑屏”,其实并不是全黑。但进入游戏 WelcomScene时,只有Scene中的LabelTTF实例能显示出来,其余Sprite都无法显示。显然肯定与我们在Worker线程加载纹理 资源有关了: 
 
 
  1. SpriteFrameCache::getInstance()->addSpriteFramesWithFile("All-Sprites.plist"); 
 
我们通过碎图压缩到一张大纹理的方式建立SpriteFrame,这是Cocos2d-x推荐的优化手段。但要想找到这个问题的根源,还得看monitor日志。我们的确发现了一些异常日志:
 
 
  1. libEGL: call to OpenGL ES API with no current context (logged once per thread) 
 
通过Google得知,只有Renderer Thread才能进行egl调用,因为egl的context是在Renderer Thread创建的,Worker Thread并没有EGL的context,在进行egl操作时,无法找到context,因此操作都是失败的,纹理也就无法显示出来。要解决这个问题就 得查看一下TextureCache::addImageAsync是如何做的了。
 
TextureCache::addImageAsync只是在worker线程进行了image数据的加载,而纹理对象Texture2D instance则是在addImageAsyncCallBack中创建的。也就是说纹理还是在Renderer线程中创建的,因此不会出现我们上面的 “黑屏”问题。模仿addImageAsync,我们来修改一下代码:
 
 
  1. static void* resource_load_thread_entry(void* param) 
  2.     … … 
  3.     allSpritesImage = new Image(); 
  4.     allSpritesImage->initWithImageFile("All-Sprites.png"); 
  5.     … … 
  6.   
  7. void FlashScene::updateScene(float dt) 
  8.     if (getResourceLoadIndicator()) { 
  9.         // construct texture with preloaded images 
  10.         Texture2D *allSpritesTexture = TextureCache::getInstance()-> 
  11.                            addImage(allSpritesImage, "All-Sprites.png"); 
  12.         allSpritesImage->release(); 
  13.         SpriteFrameCache::getInstance()->addSpriteFramesWithFile( 
  14.                            "All-Sprites.plist", allSpritesTexture); 
  15.       
  16.         Director::getInstance()->replaceScene(WelcomeScene::create()); 
  17.     } 
 
完成这一修改后,游戏画面就变得一切正常了,多线程资源加载机制正式生效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SZ_Eason

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值