日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

CCTextureCache的多线程加载原理和使用

發布時間:2025/3/15 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CCTextureCache的多线程加载原理和使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

做引擎的時候,遇到一個texture的異步加載,這里將具體的原理和使用方法貼出來,后面根據瀏覽器的特性做修改移植。?

voidCCTextureCache::addImageAsync(constchar *path, CCObject *target, SEL_CallFuncO selector)

{

CCAssert(path != NULL, "TextureCache: fileimage MUST not be NULL");


CCTexture2D *texture = NULL;


// optimization


std::string pathKey = path;

CCFileUtils::ccRemoveHDSuffixFromFile(pathKey);


pathKey = CCFileUtils::fullPathFromRelativePath(pathKey.c_str());

texture = m_pTextures->objectForKey(pathKey); ? ? //根據pathkey查看是否紋理已經加載過,如果已經有了,則不重復加載


std::string fullpath = pathKey;

if (texture != NULL)

{

if (target && selector)

{

(target->*selector)(texture);

}

return;

}

? ? ? ?if (target)

{

target->retain();

}


// lazy init

static bool firstRun = true;

if (firstRun)

{ ? ? ?

? ? ? ? s_pAsyncStructQueue = new queue<AsyncStruct*>();

? ? s_pImageQueue = new queue<ImageInfo*>();


pthread_mutex_init(&s_asyncStructQueueMutex, NULL);

sem_init(&s_sem, 0, 0);

pthread_mutex_init(&s_ImageInfoMutex, NULL);

pthread_create(&s_loadingThread, NULL, loadImage, NULL); ?//創建新的線程,用于后臺加載圖片

?

? ? ? ? ? ? ? ? //創建調度隊列,用來根據已加載的圖片進行紋理轉換

CCScheduler::sharedScheduler()->scheduleSelector(schedule_selector(CCTextureCache::addImageAsyncCallBack), this, 0, false);

need_quit = false;

firstRun = false;

}


// generate async struct

AsyncStruct *data = new AsyncStruct();

data->filename = fullpath.c_str();

data->target = target;

data->selector = selector;


// add async struct into queue

pthread_mutex_lock(&s_asyncStructQueueMutex);

s_pAsyncStructQueue->push(data); ? ? ? ? ? //將需要加載的圖片放入隊列中

pthread_mutex_unlock(&s_asyncStructQueueMutex);


sem_post(&s_sem);

}

?從上述代碼分析可以看出其過程:

1.創建線程,用于后臺加載

2. 將對于需要加載的圖片放入隊列中

3. callback函數設定,用于將加載完成的圖片轉為紋理,等待使用其調用是由CCTimer::update調用的。

4. addImageAsyncCallBack函數在處理完紋理轉換,還會調用addImageAsync傳入的SEL_CallFuncO?selector,實現用戶加載圖片紋理之后的具體處理。

使用例子:

CCTextureCache::sharedTextureCache()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack));?

?loadingCallBack函數就是使用異步加載完之后的用戶可以自處理結果,比如初始化一個sprite,用這個紋理貼出來。

關鍵詞:cocos2d-html5,cocos2d-x,游戲引擎

轉載于:https://www.cnblogs.com/SeanLin/archive/2012/03/15/2398190.html

總結

以上是生活随笔為你收集整理的CCTextureCache的多线程加载原理和使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。