Merge pull request #3554 from ricardoquesada/fileutils_perf_improvements

Fileutils perf improvements
This commit is contained in:
minggo 2013-09-08 19:50:12 -07:00
commit c5b113c35e
35 changed files with 353 additions and 879 deletions

View File

@ -1 +1 @@
fd0dee451420604712c1327679395cd1faca91b6
0bd142a09d7aacd3dbff8f23c7a14966430e9c01

View File

@ -861,7 +861,7 @@ void Director::createStatsLabel()
CC_SAFE_RELEASE_NULL(_FPSLabel);
CC_SAFE_RELEASE_NULL(_SPFLabel);
CC_SAFE_RELEASE_NULL(_drawsLabel);
textureCache->removeTextureForKey("cc_fps_images");
textureCache->removeTextureForKey("/cc_fps_images");
FileUtils::getInstance()->purgeCachedEntries();
}
@ -878,7 +878,7 @@ void Director::createStatsLabel()
return;
}
texture = textureCache->addUIImage(image, "cc_fps_images");
texture = textureCache->addImage(image, "/cc_fps_images");
CC_SAFE_RELEASE(image);
/*

View File

@ -130,7 +130,6 @@ Node::Node(void)
ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine();
_scriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone;
_componentContainer = new ComponentContainer(this);
}
Node::~Node()
@ -167,8 +166,6 @@ Node::~Node()
// children
CC_SAFE_RELEASE(_children);
// _comsContainer
_componentContainer->removeAll();
CC_SAFE_DELETE(_componentContainer);
}
@ -1253,22 +1250,30 @@ void Node::updateTransform()
Component* Node::getComponent(const char *pName)
{
return _componentContainer->get(pName);
if( _componentContainer )
return _componentContainer->get(pName);
return nullptr;
}
bool Node::addComponent(Component *pComponent)
{
// lazy alloc
if( !_componentContainer )
_componentContainer = new ComponentContainer(this);
return _componentContainer->add(pComponent);
}
bool Node::removeComponent(const char *pName)
{
return _componentContainer->remove(pName);
if( _componentContainer )
return _componentContainer->remove(pName);
return false;
}
void Node::removeAllComponents()
{
_componentContainer->removeAll();
if( _componentContainer )
_componentContainer->removeAll();
}
// NodeRGBA

View File

@ -41,8 +41,8 @@ static Texture2D* getDefaultTexture()
do
{
bool bRet = false;
const char* key = "__firePngData";
texture = TextureCache::getInstance()->textureForKey(key);
const char* key = "/__firePngData";
texture = TextureCache::getInstance()->getTextureForKey(key);
CC_BREAK_IF(texture != NULL);
pImage = new Image();
@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture()
bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData));
CC_BREAK_IF(!bRet);
texture = TextureCache::getInstance()->addUIImage(pImage, key);
texture = TextureCache::getInstance()->addImage(pImage, key);
} while (0);
CC_SAFE_RELEASE(pImage);

View File

@ -372,7 +372,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
CCASSERT(isOK, "CCParticleSystem: error init image with Data");
CC_BREAK_IF(!isOK);
setTexture(TextureCache::getInstance()->addUIImage(image, textureName.c_str()));
setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str()));
image->release();
}

View File

@ -449,7 +449,7 @@ static tinyxml2::XMLElement* generateElementForArray(cocos2d::Array *array, tiny
#else
NS_CC_BEGIN
/* The subclass FileUtilsIOS and FileUtilsMac should override these two method. */
/* The subclass FileUtilsApple should override these two method. */
Dictionary* FileUtils::createDictionaryWithContentsOfFile(const std::string& filename) {return NULL;}
bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return NULL;}
Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename) {return NULL;}
@ -459,23 +459,12 @@ Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename) {re
FileUtils* FileUtils::s_sharedFileUtils = NULL;
// XXX: deprecated
FileUtils* FileUtils::sharedFileUtils()
{
return FileUtils::getInstance();
}
void FileUtils::destroyInstance()
{
CC_SAFE_DELETE(s_sharedFileUtils);
}
// XXX: deprecated
void FileUtils::purgeFileUtils()
{
FileUtils::destroyInstance();
}
FileUtils::FileUtils()
: _filenameLookupDict(NULL)
{
@ -499,48 +488,48 @@ void FileUtils::purgeCachedEntries()
_fullPathCache.clear();
}
unsigned char* FileUtils::getFileData(const char* filename, const char* pszMode, unsigned long * pSize)
unsigned char* FileUtils::getFileData(const char* filename, const char* mode, unsigned long * size)
{
unsigned char * pBuffer = NULL;
CCASSERT(filename != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters.");
*pSize = 0;
unsigned char * buffer = NULL;
CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters.");
*size = 0;
do
{
// read the file from hardware
std::string fullPath = fullPathForFilename(filename);
FILE *fp = fopen(fullPath.c_str(), pszMode);
FILE *fp = fopen(fullPath.c_str(), mode);
CC_BREAK_IF(!fp);
fseek(fp,0,SEEK_END);
*pSize = ftell(fp);
*size = ftell(fp);
fseek(fp,0,SEEK_SET);
pBuffer = new unsigned char[*pSize];
*pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp);
buffer = new unsigned char[*size];
*size = fread(buffer,sizeof(unsigned char), *size,fp);
fclose(fp);
} while (0);
if (! pBuffer)
if (! buffer)
{
std::string msg = "Get data from file(";
msg.append(filename).append(") failed!");
CCLOG("%s", msg.c_str());
}
return pBuffer;
return buffer;
}
unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* filename, unsigned long * pSize)
unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long * size)
{
unsigned char * pBuffer = NULL;
unsigned char * buffer = NULL;
unzFile pFile = NULL;
*pSize = 0;
*size = 0;
do
{
CC_BREAK_IF(!pszZipFilePath || !filename);
CC_BREAK_IF(strlen(pszZipFilePath) == 0);
CC_BREAK_IF(!zipFilePath || !filename);
CC_BREAK_IF(strlen(zipFilePath) == 0);
pFile = unzOpen(pszZipFilePath);
pFile = unzOpen(zipFilePath);
CC_BREAK_IF(!pFile);
int nRet = unzLocateFile(pFile, filename, 1);
@ -554,11 +543,11 @@ unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const c
nRet = unzOpenCurrentFile(pFile);
CC_BREAK_IF(UNZ_OK != nRet);
pBuffer = new unsigned char[FileInfo.uncompressed_size];
int CC_UNUSED nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size);
buffer = new unsigned char[FileInfo.uncompressed_size];
int CC_UNUSED nSize = unzReadCurrentFile(pFile, buffer, FileInfo.uncompressed_size);
CCASSERT(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong");
*pSize = FileInfo.uncompressed_size;
*size = FileInfo.uncompressed_size;
unzCloseCurrentFile(pFile);
} while (0);
@ -567,22 +556,22 @@ unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const c
unzClose(pFile);
}
return pBuffer;
return buffer;
}
std::string FileUtils::getNewFilename(const char* filename)
std::string FileUtils::getNewFilename(const std::string &filename)
{
const char* pszNewFileName = NULL;
std::string newFileName;
// in Lookup Filename dictionary ?
String* fileNameFound = _filenameLookupDict ? (String*)_filenameLookupDict->objectForKey(filename) : NULL;
if( NULL == fileNameFound || fileNameFound->length() == 0) {
pszNewFileName = filename;
newFileName = filename;
}
else {
pszNewFileName = fileNameFound->getCString();
//CCLOG("FOUND NEW FILE NAME: %s.", pszNewFileName);
newFileName = fileNameFound->getCString();
}
return pszNewFileName;
return newFileName;
}
std::string FileUtils::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath)
@ -608,75 +597,62 @@ std::string FileUtils::getPathForFilename(const std::string& filename, const std
}
std::string FileUtils::fullPathForFilename(const char* filename)
std::string FileUtils::fullPathForFilename(const std::string &filename)
{
CCASSERT(filename != NULL, "CCFileUtils: Invalid path");
std::string strFileName = filename;
if (isAbsolutePath(filename))
{
//CCLOG("Return absolute path( %s ) directly.", filename);
return filename;
}
// Already Cached ?
std::map<std::string, std::string>::iterator cacheIter = _fullPathCache.find(filename);
if (cacheIter != _fullPathCache.end())
auto cacheIter = _fullPathCache.find(filename);
if( cacheIter != _fullPathCache.end() )
{
//CCLOG("Return full path from cache: %s", cacheIter->second.c_str());
return cacheIter->second;
}
// Get the new file name.
std::string newFilename = getNewFilename(filename);
std::string newFilename( getNewFilename(filename) );
string fullpath = "";
for (auto searchPathsIter = _searchPathArray.begin();
searchPathsIter != _searchPathArray.end(); ++searchPathsIter) {
for (auto resOrderIter = _searchResolutionsOrderArray.begin();
resOrderIter != _searchResolutionsOrderArray.end(); ++resOrderIter) {
for (auto searchIt = _searchPathArray.begin(); searchIt != _searchPathArray.end(); ++searchIt) {
for (auto resolutionIt = _searchResolutionsOrderArray.begin(); resolutionIt != _searchResolutionsOrderArray.end(); ++resolutionIt) {
// CCLOG("SEARCHING: %s\n", std::string(*searchPathsIter + *resOrderIter + newFilename).c_str() );
fullpath = this->getPathForFilename(newFilename, *resOrderIter, *searchPathsIter);
fullpath = this->getPathForFilename(newFilename, *resolutionIt, *searchIt);
if (fullpath.length() > 0)
{
// Using the filename passed in as key.
_fullPathCache.insert(std::pair<std::string, std::string>(filename, fullpath));
// CCLOG("Returning path: %s\n", fullpath.c_str());
return fullpath;
}
}
}
// CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename);
CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str());
// XXX: Should it return nullptr ? or an empty string ?
// The file wasn't found, return the file name passed in.
return filename;
}
const char* FileUtils::fullPathFromRelativeFile(const char *filename, const char *pszRelativeFile)
std::string FileUtils::fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile)
{
std::string relativeFile = pszRelativeFile;
String *pRet = String::create("");
pRet->_string = relativeFile.substr(0, relativeFile.rfind('/')+1);
pRet->_string += getNewFilename(filename);
return pRet->getCString();
return relativeFile.substr(0, relativeFile.rfind('/')+1) + getNewFilename(filename);
}
void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder)
{
bool bExistDefault = false;
bool existDefault = false;
_fullPathCache.clear();
_searchResolutionsOrderArray.clear();
for (std::vector<std::string>::const_iterator iter = searchResolutionsOrder.begin(); iter != searchResolutionsOrder.end(); ++iter)
for(auto iter = searchResolutionsOrder.begin(); iter != searchResolutionsOrder.end(); ++iter)
{
std::string resolutionDirectory = *iter;
if (!bExistDefault && resolutionDirectory == "")
if (!existDefault && resolutionDirectory == "")
{
bExistDefault = true;
existDefault = true;
}
if (resolutionDirectory.length() > 0 && resolutionDirectory[resolutionDirectory.length()-1] != '/')
@ -686,13 +662,13 @@ void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& search
_searchResolutionsOrderArray.push_back(resolutionDirectory);
}
if (!bExistDefault)
if (!existDefault)
{
_searchResolutionsOrderArray.push_back("");
}
}
void FileUtils::addSearchResolutionsOrder(const char* order)
void FileUtils::addSearchResolutionsOrder(const std::string &order)
{
_searchResolutionsOrderArray.push_back(order);
}
@ -702,53 +678,52 @@ const std::vector<std::string>& FileUtils::getSearchResolutionsOrder()
return _searchResolutionsOrderArray;
}
const std::vector<std::string>& FileUtils::getSearchPaths()
const std::vector<std::string>& FileUtils::getSearchPaths() const
{
return _searchPathArray;
}
void FileUtils::setSearchPaths(const std::vector<std::string>& searchPaths)
{
bool bExistDefaultRootPath = false;
bool existDefaultRootPath = false;
_fullPathCache.clear();
_searchPathArray.clear();
for (std::vector<std::string>::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter)
for (auto iter = searchPaths.begin(); iter != searchPaths.end(); ++iter)
{
std::string strPrefix;
std::string path;
if (!isAbsolutePath(*iter))
{ // Not an absolute path
strPrefix = _defaultResRootPath;
}
path = strPrefix+(*iter);
path = strPrefix + (*iter);
if (path.length() > 0 && path[path.length()-1] != '/')
{
path += "/";
}
if (!bExistDefaultRootPath && path == _defaultResRootPath)
if (!existDefaultRootPath && path == _defaultResRootPath)
{
bExistDefaultRootPath = true;
existDefaultRootPath = true;
}
_searchPathArray.push_back(path);
}
if (!bExistDefaultRootPath)
if (!existDefaultRootPath)
{
//CCLOG("Default root path doesn't exist, adding it.");
_searchPathArray.push_back(_defaultResRootPath);
}
}
void FileUtils::addSearchPath(const char* path_)
void FileUtils::addSearchPath(const std::string &searchpath)
{
std::string strPrefix;
std::string path(path_);
if (!isAbsolutePath(path))
{ // Not an absolute path
if (!isAbsolutePath(searchpath))
strPrefix = _defaultResRootPath;
}
path = strPrefix + path;
std::string path = strPrefix + searchpath;
if (path.length() > 0 && path[path.length()-1] != '/')
{
path += "/";
@ -764,22 +739,22 @@ void FileUtils::setFilenameLookupDictionary(Dictionary* pFilenameLookupDict)
CC_SAFE_RETAIN(_filenameLookupDict);
}
void FileUtils::loadFilenameLookupDictionaryFromFile(const char* filename)
void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename)
{
std::string fullPath = this->fullPathForFilename(filename);
std::string fullPath = fullPathForFilename(filename);
if (fullPath.length() > 0)
{
Dictionary* pDict = Dictionary::createWithContentsOfFile(fullPath.c_str());
if (pDict)
Dictionary* dict = Dictionary::createWithContentsOfFile(fullPath.c_str());
if (dict)
{
Dictionary* pMetadata = (Dictionary*)pDict->objectForKey("metadata");
int version = ((String*)pMetadata->objectForKey("version"))->intValue();
Dictionary* metadata = static_cast<Dictionary*>( dict->objectForKey("metadata") );
int version = static_cast<String*>( metadata->objectForKey("version"))->intValue();
if (version != 1)
{
CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename);
CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename.c_str());
return;
}
setFilenameLookupDictionary((Dictionary*)pDict->objectForKey("filenames"));
setFilenameLookupDictionary( static_cast<Dictionary*>( dict->objectForKey("filenames")) );
}
}
}
@ -800,24 +775,24 @@ std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string& str
return ret;
}
bool FileUtils::isAbsolutePath(const std::string& strPath)
bool FileUtils::isAbsolutePath(const std::string& strPath) const
{
return strPath[0] == '/' ? true : false;
return (strPath[0] == '/');
}
//////////////////////////////////////////////////////////////////////////
// Notification support when getFileData from invalid file path.
//////////////////////////////////////////////////////////////////////////
static bool s_bPopupNotify = true;
static bool s_popupNotify = true;
void FileUtils::setPopupNotify(bool bNotify)
void FileUtils::setPopupNotify(bool notify)
{
s_bPopupNotify = bNotify;
s_popupNotify = notify;
}
bool FileUtils::isPopupNotify()
{
return s_bPopupNotify;
return s_popupNotify;
}
NS_CC_END

View File

@ -57,10 +57,10 @@ public:
static void destroyInstance();
/** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static FileUtils* sharedFileUtils();
CC_DEPRECATED_ATTRIBUTE static FileUtils* sharedFileUtils() { return getInstance(); }
/** @deprecated Use destroyInstance() instead */
CC_DEPRECATED_ATTRIBUTE static void purgeFileUtils();
CC_DEPRECATED_ATTRIBUTE static void purgeFileUtils() { destroyInstance(); }
/**
* The destructor of FileUtils.
@ -86,7 +86,7 @@ public:
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/
virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize);
virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size);
/**
* Gets resource file data from a zip file.
@ -96,7 +96,7 @@ public:
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/
virtual unsigned char* getFileDataFromZip(const char* pszZipFilePath, const char* filename, unsigned long *size);
virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long *size);
/** Returns the fullpath for a given filename.
@ -144,7 +144,7 @@ public:
@since v2.1
*/
virtual std::string fullPathForFilename(const char* filename);
virtual std::string fullPathForFilename(const std::string &filename);
/**
* Loads the filenameLookup dictionary from the contents of a filename.
@ -177,7 +177,7 @@ public:
*
@since v2.1
*/
virtual void loadFilenameLookupDictionaryFromFile(const char* filename);
virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
/**
* Sets the filenameLookup dictionary.
@ -185,7 +185,7 @@ public:
* @param pFilenameLookupDict The dictionary for replacing filename.
* @since v2.1
*/
virtual void setFilenameLookupDictionary(Dictionary* pFilenameLookupDict);
virtual void setFilenameLookupDictionary(Dictionary* filenameLookupDict);
/**
* Gets full path from a file name and the path of the reletive file.
@ -196,7 +196,7 @@ public:
* Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )
*
*/
virtual const char* fullPathFromRelativeFile(const char *filename, const char *pszRelativeFile);
virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);
/**
* Sets the array that contains the search order of the resources.
@ -213,7 +213,7 @@ public:
* @see setSearchResolutionsOrder(), fullPathForFilename().
* @since v2.1
*/
virtual void addSearchResolutionsOrder(const char* order);
virtual void addSearchResolutionsOrder(const std::string &order);
/**
* Gets the array that contains the search order of the resources.
@ -247,7 +247,7 @@ public:
*
* @since v2.1
*/
void addSearchPath(const char* path);
void addSearchPath(const std::string & path);
/**
* Gets the array of search paths.
@ -255,13 +255,13 @@ public:
* @return The array of search paths.
* @see fullPathForFilename(const char*).
*/
virtual const std::vector<std::string>& getSearchPaths();
virtual const std::vector<std::string>& getSearchPaths() const;
/**
* Gets the writable path.
* @return The path that can be write/read a file in
*/
virtual std::string getWritablePath() = 0;
virtual std::string getWritablePath() const = 0;
/**
* Checks whether a file exists.
@ -270,7 +270,7 @@ public:
* @param strFilePath The path of the file, it could be a relative or absolute path.
* @return true if the file exists, otherwise it will return false.
*/
virtual bool isFileExist(const std::string& strFilePath) = 0;
virtual bool isFileExist(const std::string& filePath) const = 0;
/**
* Checks whether the path is an absolute path.
@ -281,13 +281,13 @@ public:
* @param strPath The path that needs to be checked.
* @return true if it's an absolute path, otherwise it will return false.
*/
virtual bool isAbsolutePath(const std::string& strPath);
virtual bool isAbsolutePath(const std::string& path) const;
/**
* Sets/Gets whether to pop-up a message box when failed to load an image.
*/
virtual void setPopupNotify(bool bNotify);
virtual void setPopupNotify(bool notify);
virtual bool isPopupNotify();
protected:
@ -308,11 +308,12 @@ protected:
/**
* Gets the new filename from the filename lookup dictionary.
* It is possible to have a override names.
* @param filename The original filename.
* @return The new filename after searching in the filename lookup dictionary.
* If the original filename wasn't in the dictionary, it will return the original filename.
*/
virtual std::string getNewFilename(const char* filename);
virtual std::string getNewFilename(const std::string &filename);
/**
* Gets full path for filename, resolution directory and search path.
@ -334,7 +335,7 @@ protected:
* @param strFilename The name of the file.
* @return The full path of the file, if the file can't be found, it will return an empty string.
*/
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename);
virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename);
/**
* Creates a dictionary by the contents of a file.

View File

@ -76,7 +76,7 @@ bool FileUtilsAndroid::init()
return FileUtils::init();
}
bool FileUtilsAndroid::isFileExist(const std::string& strFilePath)
bool FileUtilsAndroid::isFileExist(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
{
@ -116,7 +116,7 @@ bool FileUtilsAndroid::isFileExist(const std::string& strFilePath)
return bFound;
}
bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath)
bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const
{
// On Android, there are two situations for full path.
// 1) Files in APK, e.g. assets/path/path/file.png
@ -235,7 +235,7 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char*
return pData;
}
string FileUtilsAndroid::getWritablePath()
string FileUtilsAndroid::getWritablePath() const
{
// Fix for Nexus 10 (Android 4.2 multi-user environment)
// the path is retrieved through Java Context.getCacheDir() method

View File

@ -52,9 +52,10 @@ public:
/* override funtions */
bool init();
virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize);
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath);
virtual std::string getWritablePath() const;
virtual bool isFileExist(const std::string& strFilePath) const;
virtual bool isAbsolutePath(const std::string& strPath) const;
/** This function is android specific. It is used for TextureCache::addImageAsync().
Don't use it in your codes.

View File

@ -21,8 +21,8 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CC_FILEUTILS_IOS_H__
#define __CC_FILEUTILS_IOS_H__
#ifndef __CC_FILEUTILS_APPLE_H__
#define __CC_FILEUTILS_APPLE_H__
#include "CCFileUtils.h"
#include <string>
@ -38,19 +38,18 @@ NS_CC_BEGIN
*/
//! @brief Helper class to handle file operations
class CC_DLL FileUtilsIOS : public FileUtils
class CC_DLL FileUtilsApple : public FileUtils
{
public:
/* override funtions */
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath);
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename);
virtual std::string getWritablePath() const override;
virtual bool isFileExist(const std::string& strFilePath) const override;
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) override;
virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename);
virtual bool writeToFile(Dictionary *dict, const std::string& fullPath);
virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename) override;
virtual bool writeToFile(Dictionary *dict, const std::string& fullPath) override;
virtual Array* createArrayWithContentsOfFile(const std::string& filename);
virtual Array* createArrayWithContentsOfFile(const std::string& filename) override;
};
// end of platform group
@ -58,5 +57,5 @@ public:
NS_CC_END
#endif // __CC_FILEUTILS_IOS_H__
#endif // __CC_FILEUTILS_APPLE_H__

View File

@ -23,7 +23,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import <Foundation/Foundation.h>
#import <UIKit/UIDevice.h>
#include <string>
#include <stack>
@ -34,7 +33,7 @@ THE SOFTWARE.
#include "CCDictionary.h"
#include "support/zip_support/unzip.h"
#include "CCFileUtilsIOS.h"
#include "CCFileUtilsApple.h"
NS_CC_BEGIN
@ -210,25 +209,28 @@ static void addObjectToNSDict(const char * key, Object* object, NSMutableDiction
}
}
#pragma mark - FileUtils
static NSFileManager* s_fileManager = [NSFileManager defaultManager];
FileUtils* FileUtils::getInstance()
{
if (s_sharedFileUtils == NULL)
{
s_sharedFileUtils = new FileUtilsIOS();
s_sharedFileUtils = new FileUtilsApple();
if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsIOS");
CCLOG("ERROR: Could not init CCFileUtilsApple");
}
}
return s_sharedFileUtils;
}
static NSFileManager* s_fileManager = [NSFileManager defaultManager];
std::string FileUtilsIOS::getWritablePath()
std::string FileUtilsApple::getWritablePath() const
{
// save to document folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
@ -238,9 +240,9 @@ std::string FileUtilsIOS::getWritablePath()
return strRet;
}
bool FileUtilsIOS::isFileExist(const std::string& strFilePath)
bool FileUtilsApple::isFileExist(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
if(strFilePath.length() == 0)
{
return false;
}
@ -280,7 +282,7 @@ bool FileUtilsIOS::isFileExist(const std::string& strFilePath)
return bRet;
}
std::string FileUtilsIOS::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename)
std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename)
{
if (strDirectory[0] != '/')
{
@ -302,15 +304,9 @@ std::string FileUtilsIOS::getFullPathForDirectoryAndFilename(const std::string&
return "";
}
bool FileUtilsIOS::isAbsolutePath(const std::string& strPath)
Dictionary* FileUtilsApple::createDictionaryWithContentsOfFile(const std::string& filename)
{
NSString* path = [NSString stringWithUTF8String:strPath.c_str()];
return [path isAbsolutePath] ? true : false;
}
Dictionary* FileUtilsIOS::createDictionaryWithContentsOfFile(const std::string& filename)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
std::string fullPath = fullPathForFilename(filename);
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()];
NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath];
@ -330,7 +326,7 @@ Dictionary* FileUtilsIOS::createDictionaryWithContentsOfFile(const std::string&
}
}
bool FileUtilsIOS::writeToFile(Dictionary *dict, const std::string &fullPath)
bool FileUtilsApple::writeToFile(Dictionary *dict, const std::string &fullPath)
{
//CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
@ -348,14 +344,14 @@ bool FileUtilsIOS::writeToFile(Dictionary *dict, const std::string &fullPath)
return true;
}
Array* FileUtilsIOS::createArrayWithContentsOfFile(const std::string& filename)
Array* FileUtilsApple::createArrayWithContentsOfFile(const std::string& filename)
{
// NSString* pPath = [NSString stringWithUTF8String:pFileName];
// NSString* pathExtension= [pPath pathExtension];
// pPath = [pPath stringByDeletingPathExtension];
// pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension];
// fixing cannot read data using Array::createWithContentsOfFile
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
std::string fullPath = fullPathForFilename(filename);
NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
NSArray* array = [NSArray arrayWithContentsOfFile:path];

View File

@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//#import <UIKit/UIKit.h>
#include "CCThread.h"
NS_CC_BEGIN

View File

@ -33,7 +33,7 @@ bool FileUtilsEmscripten::init()
return FileUtils::init();
}
string FileUtilsEmscripten::getWritablePath()
string FileUtilsEmscripten::getWritablePath() const
{
// Let's write it in the current working directory's data folder
char cwd[FILENAME_MAX] = {0};
@ -47,7 +47,7 @@ string FileUtilsEmscripten::getWritablePath()
return path;
}
bool FileUtilsEmscripten::isAbsolutePath(const std::string& strPath)
bool FileUtilsEmscripten::isAbsolutePath(const std::string& strPath) const
{
if (strPath[0] == '/' || strPath.find(_defaultResRootPath) == 0)
{
@ -56,7 +56,7 @@ bool FileUtilsEmscripten::isAbsolutePath(const std::string& strPath)
return false;
}
bool FileUtilsEmscripten::isFileExist(const std::string& strFilePath)
bool FileUtilsEmscripten::isFileExist(const std::string& strFilePath) const
{
std::string strPath = strFilePath;
if (strPath[0] != '/')

View File

@ -42,12 +42,13 @@ class CC_DLL FileUtilsEmscripten : public FileUtils
{
friend class FileUtils;
FileUtilsEmscripten();
public:
/* override funtions */
bool init();
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath);
virtual std::string getWritablePath() const;
virtual bool isFileExist(const std::string& strFilePath) const;
virtual bool isAbsolutePath(const std::string& strPath) const;
};
// end of platform group

View File

@ -1,39 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import <UIKit/UIKit.h>
#include "CCThread.h"
NS_CC_BEGIN
Thread::~Thread()
{
[(id)_autoReleasePool release];
}
void Thread::createAutoreleasePool()
{
_autoReleasePool = [[NSAutoreleasePool alloc] init];
}
NS_CC_END

View File

@ -67,7 +67,7 @@ bool FileUtilsLinux::init()
return FileUtils::init();
}
string FileUtilsLinux::getWritablePath()
string FileUtilsLinux::getWritablePath() const
{
struct stat st;
stat(_writablePath.c_str(), &st);
@ -78,7 +78,7 @@ string FileUtilsLinux::getWritablePath()
return _writablePath;
}
bool FileUtilsLinux::isFileExist(const std::string& strFilePath)
bool FileUtilsLinux::isFileExist(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
{

View File

@ -46,8 +46,8 @@ class CC_DLL FileUtilsLinux : public FileUtils
public:
/* override funtions */
bool init();
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual std::string getWritablePath() const;
virtual bool isFileExist(const std::string& strFilePath) const;
};
// end of platform group

View File

@ -1,62 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CC_FILEUTILSMAC_H__
#define __CC_FILEUTILSMAC_H__
#include "CCFileUtils.h"
#include <string>
#include <vector>
#include "CCPlatformMacros.h"
#include "ccTypes.h"
NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
//! @brief Helper class to handle file operations
class CC_DLL FileUtilsMac : public FileUtils
{
public:
/* override funtions */
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath);
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename);
virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename);
virtual bool writeToFile(Dictionary *dict, const std::string& fullPath);
virtual Array* createArrayWithContentsOfFile(const std::string& filename);
};
// end of platform group
/// @}
NS_CC_END
#endif // __CC_FILEUTILSMAC_H__

View File

@ -1,354 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCFileUtilsMac.h"
#import <Foundation/Foundation.h>
#include <string>
#include <stack>
#include "cocoa/CCString.h"
#include "CCFileUtils.h"
#include "CCDirector.h"
#include "CCSAXParser.h"
#include "CCDictionary.h"
#include "support/zip_support/unzip.h"
NS_CC_BEGIN
static void addValueToDict(id key, id value, Dictionary* pDict);
static void addObjectToNSDict(const char*key, Object* object, NSMutableDictionary *dict);
static void addItemToArray(id item, Array *array)
{
// add string value into array
if ([item isKindOfClass:[NSString class]]) {
String* pValue = new String([item UTF8String]);
array->addObject(pValue);
pValue->release();
return;
}
// add number value into array(such as int, float, bool and so on)
if ([item isKindOfClass:[NSNumber class]]) {
NSString* pStr = [item stringValue];
String* pValue = new String([pStr UTF8String]);
array->addObject(pValue);
pValue->release();
return;
}
// add dictionary value into array
if ([item isKindOfClass:[NSDictionary class]]) {
Dictionary* pDictItem = new Dictionary();
pDictItem->init();
for (id subKey in [item allKeys]) {
id subValue = [item objectForKey:subKey];
addValueToDict(subKey, subValue, pDictItem);
}
array->addObject(pDictItem);
pDictItem->release();
return;
}
// add array value into array
if ([item isKindOfClass:[NSArray class]]) {
Array *arrayItem = new Array();
arrayItem->initWithCapacity( [item count] );
for (id subItem in item) {
addItemToArray(subItem, arrayItem);
}
array->addObject(arrayItem);
arrayItem->release();
return;
}
}
static void addObjectToNSArray(Object *object, NSMutableArray *array)
{
// add string into array
if (String *ccString = dynamic_cast<String *>(object)) {
NSString *strElement = [NSString stringWithCString:ccString->getCString() encoding:NSUTF8StringEncoding];
[array addObject:strElement];
return;
}
// add array into array
if (Array *ccArray = dynamic_cast<Array *>(object)) {
NSMutableArray *arrElement = [NSMutableArray array];
Object *element = NULL;
CCARRAY_FOREACH(ccArray, element)
{
addObjectToNSArray(element, arrElement);
}
[array addObject:arrElement];
return;
}
// add dictionary value into array
if (Dictionary *ccDict = dynamic_cast<Dictionary *>(object)) {
NSMutableDictionary *dictElement = [NSMutableDictionary dictionary];
DictElement *element = NULL;
CCDICT_FOREACH(ccDict, element)
{
addObjectToNSDict(element->getStrKey(), element->getObject(), dictElement);
}
[array addObject:dictElement];
}
}
static void addValueToDict(id key, id value, Dictionary* pDict)
{
// the key must be a string
CCASSERT([key isKindOfClass:[NSString class]], "The key should be a string!");
std::string pKey = [key UTF8String];
// the value is a new dictionary
if ([value isKindOfClass:[NSDictionary class]]) {
Dictionary* pSubDict = new Dictionary();
for (id subKey in [value allKeys]) {
id subValue = [value objectForKey:subKey];
addValueToDict(subKey, subValue, pSubDict);
}
pDict->setObject(pSubDict, pKey.c_str());
pSubDict->release();
return;
}
// the value is a string
if ([value isKindOfClass:[NSString class]]) {
String* pValue = new String([value UTF8String]);
pDict->setObject(pValue, pKey.c_str());
pValue->release();
return;
}
// the value is a number
if ([value isKindOfClass:[NSNumber class]]) {
NSString* pStr = [value stringValue];
String* pValue = new String([pStr UTF8String]);
pDict->setObject(pValue, pKey.c_str());
pValue->release();
return;
}
// the value is a array
if ([value isKindOfClass:[NSArray class]]) {
Array *array = new Array();
array->initWithCapacity([value count]);
for (id item in value) {
addItemToArray(item, array);
}
pDict->setObject(array, pKey.c_str());
array->release();
return;
}
}
static void addObjectToNSDict(const char * key, Object* object, NSMutableDictionary *dict)
{
NSString *NSkey = [NSString stringWithCString:key encoding:NSUTF8StringEncoding];
// the object is a Dictionary
if (Dictionary *ccDict = dynamic_cast<Dictionary *>(object)) {
NSMutableDictionary *dictElement = [NSMutableDictionary dictionary];
DictElement *element = NULL;
CCDICT_FOREACH(ccDict, element)
{
addObjectToNSDict(element->getStrKey(), element->getObject(), dictElement);
}
[dict setObject:dictElement forKey:NSkey];
return;
}
// the object is a String
if (String *element = dynamic_cast<String *>(object)) {
NSString *strElement = [NSString stringWithCString:element->getCString() encoding:NSUTF8StringEncoding];
[dict setObject:strElement forKey:NSkey];
return;
}
// the object is a Array
if (Array *ccArray = dynamic_cast<Array *>(object)) {
NSMutableArray *arrElement = [NSMutableArray array];
Object *element = NULL;
CCARRAY_FOREACH(ccArray, element)
{
addObjectToNSArray(element, arrElement);
}
[dict setObject:arrElement forKey:NSkey];
return;
}
}
FileUtils* FileUtils::getInstance()
{
if (s_sharedFileUtils == NULL)
{
s_sharedFileUtils = new FileUtilsMac();
if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsMac");
}
}
return s_sharedFileUtils;
}
static NSFileManager* s_fileManager = [NSFileManager defaultManager];
std::string FileUtilsMac::getWritablePath()
{
// save to document folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
std::string strRet = [documentsDirectory UTF8String];
strRet.append("/");
return strRet;
}
bool FileUtilsMac::isFileExist(const std::string& strFilePath)
{
if (0 == strFilePath.length())
{
return false;
}
bool bRet = false;
if (strFilePath[0] != '/')
{
std::string path = strFilePath;
std::string file;
size_t pos = path.find_last_of("/");
if (pos != std::string::npos)
{
file = path.substr(pos+1);
path = path.substr(0, pos+1);
NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:file.c_str()]
ofType:nil
inDirectory:[NSString stringWithUTF8String:path.c_str()]];
if (fullpath != nil) {
bRet = true;
}
}
}
else
{
// Search path is an absolute path.
if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:strFilePath.c_str()]]) {
bRet = true;
}
}
return bRet;
}
std::string FileUtilsMac::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename)
{
if (strDirectory[0] != '/')
{
NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:strFilename.c_str()]
ofType:nil
inDirectory:[NSString stringWithUTF8String:strDirectory.c_str()]];
if (fullpath != nil) {
return [fullpath UTF8String];
}
}
else
{
std::string fullPath = strDirectory+strFilename;
// Search path is an absolute path.
if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) {
return fullPath;
}
}
return "";
}
bool FileUtilsMac::isAbsolutePath(const std::string& strPath)
{
NSString* path = [NSString stringWithUTF8String:strPath.c_str()];
return [path isAbsolutePath] ? true : false;
}
Dictionary* FileUtilsMac::createDictionaryWithContentsOfFile(const std::string& filename)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()];
NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath];
Dictionary* pRet = Dictionary::create();
for (id key in [pDict allKeys]) {
id value = [pDict objectForKey:key];
addValueToDict(key, value, pRet);
}
return pRet;
}
bool FileUtilsMac::writeToFile(Dictionary *dict, const std::string &fullPath)
{
CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
DictElement *element = NULL;
CCDICT_FOREACH(dict, element)
{
addObjectToNSDict(element->getStrKey(), element->getObject(), nsDict);
}
NSString *file = [NSString stringWithUTF8String:fullPath.c_str()];
// do it atomically
return [nsDict writeToFile:file atomically:YES];
}
Array* FileUtilsMac::createArrayWithContentsOfFile(const std::string& filename)
{
// NSString* pPath = [NSString stringWithUTF8String:pFileName];
// NSString* pathExtension= [pPath pathExtension];
// pPath = [pPath stringByDeletingPathExtension];
// pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension];
// fixing cannot read data using Array::createWithContentsOfFile
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()];
NSArray* array = [NSArray arrayWithContentsOfFile:pPath];
Array* ret = Array::createWithCapacity( [array count] );
for (id value in array) {
addItemToArray(value, ret);
}
return ret;
}
NS_CC_END

View File

@ -84,7 +84,7 @@ FileUtilsQt5::init()
}
std::string
FileUtilsQt5::getWritablePath()
FileUtilsQt5::getWritablePath() const
{
QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
@ -96,7 +96,7 @@ FileUtilsQt5::getWritablePath()
return dir.path().toStdString();
}
bool FileUtilsQt5::isFileExist(const std::string& strFilePath)
bool FileUtilsQt5::isFileExist(const std::string& strFilePath) const
{
QString filePath = QString::fromStdString(strFilePath);

View File

@ -80,7 +80,7 @@ bool FileUtilsTizen::init()
return FileUtils::init();
}
string FileUtilsTizen::getWritablePath()
string FileUtilsTizen::getWritablePath() const
{
UiApp* pApp = UiApp::GetInstance();
if (!pApp)
@ -101,7 +101,7 @@ string FileUtilsTizen::getWritablePath()
return path;
}
bool FileUtilsTizen::isFileExist(const std::string& strFilePath)
bool FileUtilsTizen::isFileExist(const std::string& strFilePath) const
{
std::string strPath = strFilePath;
if (!isAbsolutePath(strPath))

View File

@ -47,8 +47,8 @@ class CC_DLL FileUtilsTizen : public FileUtils
public:
/* override funtions */
bool init();
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual std::string getWritablePath() const;
virtual bool isFileExist(const std::string& strFilePath) const;
};
// end of platform group

View File

@ -91,7 +91,7 @@ bool FileUtilsWin32::init()
return FileUtils::init();
}
bool FileUtilsWin32::isFileExist(const std::string& strFilePath)
bool FileUtilsWin32::isFileExist(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
{
@ -110,7 +110,7 @@ bool FileUtilsWin32::isFileExist(const std::string& strFilePath)
return GetFileAttributesW(utf16Buf) != -1 ? true : false;
}
bool FileUtilsWin32::isAbsolutePath(const std::string& strPath)
bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const
{
if ( strPath.length() > 2
&& ( (strPath[0] >= 'a' && strPath[0] <= 'z') || (strPath[0] >= 'A' && strPath[0] <= 'Z') )
@ -182,7 +182,7 @@ std::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const std::string
return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
}
string FileUtilsWin32::getWritablePath()
string FileUtilsWin32::getWritablePath() const
{
// Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
char full_path[CC_MAX_PATH + 1];

View File

@ -45,9 +45,9 @@ class CC_DLL FileUtilsWin32 : public FileUtils
public:
/* override funtions */
bool init();
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath);
virtual std::string getWritablePath() const;
virtual bool isFileExist(const std::string& strFilePath) const;
virtual bool isAbsolutePath(const std::string& strPath) const;
protected:
/**
* Gets resource file data

View File

@ -76,22 +76,22 @@ void ShaderCache::purgeSharedShaderCache()
}
ShaderCache::ShaderCache()
: _programs(0)
: _programs()
{
}
ShaderCache::~ShaderCache()
{
for( auto it = _programs.begin(); it != _programs.end(); ++it ) {
(it->second)->release();
}
CCLOGINFO("deallocing ShaderCache: %p", this);
_programs->release();
}
bool ShaderCache::init()
{
_programs = Dictionary::create();
_programs->retain();
{
loadDefaultShaders();
return true;
}
@ -101,70 +101,54 @@ void ShaderCache::loadDefaultShaders()
// Position Texture Color shader
GLProgram *p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionTextureColor);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR);
p->release();
_programs.insert( std::make_pair( GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR, p ) );
// Position Texture Color alpha test
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTest);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST);
p->release();
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST, p) );
//
// Position, Color shader
//
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionColor);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_COLOR);
p->release();
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_COLOR, p) );
//
// Position Texture shader
//
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionTexture);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_TEXTURE);
p->release();
_programs.insert( std::make_pair( GLProgram::SHADER_NAME_POSITION_TEXTURE, p) );
//
// Position, Texture attribs, 1 Color as uniform shader
//
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionTexture_uColor);
_programs->setObject(p ,GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR);
p->release();
_programs.insert( std::make_pair( GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR, p) );
//
// Position Texture A8 Color shader
//
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionTextureA8Color);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR);
p->release();
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR, p) );
//
// Position and 1 color passed as a uniform (to simulate glColor4ub )
//
p = new GLProgram();
loadDefaultShader(p, kShaderType_Position_uColor);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_U_COLOR);
p->release();
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_U_COLOR, p) );
//
// Position, Legth(TexCoords, Color (used by Draw Node basically )
//
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionLengthTexureColor);
_programs->setObject(p, GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR);
p->release();
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR, p) );
}
void ShaderCache::reloadDefaultShaders()
@ -297,14 +281,18 @@ void ShaderCache::loadDefaultShader(GLProgram *p, int type)
CHECK_GL_ERROR_DEBUG();
}
GLProgram* ShaderCache::programForKey(const char* key)
GLProgram* ShaderCache::programForKey(const std::string &key)
{
return static_cast<GLProgram*>(_programs->objectForKey(key));
auto it = _programs.find(key);
if( it != _programs.end() )
return it->second;
return nullptr;
}
void ShaderCache::addProgram(GLProgram* program, const char* key)
void ShaderCache::addProgram(GLProgram* program, const std::string &key)
{
_programs->setObject(program, key);
program->retain();
_programs.insert( std::make_pair( key, program) );
}
NS_CC_END

View File

@ -27,6 +27,9 @@ THE SOFTWARE.
#ifndef __CCSHADERCACHE_H__
#define __CCSHADERCACHE_H__
#include <string>
#include <unordered_map>
#include "cocoa/CCDictionary.h"
NS_CC_BEGIN
@ -68,17 +71,17 @@ public:
void reloadDefaultShaders();
/** returns a GL program for a given key */
GLProgram * programForKey(const char* key);
GLProgram * programForKey(const std::string &key);
/** adds a GLProgram to the cache for a given name */
void addProgram(GLProgram* program, const char* key);
void addProgram(GLProgram* program, const std::string &key);
private:
bool init();
void loadDefaultShader(GLProgram *program, int type);
Dictionary* _programs;
// Dictionary* _programs;
std::unordered_map<std::string, GLProgram*> _programs;
};
// end of shaders group

View File

@ -1089,7 +1089,7 @@ static unsigned char cc_2x2_white_image[] = {
0xFF, 0xFF, 0xFF, 0xFF
};
#define CC_2x2_WHITE_IMAGE_KEY "cc_2x2_white_image"
#define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image"
void Sprite::setTexture(Texture2D *texture)
{
@ -1110,7 +1110,7 @@ void Sprite::setTexture(Texture2D *texture)
bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8);
CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully.");
texture = TextureCache::getInstance()->addUIImage(image, CC_2x2_WHITE_IMAGE_KEY);
texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY);
CC_SAFE_RELEASE(image);
}
}

View File

@ -119,22 +119,22 @@ public:
struct PixelFormatInfo {
public:
PixelFormatInfo(GLenum internalFormat, GLenum format, GLenum type, int bpp, bool compressed, bool alpha)
: internalFormat(internalFormat)
, format(format)
, type(type)
, bpp(bpp)
, compressed(compressed)
, alpha(alpha)
{}
GLenum internalFormat;
GLenum format;
GLenum type;
int bpp;
bool compressed;
bool alpha;
PixelFormatInfo(GLenum internalFormat, GLenum format, GLenum type, int bpp, bool compressed, bool alpha)
:internalFormat(internalFormat),
format(format),
type(type),
bpp(bpp),
compressed(compressed),
alpha(alpha)
{}
};
typedef std::map<Texture2D::PixelFormat, const PixelFormatInfo> PixelFormatInfoMap;

View File

@ -74,17 +74,14 @@ TextureCache::TextureCache()
, _asyncRefCount(0)
{
CCASSERT(_sharedTextureCache == nullptr, "Attempted to allocate a second instance of a singleton.");
_textures = new Dictionary();
_textures->init();
}
TextureCache::~TextureCache()
{
CCLOGINFO("deallocing TextureCache: %p", this);
CC_SAFE_RELEASE(_textures);
for( auto it=_textures.begin(); it!=_textures.end(); ++it)
(it->second)->release();
CC_SAFE_DELETE(_loadingThread);
_sharedTextureCache = nullptr;
@ -102,42 +99,34 @@ void TextureCache::destroyInstance()
const char* TextureCache::description() const
{
return String::createWithFormat("<TextureCache | Number of textures = %u>", _textures->count())->getCString();
return String::createWithFormat("<TextureCache | Number of textures = %lu>", _textures.size() )->getCString();
}
Dictionary* TextureCache::snapshotTextures()
{
Dictionary* pRet = new Dictionary();
DictElement* pElement = NULL;
CCDICT_FOREACH(_textures, pElement)
{
pRet->setObject(pElement->getObject(), pElement->getStrKey());
}
pRet->autorelease();
return pRet;
}
//Dictionary* TextureCache::snapshotTextures()
//{
// Dictionary* pRet = new Dictionary();
// DictElement* pElement = NULL;
// CCDICT_FOREACH(_textures, pElement)
// {
// pRet->setObject(pElement->getObject(), pElement->getStrKey());
// }
// pRet->autorelease();
// return pRet;
//}
void TextureCache::addImageAsync(const char *path, Object *target, SEL_CallFuncO selector)
void TextureCache::addImageAsync(const std::string &path, Object *target, SEL_CallFuncO selector)
{
CCASSERT(path != NULL, "TextureCache: fileimage MUST not be NULL");
Texture2D *texture = NULL;
// optimization
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str());
std::string pathKey = path;
auto it = _textures.find(fullpath);
if( it != _textures.end() )
texture = it->second;
pathKey = FileUtils::getInstance()->fullPathForFilename(pathKey.c_str());
texture = static_cast<Texture2D*>(_textures->objectForKey(pathKey.c_str()));
std::string fullpath = pathKey;
if (texture != NULL)
if (texture != NULL && target && selector)
{
if (target && selector)
{
(target->*selector)(texture);
}
(target->*selector)(texture);
return;
}
@ -178,7 +167,7 @@ void TextureCache::addImageAsync(const char *path, Object *target, SEL_CallFuncO
void TextureCache::loadImage()
{
AsyncStruct *pAsyncStruct = nullptr;
AsyncStruct *asyncStruct = nullptr;
while (true)
{
@ -202,30 +191,30 @@ void TextureCache::loadImage()
}
else
{
pAsyncStruct = pQueue->front();
asyncStruct = pQueue->front();
pQueue->pop();
_asyncStructQueueMutex.unlock();
}
const char *filename = pAsyncStruct->filename.c_str();
const char *filename = asyncStruct->filename.c_str();
// generate image
Image *pImage = new Image();
if (pImage && !pImage->initWithImageFileThreadSafe(filename))
Image *image = new Image();
if (image && !image->initWithImageFileThreadSafe(filename))
{
CC_SAFE_RELEASE(pImage);
CC_SAFE_RELEASE(image);
CCLOG("can not load %s", filename);
continue;
}
// generate image info
ImageInfo *pImageInfo = new ImageInfo();
pImageInfo->asyncStruct = pAsyncStruct;
pImageInfo->image = pImage;
ImageInfo *imageInfo = new ImageInfo();
imageInfo->asyncStruct = asyncStruct;
imageInfo->image = image;
// put the image info into the queue
_imageInfoMutex.lock();
_imageInfoQueue->push(pImageInfo);
_imageInfoQueue->push(imageInfo);
_imageInfoMutex.unlock();
}
@ -250,28 +239,30 @@ void TextureCache::addImageAsyncCallBack(float dt)
}
else
{
ImageInfo *pImageInfo = imagesQueue->front();
ImageInfo *imageInfo = imagesQueue->front();
imagesQueue->pop();
_imageInfoMutex.unlock();
AsyncStruct *pAsyncStruct = pImageInfo->asyncStruct;
Image *pImage = pImageInfo->image;
AsyncStruct *asyncStruct = imageInfo->asyncStruct;
Image *image = imageInfo->image;
Object *target = pAsyncStruct->target;
SEL_CallFuncO selector = pAsyncStruct->selector;
const char* filename = pAsyncStruct->filename.c_str();
Object *target = asyncStruct->target;
SEL_CallFuncO selector = asyncStruct->selector;
const char* filename = asyncStruct->filename.c_str();
// generate texture in render thread
Texture2D *texture = new Texture2D();
texture->initWithImage(pImage);
texture->initWithImage(image);
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name
VolatileTexture::addImageTexture(texture, filename);
#endif
// cache the texture
_textures->setObject(texture, filename);
// cache the texture. retain it, since it is added in the map
_textures.insert( std::make_pair(filename, texture) );
texture->retain();
texture->autorelease();
if (target && selector)
@ -280,9 +271,9 @@ void TextureCache::addImageAsyncCallBack(float dt)
target->release();
}
pImage->release();
delete pAsyncStruct;
delete pImageInfo;
image->release();
delete asyncStruct;
delete imageInfo;
--_asyncRefCount;
if (0 == _asyncRefCount)
@ -292,86 +283,68 @@ void TextureCache::addImageAsyncCallBack(float dt)
}
}
Texture2D * TextureCache::addImage(const char * path)
Texture2D * TextureCache::addImage(const std::string &path)
{
CCASSERT(path != NULL, "TextureCache: fileimage MUST not be NULL");
Texture2D * texture = NULL;
Image* pImage = NULL;
Image* image = NULL;
// Split up directory and filename
// MUTEX:
// Needed since addImageAsync calls this method from a different thread
std::string pathKey = path;
pathKey = FileUtils::getInstance()->fullPathForFilename(pathKey.c_str());
if (pathKey.size() == 0)
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str());
if (fullpath.size() == 0)
{
return NULL;
}
texture = static_cast<Texture2D*>(_textures->objectForKey(pathKey.c_str()));
auto it = _textures.find(fullpath);
if( it != _textures.end() )
texture = it->second;
std::string fullpath = pathKey;
if (! texture)
if (! texture)
{
std::string lowerCase(pathKey);
for (unsigned int i = 0; i < lowerCase.length(); ++i)
{
lowerCase[i] = tolower(lowerCase[i]);
}
// all images are handled by UIImage except PVR extension that is handled by our own handler
do
{
pImage = new Image();
CC_BREAK_IF(NULL == pImage);
image = new Image();
CC_BREAK_IF(NULL == image);
bool bRet = pImage->initWithImageFile(fullpath.c_str());
bool bRet = image->initWithImageFile(fullpath.c_str());
CC_BREAK_IF(!bRet);
texture = new Texture2D();
if( texture &&
texture->initWithImage(pImage) )
if( texture && texture->initWithImage(image) )
{
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name
VolatileTexture::addImageTexture(texture, fullpath.c_str());
#endif
_textures->setObject(texture, pathKey.c_str());
texture->release();
// texture already retained, no need to re-retain it
_textures.insert( std::make_pair(fullpath, texture) );
}
else
{
CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path);
CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str());
}
} while (0);
}
CC_SAFE_RELEASE(pImage);
CC_SAFE_RELEASE(image);
return texture;
}
Texture2D* TextureCache::addUIImage(Image *image, const char *key)
Texture2D* TextureCache::addImage(Image *image, const std::string &key)
{
CCASSERT(image != NULL, "TextureCache: image MUST not be nil");
Texture2D * texture = NULL;
// textureForKey() use full path,so the key should be full path
std::string forKey;
if (key)
{
forKey = FileUtils::getInstance()->fullPathForFilename(key);
}
// Don't have to lock here, because addImageAsync() will not
// invoke opengl function in loading thread.
do
do
{
// If key is nil, then create a new texture each time
if(key && (texture = (Texture2D *)_textures->objectForKey(forKey.c_str())))
{
auto it = _textures.find(key);
if( it != _textures.end() ) {
texture = it->second;
break;
}
@ -379,9 +352,11 @@ Texture2D* TextureCache::addUIImage(Image *image, const char *key)
texture = new Texture2D();
texture->initWithImage(image);
if(key && texture)
if(texture)
{
_textures->setObject(texture, forKey.c_str());
_textures.insert( std::make_pair(key, texture) );
texture->retain();
texture->autorelease();
}
else
@ -402,48 +377,25 @@ Texture2D* TextureCache::addUIImage(Image *image, const char *key)
void TextureCache::removeAllTextures()
{
_textures->removeAllObjects();
for( auto it=_textures.begin(); it!=_textures.end(); ++it ) {
(it->second)->release();
}
_textures.clear();
}
void TextureCache::removeUnusedTextures()
{
/*
DictElement* pElement = NULL;
CCDICT_FOREACH(_textures, pElement)
{
CCLOG("cocos2d: TextureCache: texture: %s", pElement->getStrKey());
Texture2D *value = static_cast<Texture2D*>(pElement->getObject());
if (value->retainCount() == 1)
{
CCLOG("cocos2d: TextureCache: removing unused texture: %s", pElement->getStrKey());
_textures->removeObjectForElememt(pElement);
}
}
*/
/** Inter engineer zhuoshi sun finds that this way will get better performance
*/
if (_textures->count())
{
// find elements to be removed
DictElement* pElement = NULL;
list<DictElement*> elementToRemove;
CCDICT_FOREACH(_textures, pElement)
{
CCLOG("cocos2d: TextureCache: texture: %s", pElement->getStrKey());
Texture2D *value = static_cast<Texture2D*>(pElement->getObject());
if (value->retainCount() == 1)
{
elementToRemove.push_back(pElement);
}
}
// remove elements
for (auto iter = elementToRemove.begin(); iter != elementToRemove.end(); ++iter)
{
CCLOG("cocos2d: TextureCache: removing unused texture: %s", (*iter)->getStrKey());
_textures->removeObjectForElememt(*iter);
for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */) {
Texture2D *tex = it->second;
if( tex->retainCount() == 1 ) {
CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str());
tex->release();
_textures.erase(it++);
} else {
++it;
}
}
}
@ -454,24 +406,31 @@ void TextureCache::removeTexture(Texture2D* texture)
return;
}
Array* keys = _textures->allKeysForObject(texture);
_textures->removeObjectsForKeys(keys);
}
void TextureCache::removeTextureForKey(const char *textureKeyName)
{
if (textureKeyName == NULL)
{
return;
for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */ ) {
if( it->second == texture ) {
texture->release();
_textures.erase(it++);
break;
} else
++it;
}
string fullPath = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
_textures->removeObjectForKey(fullPath);
}
Texture2D* TextureCache::textureForKey(const char* key)
void TextureCache::removeTextureForKey(const std::string &textureKeyName)
{
return static_cast<Texture2D*>(_textures->objectForKey(FileUtils::getInstance()->fullPathForFilename(key)));
auto it = _textures.find(textureKeyName);
if( it != _textures.end() ) {
(it->second)->release();
_textures.erase(it);
}
}
Texture2D* TextureCache::getTextureForKey(const std::string &key) const
{
auto it = _textures.find(key);
if( it != _textures.end() )
return it->second;
return NULL;
}
void TextureCache::reloadAllTextures()
@ -481,22 +440,21 @@ void TextureCache::reloadAllTextures()
#endif
}
void TextureCache::dumpCachedTextureInfo()
void TextureCache::dumpCachedTextureInfo() const
{
unsigned int count = 0;
unsigned int totalBytes = 0;
DictElement* pElement = NULL;
CCDICT_FOREACH(_textures, pElement)
{
Texture2D* tex = static_cast<Texture2D*>(pElement->getObject());
for( auto it = _textures.begin(); it != _textures.end(); ++it ) {
Texture2D* tex = it->second;
unsigned int bpp = tex->getBitsPerPixelForFormat();
// Each texture takes up width * height * bytesPerPixel bytes.
unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
totalBytes += bytes;
count++;
CCLOG("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB",
pElement->getStrKey(),
log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB",
it->first.c_str(),
(long)tex->retainCount(),
(long)tex->getName(),
(long)tex->getPixelsWide(),
@ -505,7 +463,7 @@ void TextureCache::dumpCachedTextureInfo()
(long)bytes / 1024);
}
CCLOG("cocos2d: TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
log("cocos2d: TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
}
#if CC_ENABLE_CACHE_TEXTURE_DATA
@ -652,20 +610,20 @@ void VolatileTexture::reloadAllTextures()
{
case kImageFile:
{
Image* pImage = new Image();
Image* image = new Image();
unsigned long nSize = 0;
unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &nSize);
if (pImage && pImage->initWithImageData(pBuffer, nSize))
if (image && image->initWithImageData(pBuffer, nSize))
{
Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat);
vt->_texture->initWithImage(pImage);
vt->_texture->initWithImage(image);
Texture2D::setDefaultAlphaPixelFormat(oldPixelFormat);
}
CC_SAFE_DELETE_ARRAY(pBuffer);
CC_SAFE_RELEASE(pImage);
CC_SAFE_RELEASE(image);
}
break;
case kImageData:

View File

@ -33,9 +33,9 @@ THE SOFTWARE.
#include <condition_variable>
#include <queue>
#include <string>
#include <unordered_map>
#include "cocoa/CCObject.h"
#include "cocoa/CCDictionary.h"
#include "textures/CCTexture2D.h"
#include "platform/CCImage.h"
@ -83,15 +83,15 @@ public:
const char* description(void) const;
Dictionary* snapshotTextures();
// Dictionary* snapshotTextures();
/** Returns a Texture2D object given an file image
* If the file image was not previously loaded, it will create a new Texture2D
/** Returns a Texture2D object given an filename.
* If the filename was not previously loaded, it will create a new Texture2D
* object and it will return it. It will use the filename as a key.
* Otherwise it will return a reference of a previously loaded image.
* Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif
*/
Texture2D* addImage(const char* fileimage);
Texture2D* addImage(const std::string &filepath);
/* Returns a Texture2D object given a file image
* If the file image was not previously loaded, it will create a new Texture2D object and it will return it.
@ -100,20 +100,22 @@ public:
* Supported image extensions: .png, .jpg
* @since v0.8
*/
virtual void addImageAsync(const char *path, Object *target, SEL_CallFuncO selector);
virtual void addImageAsync(const std::string &filepath, Object *target, SEL_CallFuncO selector);
/** Returns a Texture2D object given an UIImage image
/** Returns a Texture2D object given an Image.
* If the image was not previously loaded, it will create a new Texture2D object and it will return it.
* Otherwise it will return a reference of a previously loaded image
* Otherwise it will return a reference of a previously loaded image.
* The "key" parameter will be used as the "key" for the cache.
* If "key" is nil, then a new texture will be created each time.
*/
Texture2D* addUIImage(Image *image, const char *key);
Texture2D* addImage(Image *image, const std::string &key);
CC_DEPRECATED_ATTRIBUTE Texture2D* addUIImage(Image *image, const char *key) { return addImage(image,key); }
/** Returns an already created texture. Returns nil if the texture doesn't exist.
@since v0.99.5
*/
Texture2D* textureForKey(const char* key);
Texture2D* getTextureForKey(const std::string& key) const;
CC_DEPRECATED_ATTRIBUTE Texture2D* textureForKey(const char* key) const { return getTextureForKey(key); }
/** Purges the dictionary of loaded textures.
* Call this method if you receive the "Memory Warning"
@ -137,14 +139,14 @@ public:
/** Deletes a texture from the cache given a its key name
@since v0.99.4
*/
void removeTextureForKey(const char *textureKeyName);
void removeTextureForKey(const std::string &key);
/** Output to CCLOG the current contents of this TextureCache
* This will attempt to calculate the size of each texture, and the total texture memory in use
*
* @since v1.0
*/
void dumpCachedTextureInfo();
void dumpCachedTextureInfo() const;
private:
void addImageAsyncCallBack(float dt);
@ -156,9 +158,9 @@ public:
public:
AsyncStruct(const std::string& fn, Object *t, SEL_CallFuncO s) : filename(fn), target(t), selector(s) {}
std::string filename;
Object *target;
SEL_CallFuncO selector;
std::string filename;
Object *target;
SEL_CallFuncO selector;
};
protected:
@ -183,7 +185,7 @@ protected:
int _asyncRefCount;
Dictionary* _textures;
std::unordered_map<std::string, Texture2D*> _textures;
static TextureCache *_sharedTextureCache;
};

View File

@ -71,9 +71,9 @@ void PrettyPrinterDemo::onEnter()
vistor.clear();
addSprite();
dict = TextureCache::getInstance()->snapshotTextures();
dict->acceptVisitor(vistor);
log("%s", vistor.getResult().c_str());
// dict = TextureCache::getInstance()->snapshotTextures();
// dict->acceptVisitor(vistor);
// log("%s", vistor.getResult().c_str());
}
void DataVisitorTestScene::runThisTest()

View File

@ -280,7 +280,7 @@ void NodeDeallocTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Sprite: %lu\n", sizeof(Node));
printf("Size of Node: %lu\n", sizeof(Node));
scheduleUpdate();
}
@ -333,7 +333,7 @@ void SpriteCreateEmptyTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Node: %lu\n", sizeof(Sprite));
printf("Size of Sprite: %lu\n", sizeof(Sprite));
scheduleUpdate();
}
@ -383,7 +383,7 @@ void SpriteCreateTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Node: %lu\n", sizeof(Sprite));
printf("Size of Sprite: %lu\n", sizeof(Sprite));
scheduleUpdate();
}
@ -406,7 +406,7 @@ void SpriteCreateTest::update(float dt)
std::string SpriteCreateTest::title()
{
return "Create Sprite.";
return "Create Sprite";
}
std::string SpriteCreateTest::subtitle()
@ -433,7 +433,7 @@ void SpriteDeallocTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Node: %lu\n", sizeof(Sprite));
printf("Size of sprite: %lu\n", sizeof(Sprite));
scheduleUpdate();
}

View File

@ -133,12 +133,12 @@ string RenderTextureSave::subtitle()
return "Press 'Save Image' to create an snapshot of the render texture";
}
void RenderTextureSave::clearImage(cocos2d::Object *pSender)
void RenderTextureSave::clearImage(cocos2d::Object *sender)
{
_target->clear(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1());
}
void RenderTextureSave::saveImage(cocos2d::Object *pSender)
void RenderTextureSave::saveImage(cocos2d::Object *sender)
{
static int counter = 0;
@ -151,11 +151,11 @@ void RenderTextureSave::saveImage(cocos2d::Object *pSender)
_target->saveToFile(jpg, Image::Format::JPG);
auto pImage = _target->newImage();
auto image = _target->newImage();
auto tex = TextureCache::getInstance()->addUIImage(pImage, png);
auto tex = TextureCache::getInstance()->addImage(image, png);
CC_SAFE_DELETE(pImage);
CC_SAFE_DELETE(image);
auto sprite = Sprite::createWithTexture(tex);