獲取cocos2dx3.3資源文件下的文件名, 異步加載所有資源

異步加載紋理參考:<a target=_blank href="http://cn.cocos2d-x.org/tutorial/show?id=2450">http://cn.cocos2d-x.org/tutorial/show?id=2450</a>

void Loading::loadTextureCache()
{
	//getResName;
	std::vector<std::string>saveFiles;
<span style="white-space:pre">	</span>//獲取路徑
	std::vector<std::string> searchPathArray = FileUtils::getInstance()->getSearchPaths();
	std::string resName = "res";
	std::string imgPath = "general/img";
	std::string findPath;
        //找出 resName 的路徑名
	for (auto it : searchPathArray)
	{
		if (it.find(resName) != std::string::npos)
		{
			findPath = it + imgPath;  // ../res/general/img
			break;
		}
	}
	getFiles(findPath, saveFiles);

	//only support .jpg .png 只支持png和jpg格式
	for (auto itor = saveFiles.begin(); itor != saveFiles.end();)
	{
		auto l = *itor;
		if (l.find(".png") != std::string::npos || l.find(".jpg") != std::string::npos)
		{
			++itor;
		}
		else
		{
			itor = saveFiles.erase(itor);
		}
	}

	//load 異步加載所有<span style="font-family: Arial, Helvetica, sans-serif;">imgPath路徑下的所有紋理</span>
	_numOfTexture = saveFiles.size();
	for (int i = 0; i < _numOfTexture; i++)
	{
		size_t len = saveFiles[i].find(imgPath);
		std::string outPath = saveFiles[i].substr(len);
		//CCLOG("-------------- >  %s", outPath.c_str());
		Director::getInstance()->getTextureCache()->addImageAsync(outPath, CC_CALLBACK_1(Loading::loadTextureCacheCallback, this));
	}
}

//異步回調
void Loading::loadTextureCacheCallback(Texture2D *texture)
{
	CCLOG("%d/%d", ++_loadedOfTexture, _numOfTexture);
	if (_loadedOfTexture == _numOfTexture)
	{
<span style="white-space:pre">		</span>//測試 initAllScenes() 耗時
		int time = clock();
		if (initAllScenes())
		{
			CCLOG("==============initAllScenes===================> useTime = %d", clock() - time);
			
		}
		else
		{
			//do sth
		}
	}
}

//get full path 獲取path文件下的所有文件名
void Loading::getFiles(std::string path, std::vector<std::string>& files)
{
	//file handle  
	long   hFile = 0;
	//file info 
	struct _finddata_t fileinfo;
	std::string p;
	if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			//if is dir ,iteration getFiles(...); 			
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					getFiles(p.assign(path).append("/").append(fileinfo.name), files);
				}
			}
			else
			{
				//if isn't dir, push_back vector.
				files.push_back(p.assign(path).append("/").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章