首页 > 代码库 > Cocos2d-x3.2 TextureCache类异步加载功能讲解

Cocos2d-x3.2 TextureCache类异步加载功能讲解

本文TextureCache类异步加载功能的代码抽出,总共代码就200多行,感兴趣可以看看。

研究这个主要是因为项目中需要异步插入数据,但之前的方法在Android上总是崩溃所以想到TextureCache有异步加载的功能就将其抽出了。

原文地址:http://blog.csdn.net/qqmcy/article/details/39890837


首先,创建AsyncTaskTime类,主要模拟一个费时的方法

AsyncTaskTime.h

#include "cocos2d.h"

USING_NS_CC;

class AsyncTaskTime
{
public:
    
    //模拟一个费时操作
    bool initWithImageFileThreadSafe(const std::string &filename);
    
    
};

AsyncTaskTime.cpp

//
//  AsyncTaskTime.cpp
//  cpp4
//
//  Created by 杜甲 on 10/8/14.
//
//

#include "AsyncTaskTime.h"

bool AsyncTaskTime::initWithImageFileThreadSafe(const std::string &filename)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    return true;
}

创建异步加载功能类

AsyncTest.h

//
//  AsyncTest.h
//  cpp4
//
//  Created by 杜甲 on 10/8/14.
//
//

#ifndef __cpp4__AsyncTest__
#define __cpp4__AsyncTest__

#include "cocos2d.h"
#include "AsyncTaskTime.h"

using namespace std;

USING_NS_CC;
class AsyncTest : public Ref
{
public:
    CREATE_FUNC(AsyncTest);
    
    virtual bool init();
    
    AsyncTest();
    
    // 异步加载
    void addImageAsync(const string &path , const function<void(AsyncTaskTime *)> &callback);
private:
    
    void addImageAsyncCallback(float dt);
    //加载数据
    void loadImage();
    
public:
    struct AsyncStruct
    {
    public:
        AsyncStruct(const string &fn , function<void(AsyncTaskTime *)> f): filename(fn) , callback(f){};
        
        string filename;
        function<void(AsyncTaskTime *)> callback;
    };
    
protected:
    
    typedef struct
    {
        AsyncStruct *asyncStruct;
        AsyncTaskTime *image;
    }ImageInfo;
    
    
    thread *_loadingThread;
    queue<AsyncStruct *>        *_asyncStructQueue;
    deque<ImageInfo *>          *_ImageInfoQueue;
    
    mutex                       _asyncStructQueueMutex;
    mutex                       _imageInfoMutex;
    
    mutex                       _sleepMutex;
    condition_variable          _sleepCondition;
    
    bool                        _needQuit;
    int                         _asyncRefCount;
    unordered_map<std::string , AsyncTaskTime* > _textures;
    
    
    
    
};

#endif /* defined(__cpp4__AsyncTest__) */

AsyncTest.cpp

//
//  AsyncTest.cpp
//  cpp4
//
//  Created by 杜甲 on 10/8/14.
//
//

#include "AsyncTest.h"

AsyncTest::AsyncTest()
: _loadingThread(nullptr)
, _asyncStructQueue(nullptr)
, _ImageInfoQueue(nullptr)
, _needQuit(false)
, _asyncRefCount(0)
{
    
}

bool AsyncTest::init()
{
    return true;
}

void AsyncTest::addImageAsync(const string &path, const function<void (AsyncTaskTime *)> &callback)
{
    AsyncTaskTime *texture = nullptr;
    
    auto it = _textures.find(path);
    if (it != _textures.end()) {
        texture = it->second;
    }
    
    if (texture != nullptr) {
        callback(texture);
        return;
    }
    
    if (_asyncStructQueue == nullptr) {
        _asyncStructQueue = new queue<AsyncStruct *>();
        _ImageInfoQueue = new deque<ImageInfo *>();
        
        _loadingThread = new thread(&AsyncTest::loadImage , this);
        
        _needQuit = false;
    }
    
    if (0 == _asyncRefCount) {
        Director::getInstance()->getScheduler()->schedule(schedule_selector(AsyncTest::addImageAsyncCallback), this, 0, false);
    }
    
    ++_asyncRefCount;
    
    auto data = http://www.mamicode.com/new AsyncStruct(path , callback);>

调用:

HelloWorldScene.h  

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
#include "AsyncTest.h"
USING_NS_CC;


class HelloWorld : public cocos2d::Layer
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    
    HelloWorld();
    
    virtual bool init();  

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* scene();
    
   
    
    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);
    
    
private:
    Size winSize;
    //这里添加一个回调方法
    void loadCallback1(AsyncTaskTime *time);
    
};

#endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    auto as = AsyncTest::create();
    as->retain();
    as->addImageAsync("test", CC_CALLBACK_1(HelloWorld::loadCallback1, this));
    
    
    
       
    return true;
}

void HelloWorld::loadCallback1(AsyncTaskTime *time)
{
    
    log("加载完成");
    
}


控制台:

cocos2d: 加载完成


这样我们就将TextureCache中

 virtual void addImageAsync(conststd::string &filepath, const std::function<void(Texture2D*)>& callback);

这个异步加载数据的功能实现了。















Cocos2d-x3.2 TextureCache类异步加载功能讲解