Merge branch 'develop' of https://github.com/cocos2d/cocos2d-x into Bridge

This commit is contained in:
samuele3hu 2013-09-11 09:50:31 +08:00
commit 7c62509b02
164 changed files with 4011 additions and 2583 deletions

View File

@ -560,6 +560,7 @@ Developers:
Nako Sung (nakosung) Nako Sung (nakosung)
Fixing a bug that wrong logic when pass an empty std::vector to WebSocket::init. Fixing a bug that wrong logic when pass an empty std::vector to WebSocket::init.
Exposing cc.RemoveSelf to JS. Exposing cc.RemoveSelf to JS.
exposed AssetsManager to javascript and added multiple-assetsManager support
dotsquid dotsquid
Fixed the crash caused by improper deletion of VBOs and VAO in ParticleSystemQuad. Fixed the crash caused by improper deletion of VBOs and VAO in ParticleSystemQuad.

View File

@ -1 +1 @@
fd0dee451420604712c1327679395cd1faca91b6 cee239faffacb79c42a315cc01d4bce887435f5b

View File

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

View File

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

View File

@ -41,8 +41,8 @@ static Texture2D* getDefaultTexture()
do do
{ {
bool bRet = false; bool bRet = false;
const char* key = "__firePngData"; const char* key = "/__firePngData";
texture = TextureCache::getInstance()->textureForKey(key); texture = TextureCache::getInstance()->getTextureForKey(key);
CC_BREAK_IF(texture != NULL); CC_BREAK_IF(texture != NULL);
pImage = new Image(); pImage = new Image();
@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture()
bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData)); bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData));
CC_BREAK_IF(!bRet); CC_BREAK_IF(!bRet);
texture = TextureCache::getInstance()->addUIImage(pImage, key); texture = TextureCache::getInstance()->addImage(pImage, key);
} while (0); } while (0);
CC_SAFE_RELEASE(pImage); 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"); CCASSERT(isOK, "CCParticleSystem: error init image with Data");
CC_BREAK_IF(!isOK); CC_BREAK_IF(!isOK);
setTexture(TextureCache::getInstance()->addUIImage(image, textureName.c_str())); setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str()));
image->release(); image->release();
} }

View File

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

View File

@ -57,10 +57,10 @@ public:
static void destroyInstance(); static void destroyInstance();
/** @deprecated Use getInstance() instead */ /** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static FileUtils* sharedFileUtils(); CC_DEPRECATED_ATTRIBUTE static FileUtils* sharedFileUtils() { return getInstance(); }
/** @deprecated Use destroyInstance() instead */ /** @deprecated Use destroyInstance() instead */
CC_DEPRECATED_ATTRIBUTE static void purgeFileUtils(); CC_DEPRECATED_ATTRIBUTE static void purgeFileUtils() { destroyInstance(); }
/** /**
* The destructor of FileUtils. * The destructor of FileUtils.
@ -86,7 +86,7 @@ public:
* @return Upon success, a pointer to the data is returned, otherwise NULL. * @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. * @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. * 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. * @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. * @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. /** Returns the fullpath for a given filename.
@ -144,7 +144,7 @@ public:
@since v2.1 @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. * Loads the filenameLookup dictionary from the contents of a filename.
@ -177,7 +177,7 @@ public:
* *
@since v2.1 @since v2.1
*/ */
virtual void loadFilenameLookupDictionaryFromFile(const char* filename); virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
/** /**
* Sets the filenameLookup dictionary. * Sets the filenameLookup dictionary.
@ -185,7 +185,7 @@ public:
* @param pFilenameLookupDict The dictionary for replacing filename. * @param pFilenameLookupDict The dictionary for replacing filename.
* @since v2.1 * @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. * 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. ) * 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. * Sets the array that contains the search order of the resources.
@ -213,7 +213,7 @@ public:
* @see setSearchResolutionsOrder(), fullPathForFilename(). * @see setSearchResolutionsOrder(), fullPathForFilename().
* @since v2.1 * @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. * Gets the array that contains the search order of the resources.
@ -247,7 +247,7 @@ public:
* *
* @since v2.1 * @since v2.1
*/ */
void addSearchPath(const char* path); void addSearchPath(const std::string & path);
/** /**
* Gets the array of search paths. * Gets the array of search paths.
@ -255,13 +255,13 @@ public:
* @return The array of search paths. * @return The array of search paths.
* @see fullPathForFilename(const char*). * @see fullPathForFilename(const char*).
*/ */
virtual const std::vector<std::string>& getSearchPaths(); virtual const std::vector<std::string>& getSearchPaths() const;
/** /**
* Gets the writable path. * Gets the writable path.
* @return The path that can be write/read a file in * @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. * 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. * @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. * @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. * Checks whether the path is an absolute path.
@ -281,13 +281,13 @@ public:
* @param strPath The path that needs to be checked. * @param strPath The path that needs to be checked.
* @return true if it's an absolute path, otherwise it will return false. * @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. * 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(); virtual bool isPopupNotify();
protected: protected:
@ -308,11 +308,12 @@ protected:
/** /**
* Gets the new filename from the filename lookup dictionary. * Gets the new filename from the filename lookup dictionary.
* It is possible to have a override names.
* @param filename The original filename. * @param filename The original filename.
* @return The new filename after searching in the filename lookup dictionary. * @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. * 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. * Gets full path for filename, resolution directory and search path.
@ -334,7 +335,7 @@ protected:
* @param strFilename The name of the file. * @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. * @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. * Creates a dictionary by the contents of a file.

View File

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

View File

@ -52,9 +52,10 @@ public:
/* override funtions */ /* override funtions */
bool init(); bool init();
virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize); 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 std::string getWritablePath() const;
virtual bool isAbsolutePath(const std::string& strPath); 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(). /** This function is android specific. It is used for TextureCache::addImageAsync().
Don't use it in your codes. 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __CC_FILEUTILS_IOS_H__ #ifndef __CC_FILEUTILS_APPLE_H__
#define __CC_FILEUTILS_IOS_H__ #define __CC_FILEUTILS_APPLE_H__
#include "CCFileUtils.h" #include "CCFileUtils.h"
#include <string> #include <string>
@ -38,19 +38,18 @@ NS_CC_BEGIN
*/ */
//! @brief Helper class to handle file operations //! @brief Helper class to handle file operations
class CC_DLL FileUtilsIOS : public FileUtils class CC_DLL FileUtilsApple : public FileUtils
{ {
public: public:
/* override funtions */ /* override funtions */
virtual std::string getWritablePath(); virtual std::string getWritablePath() const override;
virtual bool isFileExist(const std::string& strFilePath); virtual bool isFileExist(const std::string& strFilePath) const override;
virtual bool isAbsolutePath(const std::string& strPath); virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) override;
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename);
virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename); virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename) override;
virtual bool writeToFile(Dictionary *dict, const std::string& fullPath); 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 // end of platform group
@ -58,5 +57,5 @@ public:
NS_CC_END 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. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <UIKit/UIDevice.h>
#include <string> #include <string>
#include <stack> #include <stack>
@ -34,7 +33,7 @@ THE SOFTWARE.
#include "CCDictionary.h" #include "CCDictionary.h"
#include "support/zip_support/unzip.h" #include "support/zip_support/unzip.h"
#include "CCFileUtilsIOS.h" #include "CCFileUtilsApple.h"
NS_CC_BEGIN 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() FileUtils* FileUtils::getInstance()
{ {
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsIOS(); s_sharedFileUtils = new FileUtilsApple();
if(!s_sharedFileUtils->init()) if(!s_sharedFileUtils->init())
{ {
delete s_sharedFileUtils; delete s_sharedFileUtils;
s_sharedFileUtils = NULL; s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsIOS"); CCLOG("ERROR: Could not init CCFileUtilsApple");
} }
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }
static NSFileManager* s_fileManager = [NSFileManager defaultManager]; std::string FileUtilsApple::getWritablePath() const
std::string FileUtilsIOS::getWritablePath()
{ {
// save to document folder // save to document folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
@ -238,9 +240,9 @@ std::string FileUtilsIOS::getWritablePath()
return strRet; 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; return false;
} }
@ -280,7 +282,7 @@ bool FileUtilsIOS::isFileExist(const std::string& strFilePath)
return bRet; 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] != '/') if (strDirectory[0] != '/')
{ {
@ -302,15 +304,9 @@ std::string FileUtilsIOS::getFullPathForDirectoryAndFilename(const std::string&
return ""; return "";
} }
bool FileUtilsIOS::isAbsolutePath(const std::string& strPath) Dictionary* FileUtilsApple::createDictionaryWithContentsOfFile(const std::string& filename)
{ {
NSString* path = [NSString stringWithUTF8String:strPath.c_str()]; std::string fullPath = fullPathForFilename(filename);
return [path isAbsolutePath] ? true : false;
}
Dictionary* FileUtilsIOS::createDictionaryWithContentsOfFile(const std::string& filename)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()];
NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath]; 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()); //CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
NSMutableDictionary *nsDict = [NSMutableDictionary dictionary]; NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
@ -348,14 +344,14 @@ bool FileUtilsIOS::writeToFile(Dictionary *dict, const std::string &fullPath)
return true; return true;
} }
Array* FileUtilsIOS::createArrayWithContentsOfFile(const std::string& filename) Array* FileUtilsApple::createArrayWithContentsOfFile(const std::string& filename)
{ {
// NSString* pPath = [NSString stringWithUTF8String:pFileName]; // NSString* pPath = [NSString stringWithUTF8String:pFileName];
// NSString* pathExtension= [pPath pathExtension]; // NSString* pathExtension= [pPath pathExtension];
// pPath = [pPath stringByDeletingPathExtension]; // pPath = [pPath stringByDeletingPathExtension];
// pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension]; // pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension];
// fixing cannot read data using Array::createWithContentsOfFile // 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()]; NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
NSArray* array = [NSArray arrayWithContentsOfFile:path]; 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
//#import <UIKit/UIKit.h>
#include "CCThread.h" #include "CCThread.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -27,6 +27,9 @@ THE SOFTWARE.
#ifndef __CCSHADERCACHE_H__ #ifndef __CCSHADERCACHE_H__
#define __CCSHADERCACHE_H__ #define __CCSHADERCACHE_H__
#include <string>
#include <unordered_map>
#include "cocoa/CCDictionary.h" #include "cocoa/CCDictionary.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -68,17 +71,17 @@ public:
void reloadDefaultShaders(); void reloadDefaultShaders();
/** returns a GL program for a given key */ /** 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 */ /** 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: private:
bool init(); bool init();
void loadDefaultShader(GLProgram *program, int type); void loadDefaultShader(GLProgram *program, int type);
Dictionary* _programs; // Dictionary* _programs;
std::unordered_map<std::string, GLProgram*> _programs;
}; };
// end of shaders group // end of shaders group

View File

@ -1089,7 +1089,7 @@ static unsigned char cc_2x2_white_image[] = {
0xFF, 0xFF, 0xFF, 0xFF 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) 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); 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."); 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); CC_SAFE_RELEASE(image);
} }
} }

View File

@ -77,6 +77,11 @@ const char* Component::getName() const
return _name.c_str(); return _name.c_str();
} }
void Component::setName(const char *pName)
{
_name.assign(pName);
}
Node* Component::getOwner() const Node* Component::getOwner() const
{ {
return _owner; return _owner;

View File

@ -46,6 +46,7 @@ public:
static Component* create(void); static Component* create(void);
const char* getName() const; const char* getName() const;
void setName(const char *pName);
void setOwner(Node *pOwner); void setOwner(Node *pOwner);
Node* getOwner() const; Node* getOwner() const;

View File

@ -119,22 +119,22 @@ public:
struct PixelFormatInfo { 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 internalFormat;
GLenum format; GLenum format;
GLenum type; GLenum type;
int bpp; int bpp;
bool compressed; bool compressed;
bool alpha; 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; typedef std::map<Texture2D::PixelFormat, const PixelFormatInfo> PixelFormatInfoMap;

View File

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

View File

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

View File

@ -8,32 +8,6 @@ LOCAL_MODULE_FILENAME := libextension
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
CCDeprecated-ext.cpp \ CCDeprecated-ext.cpp \
AssetsManager/AssetsManager.cpp \ AssetsManager/AssetsManager.cpp \
CCArmature/CCArmature.cpp \
CCArmature/CCBone.cpp \
CCArmature/animation/CCArmatureAnimation.cpp \
CCArmature/animation/CCProcessBase.cpp \
CCArmature/animation/CCTween.cpp \
CCArmature/datas/CCDatas.cpp \
CCArmature/display/CCBatchNode.cpp \
CCArmature/display/CCDecorativeDisplay.cpp \
CCArmature/display/CCDisplayFactory.cpp \
CCArmature/display/CCDisplayManager.cpp \
CCArmature/display/CCShaderNode.cpp \
CCArmature/display/CCSkin.cpp \
CCArmature/external_tool/CCTexture2DMutable.cpp \
CCArmature/external_tool/GLES-Render.cpp \
CCArmature/external_tool/Json/CSContentJsonDictionary.cpp \
CCArmature/external_tool/Json/lib_json/json_reader.cpp \
CCArmature/external_tool/Json/lib_json/json_value.cpp \
CCArmature/external_tool/Json/lib_json/json_writer.cpp \
CCArmature/physics/CCColliderDetector.cpp \
CCArmature/physics/CCPhysicsWorld.cpp \
CCArmature/utils/CCArmatureDataManager.cpp \
CCArmature/utils/CCDataReaderHelper.cpp \
CCArmature/utils/CCSpriteFrameCacheHelper.cpp \
CCArmature/utils/CCTransformHelp.cpp \
CCArmature/utils/CCTweenFunction.cpp \
CCArmature/utils/CCUtilMath.cpp \
CCBReader/CCBAnimationManager.cpp \ CCBReader/CCBAnimationManager.cpp \
CCBReader/CCBFileLoader.cpp \ CCBReader/CCBFileLoader.cpp \
CCBReader/CCBKeyframe.cpp \ CCBReader/CCBKeyframe.cpp \
@ -57,10 +31,6 @@ CCBReader/CCParticleSystemQuadLoader.cpp \
CCBReader/CCScale9SpriteLoader.cpp \ CCBReader/CCScale9SpriteLoader.cpp \
CCBReader/CCScrollViewLoader.cpp \ CCBReader/CCScrollViewLoader.cpp \
CCBReader/CCSpriteLoader.cpp \ CCBReader/CCSpriteLoader.cpp \
Components/CCComAttribute.cpp \
Components/CCComAudio.cpp \
Components/CCComController.cpp \
Components/CCInputDelegate.cpp \
GUI/CCControlExtension/CCControl.cpp \ GUI/CCControlExtension/CCControl.cpp \
GUI/CCControlExtension/CCControlButton.cpp \ GUI/CCControlExtension/CCControlButton.cpp \
GUI/CCControlExtension/CCControlColourPicker.cpp \ GUI/CCControlExtension/CCControlColourPicker.cpp \
@ -89,6 +59,39 @@ network/SocketIO.cpp \
network/WebSocket.cpp \ network/WebSocket.cpp \
physics_nodes/CCPhysicsDebugNode.cpp \ physics_nodes/CCPhysicsDebugNode.cpp \
physics_nodes/CCPhysicsSprite.cpp \ physics_nodes/CCPhysicsSprite.cpp \
CocoStudio/Armature/CCArmature.cpp \
CocoStudio/Armature/CCBone.cpp \
CocoStudio/Armature/animation/CCArmatureAnimation.cpp \
CocoStudio/Armature/animation/CCProcessBase.cpp \
CocoStudio/Armature/animation/CCTween.cpp \
CocoStudio/Armature/datas/CCDatas.cpp \
CocoStudio/Armature/display/CCBatchNode.cpp \
CocoStudio/Armature/display/CCDecorativeDisplay.cpp \
CocoStudio/Armature/display/CCDisplayFactory.cpp \
CocoStudio/Armature/display/CCDisplayManager.cpp \
CocoStudio/Armature/display/CCShaderNode.cpp \
CocoStudio/Armature/display/CCSkin.cpp \
CocoStudio/Armature/external_tool/CCTexture2DMutable.cpp \
CocoStudio/Armature/external_tool/GLES-Render.cpp \
CocoStudio/Armature/physics/CCColliderDetector.cpp \
CocoStudio/Armature/physics/CCPhysicsWorld.cpp \
CocoStudio/Armature/utils/CCArmatureDataManager.cpp \
CocoStudio/Armature/utils/CCDataReaderHelper.cpp \
CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.cpp \
CocoStudio/Armature/utils/CCTransformHelp.cpp \
CocoStudio/Armature/utils/CCTweenFunction.cpp \
CocoStudio/Armature/utils/CCUtilMath.cpp \
CocoStudio/Components/CCComAttribute.cpp \
CocoStudio/Components/CCComAudio.cpp \
CocoStudio/Components/CCComController.cpp \
CocoStudio/Components/CCComRender.cpp \
CocoStudio/Components/CCInputDelegate.cpp \
CocoStudio/Json/CSContentJsonDictionary.cpp \
CocoStudio/Json/DictionaryHelper.cpp \
CocoStudio/Json/lib_json/json_value.cpp \
CocoStudio/Json/lib_json/json_reader.cpp \
CocoStudio/Json/lib_json/json_writer.cpp \
CocoStudio/Reader/CCSSceneReader.cpp \
spine/Animation.cpp \ spine/Animation.cpp \
spine/AnimationState.cpp \ spine/AnimationState.cpp \
spine/AnimationStateData.cpp \ spine/AnimationStateData.cpp \

View File

@ -34,8 +34,10 @@
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <errno.h> #include <errno.h>
#include <dirent.h>
#endif #endif
#include "support/zip_support/unzip.h" #include "support/zip_support/unzip.h"
using namespace cocos2d; using namespace cocos2d;
@ -81,6 +83,7 @@ AssetsManager::AssetsManager(const char* packageUrl/* =NULL */, const char* vers
, _connectionTimeout(0) , _connectionTimeout(0)
, _delegate(NULL) , _delegate(NULL)
, _isDownloading(false) , _isDownloading(false)
, _shouldDeleteDelegateWhenExit(false)
{ {
checkStoragePath(); checkStoragePath();
_schedule = new Helper(); _schedule = new Helper();
@ -92,6 +95,10 @@ AssetsManager::~AssetsManager()
{ {
_schedule->release(); _schedule->release();
} }
if (_shouldDeleteDelegateWhenExit)
{
delete _delegate;
}
} }
void AssetsManager::checkStoragePath() void AssetsManager::checkStoragePath()
@ -102,6 +109,26 @@ void AssetsManager::checkStoragePath()
} }
} }
// Multiple key names
static std::string keyWithHash( const char* prefix, const std::string& url )
{
char buf[256];
sprintf(buf,"%s%zd",prefix,std::hash<std::string>()(url));
return buf;
}
// hashed version
std::string AssetsManager::keyOfVersion() const
{
return keyWithHash(KEY_OF_VERSION,_packageUrl);
}
// hashed version
std::string AssetsManager::keyOfDownloadedVersion() const
{
return keyWithHash(KEY_OF_DOWNLOADED_VERSION,_packageUrl);
}
static size_t getVersionCode(void *ptr, size_t size, size_t nmemb, void *userdata) static size_t getVersionCode(void *ptr, size_t size, size_t nmemb, void *userdata)
{ {
string *version = (string*)userdata; string *version = (string*)userdata;
@ -140,7 +167,7 @@ bool AssetsManager::checkUpdate()
return false; return false;
} }
string recordedVersion = UserDefault::getInstance()->getStringForKey(KEY_OF_VERSION); string recordedVersion = UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str());
if (recordedVersion == _version) if (recordedVersion == _version)
{ {
sendErrorMessage(ErrorCode::NO_NEW_VERSION); sendErrorMessage(ErrorCode::NO_NEW_VERSION);
@ -212,7 +239,7 @@ void AssetsManager::update()
} }
// Is package already downloaded? // Is package already downloaded?
_downloadedVersion = UserDefault::getInstance()->getStringForKey(KEY_OF_DOWNLOADED_VERSION); _downloadedVersion = UserDefault::getInstance()->getStringForKey(keyOfDownloadedVersion().c_str());
auto t = std::thread(&AssetsManager::downloadAndUncompress, this); auto t = std::thread(&AssetsManager::downloadAndUncompress, this);
t.detach(); t.detach();
@ -469,12 +496,12 @@ void AssetsManager::setVersionFileUrl(const char *versionFileUrl)
string AssetsManager::getVersion() string AssetsManager::getVersion()
{ {
return UserDefault::getInstance()->getStringForKey(KEY_OF_VERSION); return UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str());
} }
void AssetsManager::deleteVersion() void AssetsManager::deleteVersion()
{ {
UserDefault::getInstance()->setStringForKey(KEY_OF_VERSION, ""); UserDefault::getInstance()->setStringForKey(keyOfVersion().c_str(), "");
} }
void AssetsManager::setDelegate(AssetsManagerDelegateProtocol *delegate) void AssetsManager::setDelegate(AssetsManagerDelegateProtocol *delegate)
@ -549,7 +576,7 @@ void AssetsManager::Helper::update(float dt)
break; break;
case ASSETSMANAGER_MESSAGE_RECORD_DOWNLOADED_VERSION: case ASSETSMANAGER_MESSAGE_RECORD_DOWNLOADED_VERSION:
UserDefault::getInstance()->setStringForKey(KEY_OF_DOWNLOADED_VERSION, UserDefault::getInstance()->setStringForKey(((AssetsManager*)msg->obj)->keyOfDownloadedVersion().c_str(),
((AssetsManager*)msg->obj)->_version.c_str()); ((AssetsManager*)msg->obj)->_version.c_str());
UserDefault::getInstance()->flush(); UserDefault::getInstance()->flush();
@ -585,10 +612,10 @@ void AssetsManager::Helper::handleUpdateSucceed(Message *msg)
AssetsManager* manager = (AssetsManager*)msg->obj; AssetsManager* manager = (AssetsManager*)msg->obj;
// Record new version code. // Record new version code.
UserDefault::getInstance()->setStringForKey(KEY_OF_VERSION, manager->_version.c_str()); UserDefault::getInstance()->setStringForKey(manager->keyOfVersion().c_str(), manager->_version.c_str());
// Unrecord downloaded version code. // Unrecord downloaded version code.
UserDefault::getInstance()->setStringForKey(KEY_OF_DOWNLOADED_VERSION, ""); UserDefault::getInstance()->setStringForKey(manager->keyOfDownloadedVersion().c_str(), "");
UserDefault::getInstance()->flush(); UserDefault::getInstance()->flush();
// Set resource search path. // Set resource search path.
@ -604,4 +631,69 @@ void AssetsManager::Helper::handleUpdateSucceed(Message *msg)
if (manager) manager->_delegate->onSuccess(); if (manager) manager->_delegate->onSuccess();
} }
AssetsManager* AssetsManager::create(const char* packageUrl, const char* versionFileUrl, const char* storagePath, ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback )
{
class DelegateProtocolImpl : public AssetsManagerDelegateProtocol
{
public :
DelegateProtocolImpl(ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback)
: errorCallback(errorCallback), progressCallback(progressCallback), successCallback(successCallback)
{}
virtual void onError(AssetsManager::ErrorCode errorCode) { errorCallback(int(errorCode)); }
virtual void onProgress(int percent) { progressCallback(percent); }
virtual void onSuccess() { successCallback(); }
private :
ErrorCallback errorCallback;
ProgressCallback progressCallback;
SuccessCallback successCallback;
};
auto* manager = new AssetsManager(packageUrl,versionFileUrl,storagePath);
auto* delegate = new DelegateProtocolImpl(errorCallback,progressCallback,successCallback);
manager->setDelegate(delegate);
manager->_shouldDeleteDelegateWhenExit = true;
manager->autorelease();
return manager;
}
void AssetsManager::createStoragePath()
{
// Remove downloaded files
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
DIR *dir = NULL;
dir = opendir (_storagePath.c_str());
if (!dir)
{
mkdir(_storagePath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
}
#else
if ((GetFileAttributesA(_storagePath.c_str())) == INVALID_FILE_ATTRIBUTES)
{
CreateDirectoryA(_storagePath.c_str(), 0);
}
#endif
}
void AssetsManager::destroyStoragePath()
{
// Delete recorded version codes.
deleteVersion();
// Remove downloaded files
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
string command = "rm -r ";
// Path may include space.
command += "\"" + _storagePath + "\"";
system(command.c_str());
#else
string command = "rd /s /q ";
// Path may include space.
command += "\"" + _storagePath + "\"";
system(command.c_str());
#endif
}
NS_CC_EXT_END; NS_CC_EXT_END;

View File

@ -26,7 +26,7 @@
#define __AssetsManager__ #define __AssetsManager__
#include <string> #include <string>
#include <curl/curl.h>
#include <mutex> #include <mutex>
#include "cocos2d.h" #include "cocos2d.h"
@ -41,7 +41,7 @@ class AssetsManagerDelegateProtocol;
* The updated package should be a zip file. And there should be a file named * The updated package should be a zip file. And there should be a file named
* version in the server, which contains version code. * version in the server, which contains version code.
*/ */
class AssetsManager class AssetsManager : public Node
{ {
public: public:
enum class ErrorCode enum class ErrorCode
@ -77,6 +77,14 @@ public:
virtual ~AssetsManager(); virtual ~AssetsManager();
typedef std::function<void(int)> ErrorCallback;
typedef std::function<void(int)> ProgressCallback;
typedef std::function<void(void)> SuccessCallback;
/* @brief To access within scripting environment
*/
static AssetsManager* create(const char* packageUrl, const char* versionFileUrl, const char* storagePath, ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback );
/* @brief Check out if there is a new version resource. /* @brief Check out if there is a new version resource.
* You may use this method before updating, then let user determine whether * You may use this method before updating, then let user determine whether
* he wants to update resources. * he wants to update resources.
@ -138,7 +146,7 @@ public:
/* downloadAndUncompress is the entry of a new thread /* downloadAndUncompress is the entry of a new thread
*/ */
friend int assetsManagerProgressFunc(void *, double, double, double, double); friend int assetsManagerProgressFunc(void *, double, double, double, double);
protected: protected:
bool downLoad(); bool downLoad();
void checkStoragePath(); void checkStoragePath();
@ -172,6 +180,15 @@ private:
std::list<Message*> *_messageQueue; std::list<Message*> *_messageQueue;
std::mutex _messageQueueMutex; std::mutex _messageQueueMutex;
}; };
private:
/** @brief Initializes storage path.
*/
void createStoragePath();
/** @brief Destroys storage path.
*/
void destroyStoragePath();
private: private:
//! The path to store downloaded resources. //! The path to store downloaded resources.
@ -185,13 +202,18 @@ private:
std::string _downloadedVersion; std::string _downloadedVersion;
CURL *_curl; void *_curl;
Helper *_schedule; Helper *_schedule;
unsigned int _connectionTimeout; unsigned int _connectionTimeout;
AssetsManagerDelegateProtocol *_delegate; // weak reference AssetsManagerDelegateProtocol *_delegate;
bool _isDownloading; bool _isDownloading;
bool _shouldDeleteDelegateWhenExit;
std::string keyOfVersion() const;
std::string keyOfDownloadedVersion() const;
}; };
class AssetsManagerDelegateProtocol class AssetsManagerDelegateProtocol

View File

@ -1,375 +0,0 @@
/*
* Copyright (c) 2012 Chukong Technologies, Inc.
*
* http://www.cocostudio.com
* http://tools.cocoachina.com
*
* 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 <iostream>
#include "CSContentJsonDictionary.h"
namespace cs {
CSJsonDictionary::CSJsonDictionary()
{
_value.clear();
}
CSJsonDictionary::~CSJsonDictionary()
{
_value.clear();
}
void CSJsonDictionary::initWithDescription(const char *pszDescription)
{
CSJson::Reader cReader;
_value.clear();
if (pszDescription && *pszDescription)
{
std::string strValue = pszDescription;
cReader.parse(strValue, _value, false);
}
}
void CSJsonDictionary::initWithValue(CSJson::Value& value)
{
_value = value;
}
void CSJsonDictionary::insertItem(const char *pszKey, int nValue)
{
_value[pszKey] = nValue;
}
void CSJsonDictionary::insertItem(const char *pszKey, double fValue)
{
_value[pszKey] = fValue;
}
void CSJsonDictionary::insertItem(const char *pszKey, const char * pszValue)
{
_value[pszKey] = pszValue;
}
void CSJsonDictionary::insertItem(const char *pszKey, bool bValue)
{
_value[pszKey] = bValue;
}
void CSJsonDictionary::insertItem(const char *pszKey, CSJsonDictionary * subDictionary)
{
if (subDictionary)
_value[pszKey] = subDictionary->_value;
}
bool CSJsonDictionary::deleteItem(const char *pszKey)
{
if(!_value.isMember(pszKey))
return false;
_value.removeMember(pszKey);
return true;
}
void CSJsonDictionary::cleanUp()
{
_value.clear();
}
bool CSJsonDictionary::isKeyValidate(const char *pszKey)
{
return _value.isMember(pszKey);
}
int CSJsonDictionary::getItemIntValue(const char *pszKey, int nDefaultValue)
{
if (!isKeyValidate(pszKey, _value) || !_value[pszKey].isNumeric())
return nDefaultValue;
return _value[pszKey].asInt();
}
double CSJsonDictionary::getItemFloatValue(const char *pszKey, double fDefaultValue)
{
if (!isKeyValidate(pszKey, _value) || !_value[pszKey].isNumeric())
return fDefaultValue;
return _value[pszKey].asDouble();
}
const char * CSJsonDictionary::getItemStringValue(const char *pszKey)
{
if (!isKeyValidate(pszKey, _value) || !_value[pszKey].isString())
return NULL;
return _value[pszKey].asCString();
}
bool CSJsonDictionary::getItemBoolvalue(const char *pszKey, bool bDefaultValue)
{
if (!isKeyValidate(pszKey, _value) || !_value[pszKey].isBool())
return bDefaultValue;
return _value[pszKey].asBool();
}
CSJsonDictionary * CSJsonDictionary::getSubDictionary(const char *pszKey)
{
CSJsonDictionary * pNewDictionary;
if (!isKeyValidate(pszKey, _value) || (!_value[pszKey].isArray() &&
!_value[pszKey].isObject() &&
!_value[pszKey].isConvertibleTo(CSJson::arrayValue) &&
!_value[pszKey].isConvertibleTo(CSJson::objectValue)))
{
pNewDictionary = NULL;
}
else
{
pNewDictionary = new CSJsonDictionary();
pNewDictionary->initWithValue(_value[pszKey]);
}
return pNewDictionary;
}
std::string CSJsonDictionary::getDescription()
{
std::string strReturn = _value.toStyledString();
return strReturn;
}
bool CSJsonDictionary::insertItemToArray(const char *pszArrayKey, int nValue)
{
CSJson::Value array;
if(_value.isMember(pszArrayKey))
{
if (!_value[pszArrayKey].isArray() && !_value[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = _value[pszArrayKey];
}
array.append(nValue);
_value[pszArrayKey] = array;
return true;
}
bool CSJsonDictionary::insertItemToArray(const char *pszArrayKey, double fValue)
{
CSJson::Value array;
if(_value.isMember(pszArrayKey))
{
if (!_value[pszArrayKey].isArray() && !_value[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = _value[pszArrayKey];
}
array.append(fValue);
_value[pszArrayKey] = array;
return true;
}
bool CSJsonDictionary::insertItemToArray(const char *pszArrayKey, const char * pszValue)
{
CSJson::Value array;
if(_value.isMember(pszArrayKey))
{
if (!_value[pszArrayKey].isArray() && !_value[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = _value[pszArrayKey];
}
array.append(pszValue);
_value[pszArrayKey] = array;
return true;
}
bool CSJsonDictionary::insertItemToArray(const char *pszArrayKey, CSJsonDictionary * subDictionary)
{
CSJson::Value array;
if(_value.isMember(pszArrayKey))
{
if (!_value[pszArrayKey].isArray() && !_value[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = _value[pszArrayKey];
}
array.append(subDictionary->_value);
_value[pszArrayKey] = array;
return true;
}
int CSJsonDictionary::getItemCount()
{
return _value.size();
}
DicItemType CSJsonDictionary::getItemType(int nIndex)
{
return (DicItemType)_value[nIndex].type();
}
DicItemType CSJsonDictionary::getItemType(const char *pszKey)
{
return (DicItemType)_value[pszKey].type();
}
std::vector<std::string> CSJsonDictionary::getAllMemberNames()
{
return _value.getMemberNames();
}
int CSJsonDictionary::getArrayItemCount(const char *pszArrayKey)
{
int nRet = 0;
if (!isKeyValidate(pszArrayKey, _value) ||
(!_value[pszArrayKey].isArray() && !_value[pszArrayKey].isObject() &&
!_value[pszArrayKey].isConvertibleTo(CSJson::arrayValue) && !_value[pszArrayKey].isConvertibleTo(CSJson::objectValue)))
{
nRet = 0;
}
else
{
CSJson::Value arrayValue = _value[pszArrayKey];
nRet = arrayValue.size();
}
return nRet;
}
int CSJsonDictionary::getIntValueFromArray(const char *pszArrayKey, int nIndex, int nDefaultValue)
{
int nRet = nDefaultValue;
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isNumeric())
nRet = (*arrayValue)[nIndex].asInt();
}
return nRet;
}
double CSJsonDictionary::getFloatValueFromArray(const char *pszArrayKey, int nIndex, double fDefaultValue)
{
double fRet = fDefaultValue;
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isNumeric())
fRet = (*arrayValue)[nIndex].asDouble();
}
return fRet;
}
const char * CSJsonDictionary::getStringValueFromArray(const char *pszArrayKey, int nIndex)
{
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isString())
return (*arrayValue)[nIndex].asCString();
}
return NULL;
}
CSJsonDictionary * CSJsonDictionary::getSubItemFromArray(const char *pszArrayKey, int nIndex)
{
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isArray() || (*arrayValue)[nIndex].isObject())
{
CSJsonDictionary * pNewDictionary = new CSJsonDictionary();
pNewDictionary->initWithValue((*arrayValue)[nIndex]);
return pNewDictionary;
}
}
return NULL;
}
DicItemType CSJsonDictionary::getItemTypeFromArray(const char *pszArrayKey, int nIndex)
{
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
return (DicItemType)((*arrayValue)[nIndex].type());
return (DicItemType)CSJson::nullValue;
}
inline bool CSJsonDictionary::isKeyValidate(const char *pszKey, CSJson::Value& root)
{
if (root.isNull() || !root.isMember(pszKey))
return false;
return true;
}
inline CSJson::Value * CSJsonDictionary::validateArrayItem(const char *pszArrayKey, int nIndex)
{
if (!isKeyValidate(pszArrayKey, _value) && !_value[pszArrayKey].isArray() && !_value[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return NULL;
if (!_value[pszArrayKey].isValidIndex(nIndex))
return NULL;
return &_value[pszArrayKey];
}
}

View File

@ -23,7 +23,7 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCDatas.h" #include "CCDatas.h"
#include "CCArmature/utils/CCUtilMath.h" #include "../utils/CCUtilMath.h"
namespace cocos2d { namespace extension { namespace armature { namespace cocos2d { namespace extension { namespace armature {

View File

@ -807,14 +807,14 @@ void DataReaderHelper::addDataFromJson(const char *filePath)
void DataReaderHelper::addDataFromJsonCache(const char *fileContent) void DataReaderHelper::addDataFromJsonCache(const char *fileContent)
{ {
cs::CSJsonDictionary json; cs::JsonDictionary json;
json.initWithDescription(fileContent); json.initWithDescription(fileContent);
// Decode armatures // Decode armatures
int length = json.getArrayItemCount(ARMATURE_DATA); int length = json.getArrayItemCount(ARMATURE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); cs::JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i);
ArmatureData *armatureData = decodeArmature(*armatureDic); ArmatureData *armatureData = decodeArmature(*armatureDic);
ArmatureDataManager::sharedArmatureDataManager()->addArmatureData(armatureData->name.c_str(), armatureData); ArmatureDataManager::sharedArmatureDataManager()->addArmatureData(armatureData->name.c_str(), armatureData);
@ -825,7 +825,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent)
length = json.getArrayItemCount(ANIMATION_DATA); length = json.getArrayItemCount(ANIMATION_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); cs::JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i);
AnimationData *animationData = decodeAnimation(*animationDic); AnimationData *animationData = decodeAnimation(*animationDic);
ArmatureDataManager::sharedArmatureDataManager()->addAnimationData(animationData->name.c_str(), animationData); ArmatureDataManager::sharedArmatureDataManager()->addAnimationData(animationData->name.c_str(), animationData);
@ -836,7 +836,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent)
length = json.getArrayItemCount(TEXTURE_DATA); length = json.getArrayItemCount(TEXTURE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); cs::JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i);
TextureData *textureData = decodeTexture(*textureDic); TextureData *textureData = decodeTexture(*textureDic);
ArmatureDataManager::sharedArmatureDataManager()->addTextureData(textureData->name.c_str(), textureData); ArmatureDataManager::sharedArmatureDataManager()->addTextureData(textureData->name.c_str(), textureData);
@ -844,7 +844,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent)
} }
} }
ArmatureData *DataReaderHelper::decodeArmature(cs::CSJsonDictionary &json) ArmatureData *DataReaderHelper::decodeArmature(cs::JsonDictionary &json)
{ {
ArmatureData *armatureData = ArmatureData::create(); ArmatureData *armatureData = ArmatureData::create();
@ -857,7 +857,7 @@ ArmatureData *DataReaderHelper::decodeArmature(cs::CSJsonDictionary &json)
int length = json.getArrayItemCount(BONE_DATA); int length = json.getArrayItemCount(BONE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); cs::JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i);
armatureData->addBoneData(decodeBone(*dic)); armatureData->addBoneData(decodeBone(*dic));
delete dic; delete dic;
@ -866,7 +866,7 @@ ArmatureData *DataReaderHelper::decodeArmature(cs::CSJsonDictionary &json)
return armatureData; return armatureData;
} }
BoneData *DataReaderHelper::decodeBone(cs::CSJsonDictionary &json) BoneData *DataReaderHelper::decodeBone(cs::JsonDictionary &json)
{ {
BoneData *boneData = BoneData::create(); BoneData *boneData = BoneData::create();
@ -888,7 +888,7 @@ BoneData *DataReaderHelper::decodeBone(cs::CSJsonDictionary &json)
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); cs::JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i);
boneData->addDisplayData(decodeBoneDisplay(*dic)); boneData->addDisplayData(decodeBoneDisplay(*dic));
delete dic; delete dic;
@ -897,7 +897,7 @@ BoneData *DataReaderHelper::decodeBone(cs::CSJsonDictionary &json)
return boneData; return boneData;
} }
DisplayData *DataReaderHelper::decodeBoneDisplay(cs::CSJsonDictionary &json) DisplayData *DataReaderHelper::decodeBoneDisplay(cs::JsonDictionary &json)
{ {
DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE);
@ -963,7 +963,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(cs::CSJsonDictionary &json)
return displayData; return displayData;
} }
AnimationData *DataReaderHelper::decodeAnimation(cs::CSJsonDictionary &json) AnimationData *DataReaderHelper::decodeAnimation(cs::JsonDictionary &json)
{ {
AnimationData *aniData = AnimationData::create(); AnimationData *aniData = AnimationData::create();
@ -977,7 +977,7 @@ AnimationData *DataReaderHelper::decodeAnimation(cs::CSJsonDictionary &json)
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i);
aniData->addMovement(decodeMovement(*dic)); aniData->addMovement(decodeMovement(*dic));
delete dic; delete dic;
@ -986,7 +986,7 @@ AnimationData *DataReaderHelper::decodeAnimation(cs::CSJsonDictionary &json)
return aniData; return aniData;
} }
MovementData *DataReaderHelper::decodeMovement(cs::CSJsonDictionary &json) MovementData *DataReaderHelper::decodeMovement(cs::JsonDictionary &json)
{ {
MovementData *movementData = MovementData::create(); MovementData *movementData = MovementData::create();
@ -1005,7 +1005,7 @@ MovementData *DataReaderHelper::decodeMovement(cs::CSJsonDictionary &json)
int length = json.getArrayItemCount(MOVEMENT_BONE_DATA); int length = json.getArrayItemCount(MOVEMENT_BONE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i);
movementData->addMovementBoneData(decodeMovementBone(*dic)); movementData->addMovementBoneData(decodeMovementBone(*dic));
delete dic; delete dic;
@ -1014,7 +1014,7 @@ MovementData *DataReaderHelper::decodeMovement(cs::CSJsonDictionary &json)
return movementData; return movementData;
} }
MovementBoneData *DataReaderHelper::decodeMovementBone(cs::CSJsonDictionary &json) MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json)
{ {
MovementBoneData *movementBoneData = MovementBoneData::create(); MovementBoneData *movementBoneData = MovementBoneData::create();
@ -1030,7 +1030,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(cs::CSJsonDictionary &jso
int length = json.getArrayItemCount(FRAME_DATA); int length = json.getArrayItemCount(FRAME_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); cs::JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i);
FrameData *frameData = decodeFrame(*dic); FrameData *frameData = decodeFrame(*dic);
movementBoneData->addFrameData(frameData); movementBoneData->addFrameData(frameData);
//movementBoneData->duration += frameData->duration; //movementBoneData->duration += frameData->duration;
@ -1041,7 +1041,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(cs::CSJsonDictionary &jso
return movementBoneData; return movementBoneData;
} }
FrameData *DataReaderHelper::decodeFrame(cs::CSJsonDictionary &json) FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json)
{ {
FrameData *frameData = FrameData::create(); FrameData *frameData = FrameData::create();
@ -1060,7 +1060,7 @@ FrameData *DataReaderHelper::decodeFrame(cs::CSJsonDictionary &json)
return frameData; return frameData;
} }
TextureData *DataReaderHelper::decodeTexture(cs::CSJsonDictionary &json) TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json)
{ {
TextureData *textureData = TextureData::create(); TextureData *textureData = TextureData::create();
@ -1078,7 +1078,7 @@ TextureData *DataReaderHelper::decodeTexture(cs::CSJsonDictionary &json)
int length = json.getArrayItemCount(CONTOUR_DATA); int length = json.getArrayItemCount(CONTOUR_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i); cs::JsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i);
textureData->contourDataList->addObject(decodeContour(*dic)); textureData->contourDataList->addObject(decodeContour(*dic));
delete dic; delete dic;
@ -1087,14 +1087,14 @@ TextureData *DataReaderHelper::decodeTexture(cs::CSJsonDictionary &json)
return textureData; return textureData;
} }
ContourData *DataReaderHelper::decodeContour(cs::CSJsonDictionary &json) ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json)
{ {
ContourData *contourData = ContourData::create(); ContourData *contourData = ContourData::create();
int length = json.getArrayItemCount(VERTEX_POINT); int length = json.getArrayItemCount(VERTEX_POINT);
for (int i = length - 1; i >= 0; i--) for (int i = length - 1; i >= 0; i--)
{ {
cs::CSJsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i); cs::JsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i);
ContourVertex2F *vertex = new ContourVertex2F(0, 0); ContourVertex2F *vertex = new ContourVertex2F(0, 0);
@ -1110,7 +1110,7 @@ ContourData *DataReaderHelper::decodeContour(cs::CSJsonDictionary &json)
return contourData; return contourData;
} }
void DataReaderHelper::decodeNode(BaseData *node, cs::CSJsonDictionary &json) void DataReaderHelper::decodeNode(BaseData *node, cs::JsonDictionary &json)
{ {
node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale;
node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale;
@ -1121,7 +1121,7 @@ void DataReaderHelper::decodeNode(BaseData *node, cs::CSJsonDictionary &json)
node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleX = json.getItemFloatValue(A_SCALE_X, 1);
node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1);
cs::CSJsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); cs::JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0);
if (colorDic) if (colorDic)
{ {

View File

@ -29,7 +29,7 @@ THE SOFTWARE.
#include "../datas/CCDatas.h" #include "../datas/CCDatas.h"
#include "../utils/CCConstValue.h" #include "../utils/CCConstValue.h"
#include "../CCArmature.h" #include "../CCArmature.h"
#include "../external_tool/Json/CSContentJsonDictionary.h" #include "../../Json/CSContentJsonDictionary.h"
namespace tinyxml2 { class XMLElement; } namespace tinyxml2 { class XMLElement; }
@ -110,20 +110,20 @@ public:
static void addDataFromJson(const char *filePath); static void addDataFromJson(const char *filePath);
static void addDataFromJsonCache(const char *fileContent); static void addDataFromJsonCache(const char *fileContent);
static ArmatureData *decodeArmature(cs::CSJsonDictionary &json); static ArmatureData *decodeArmature(cs::JsonDictionary &json);
static BoneData *decodeBone(cs::CSJsonDictionary &json); static BoneData *decodeBone(cs::JsonDictionary &json);
static DisplayData *decodeBoneDisplay(cs::CSJsonDictionary &json); static DisplayData *decodeBoneDisplay(cs::JsonDictionary &json);
static AnimationData *decodeAnimation(cs::CSJsonDictionary &json); static AnimationData *decodeAnimation(cs::JsonDictionary &json);
static MovementData *decodeMovement(cs::CSJsonDictionary &json); static MovementData *decodeMovement(cs::JsonDictionary &json);
static MovementBoneData *decodeMovementBone(cs::CSJsonDictionary &json); static MovementBoneData *decodeMovementBone(cs::JsonDictionary &json);
static FrameData *decodeFrame(cs::CSJsonDictionary &json); static FrameData *decodeFrame(cs::JsonDictionary &json);
static TextureData *decodeTexture(cs::CSJsonDictionary &json); static TextureData *decodeTexture(cs::JsonDictionary &json);
static ContourData *decodeContour(cs::CSJsonDictionary &json); static ContourData *decodeContour(cs::JsonDictionary &json);
static void decodeNode(BaseData *node, cs::CSJsonDictionary &json); static void decodeNode(BaseData *node, cs::JsonDictionary &json);
}; };
}}} // namespace cocos2d { namespace extension { namespace armature { }}} // namespace cocos2d { namespace extension { namespace armature {

View File

@ -28,12 +28,14 @@ NS_CC_EXT_BEGIN
ComAttribute::ComAttribute(void) ComAttribute::ComAttribute(void)
: _attributes(NULL) : _attributes(NULL)
, _jsonDict(NULL)
{ {
_name = "ComAttribute"; _name = "ComAttribute";
} }
ComAttribute::~ComAttribute(void) ComAttribute::~ComAttribute(void)
{ {
CC_SAFE_DELETE(_jsonDict);
CC_SAFE_RELEASE(_attributes); CC_SAFE_RELEASE(_attributes);
} }
@ -41,6 +43,8 @@ bool ComAttribute::init()
{ {
_attributes = Dictionary::create(); _attributes = Dictionary::create();
_attributes->retain(); _attributes->retain();
_jsonDict = new cs::JsonDictionary();
return true; return true;
} }
@ -180,4 +184,9 @@ Object* ComAttribute::getObject(const char *key) const
return _attributes->objectForKey(key); return _attributes->objectForKey(key);
} }
cs::JsonDictionary* ComAttribute::getDict() const
{
return _jsonDict;
}
NS_CC_EXT_END NS_CC_EXT_END

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "cocos2d.h" #include "cocos2d.h"
#include "ExtensionMacros.h" #include "ExtensionMacros.h"
#include <string> #include <string>
#include "../Json/CSContentJsonDictionary.h"
NS_CC_EXT_BEGIN NS_CC_EXT_BEGIN
@ -55,8 +56,10 @@ public:
const char* getCString(const char *key) const; const char* getCString(const char *key) const;
Object* getObject(const char *key) const; Object* getObject(const char *key) const;
cs::JsonDictionary* getDict() const;
private: private:
Dictionary *_attributes; Dictionary *_attributes;
cs::JsonDictionary *_jsonDict;
}; };

View File

@ -28,6 +28,8 @@ THE SOFTWARE.
NS_CC_EXT_BEGIN NS_CC_EXT_BEGIN
ComAudio::ComAudio(void) ComAudio::ComAudio(void)
: _filePath("")
, _loop(false)
{ {
_name = "Audio"; _name = "Audio";
} }
@ -201,5 +203,24 @@ void ComAudio::unloadEffect(const char *pszFilePath)
CocosDenshion::SimpleAudioEngine::getInstance()->unloadEffect(pszFilePath); CocosDenshion::SimpleAudioEngine::getInstance()->unloadEffect(pszFilePath);
} }
void ComAudio::setFile(const char* pszFilePath)
{
_filePath.assign(pszFilePath);
}
void ComAudio::setLoop(bool bLoop)
{
_loop = bLoop;
}
const char* ComAudio::getFile()
{
return _filePath.c_str();
}
bool ComAudio::isLoop()
{
return _loop;
}
NS_CC_EXT_END NS_CC_EXT_END

View File

@ -71,6 +71,13 @@ public:
void stopAllEffects(); void stopAllEffects();
void preloadEffect(const char* pszFilePath); void preloadEffect(const char* pszFilePath);
void unloadEffect(const char* pszFilePath); void unloadEffect(const char* pszFilePath);
void setFile(const char* pszFilePath);
const char* getFile();
void setLoop(bool bLoop);
bool isLoop();
private:
std::string _filePath;
bool _loop;
}; };
NS_CC_EXT_END NS_CC_EXT_END

View File

@ -0,0 +1,79 @@
/****************************************************************************
Copyright (c) 2013 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.
****************************************************************************/
#include "CCComRender.h"
NS_CC_EXT_BEGIN
ComRender::ComRender(void)
: _render(NULL)
{
}
ComRender::ComRender(cocos2d::Node *node, const char *comName)
{
_render = node;
_name.assign(comName);
}
ComRender::~ComRender(void)
{
_render = NULL;
}
void ComRender::onEnter()
{
if (_owner != NULL)
{
_owner->addChild(_render);
}
}
void ComRender::onExit()
{
_render = NULL;
}
cocos2d::Node* ComRender::getNode()
{
return _render;
}
ComRender* ComRender::create(cocos2d::Node *pNode, const char *comName)
{
ComRender * pRet = new ComRender(pNode, comName);
if (pRet != NULL && pRet->init())
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
NS_CC_EXT_END

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -21,19 +21,33 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#import <UIKit/UIKit.h>
#include "CCThread.h"
NS_CC_BEGIN #ifndef __CC_EXTENTIONS_CCCOMNODE_H__
#define __CC_EXTENTIONS_CCCOMNODE_H__
Thread::~Thread() #include "cocos2d.h"
#include "cocos-ext.h"
#include "ExtensionMacros.h"
NS_CC_EXT_BEGIN
class ComRender : public cocos2d::Component
{ {
[(id)_autoReleasePool release]; protected:
} ComRender(void);
ComRender(cocos2d::Node *node, const char *comName);
virtual ~ComRender(void);
public:
virtual void onEnter();
virtual void onExit();
cocos2d::Node* getNode();
void Thread::createAutoreleasePool() static ComRender* create(cocos2d::Node *pNode, const char *comName);
{
_autoReleasePool = [[NSAutoreleasePool alloc] init];
}
NS_CC_END private:
cocos2d::Node *_render;
};
NS_CC_EXT_END
#endif // __FUNDATION__CCCOMPONENT_H__

View File

@ -0,0 +1,388 @@
/*
* Copyright (c) 2012 Chukong Technologies, Inc.
*
* http://www.cocostudio.com
* http://tools.cocoachina.com
*
* 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 <iostream>
#include "CSContentJsonDictionary.h"
namespace cs {
JsonDictionary::JsonDictionary()
{
m_cValue.clear();
}
JsonDictionary::~JsonDictionary()
{
m_cValue.clear();
}
void JsonDictionary::initWithDescription(const char *pszDescription)
{
CSJson::Reader cReader;
m_cValue.clear();
if (pszDescription && *pszDescription)
{
std::string strValue = pszDescription;
cReader.parse(strValue, m_cValue, false);
}
}
void JsonDictionary::initWithValue(CSJson::Value& value)
{
m_cValue = value;
}
void JsonDictionary::insertItem(const char *pszKey, int nValue)
{
m_cValue[pszKey] = nValue;
}
void JsonDictionary::insertItem(const char *pszKey, double fValue)
{
m_cValue[pszKey] = fValue;
}
void JsonDictionary::insertItem(const char *pszKey, const char * pszValue)
{
m_cValue[pszKey] = pszValue;
}
void JsonDictionary::insertItem(const char *pszKey, bool bValue)
{
m_cValue[pszKey] = bValue;
}
void JsonDictionary::insertItem(const char *pszKey, JsonDictionary * subDictionary)
{
if (subDictionary)
m_cValue[pszKey] = subDictionary->m_cValue;
}
bool JsonDictionary::deleteItem(const char *pszKey)
{
if(!m_cValue.isMember(pszKey))
return false;
m_cValue.removeMember(pszKey);
return true;
}
void JsonDictionary::cleanUp()
{
m_cValue.clear();
}
bool JsonDictionary::isKeyValidate(const char *pszKey)
{
return m_cValue.isMember(pszKey);
}
int JsonDictionary::getItemIntValue(const char *pszKey, int nDefaultValue)
{
if (!isKeyValidate(pszKey, m_cValue) || !m_cValue[pszKey].isNumeric())
return nDefaultValue;
return m_cValue[pszKey].asInt();
}
double JsonDictionary::getItemFloatValue(const char *pszKey, double fDefaultValue)
{
if (!isKeyValidate(pszKey, m_cValue) || !m_cValue[pszKey].isNumeric())
return fDefaultValue;
return m_cValue[pszKey].asDouble();
}
const char * JsonDictionary::getItemStringValue(const char *pszKey)
{
if (!isKeyValidate(pszKey, m_cValue) || !m_cValue[pszKey].isString())
return NULL;
return m_cValue[pszKey].asCString();
}
bool JsonDictionary::getItemBoolvalue(const char *pszKey, bool bDefaultValue)
{
if (!isKeyValidate(pszKey, m_cValue) || !m_cValue[pszKey].isBool())
return bDefaultValue;
return m_cValue[pszKey].asBool();
}
JsonDictionary * JsonDictionary::getSubDictionary(const char *pszKey)
{
JsonDictionary * pNewDictionary;
if (!isKeyValidate(pszKey, m_cValue) || (!m_cValue[pszKey].isArray() &&
!m_cValue[pszKey].isObject() &&
!m_cValue[pszKey].isConvertibleTo(CSJson::arrayValue) &&
!m_cValue[pszKey].isConvertibleTo(CSJson::objectValue)))
{
pNewDictionary = NULL;
}
else
{
pNewDictionary = new JsonDictionary();
pNewDictionary->initWithValue(m_cValue[pszKey]);
}
return pNewDictionary;
}
std::string JsonDictionary::getDescription()
{
std::string strReturn = m_cValue.toStyledString();
return strReturn;
}
bool JsonDictionary::insertItemToArray(const char *pszArrayKey, int nValue)
{
CSJson::Value array;
if(m_cValue.isMember(pszArrayKey))
{
if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = m_cValue[pszArrayKey];
}
array.append(nValue);
m_cValue[pszArrayKey] = array;
return true;
}
bool JsonDictionary::insertItemToArray(const char *pszArrayKey, double fValue)
{
CSJson::Value array;
if(m_cValue.isMember(pszArrayKey))
{
if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = m_cValue[pszArrayKey];
}
array.append(fValue);
m_cValue[pszArrayKey] = array;
return true;
}
bool JsonDictionary::insertItemToArray(const char *pszArrayKey, const char * pszValue)
{
CSJson::Value array;
if(m_cValue.isMember(pszArrayKey))
{
if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = m_cValue[pszArrayKey];
}
array.append(pszValue);
m_cValue[pszArrayKey] = array;
return true;
}
bool JsonDictionary::insertItemToArray(const char *pszArrayKey, JsonDictionary * subDictionary)
{
CSJson::Value array;
if(m_cValue.isMember(pszArrayKey))
{
if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return false;
array = m_cValue[pszArrayKey];
}
array.append(subDictionary->m_cValue);
m_cValue[pszArrayKey] = array;
return true;
}
int JsonDictionary::getItemCount()
{
return m_cValue.size();
}
DicItemType JsonDictionary::getItemType(int nIndex)
{
return (DicItemType)m_cValue[nIndex].type();
}
DicItemType JsonDictionary::getItemType(const char *pszKey)
{
return (DicItemType)m_cValue[pszKey].type();
}
std::vector<std::string> JsonDictionary::getAllMemberNames()
{
return m_cValue.getMemberNames();
}
int JsonDictionary::getArrayItemCount(const char *pszArrayKey)
{
int nRet = 0;
if (!isKeyValidate(pszArrayKey, m_cValue) ||
(!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isObject() &&
!m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue) && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::objectValue)))
{
nRet = 0;
}
else
{
CSJson::Value arrayValue = m_cValue[pszArrayKey];
nRet = arrayValue.size();
}
return nRet;
}
int JsonDictionary::getIntValueFromArray(const char *pszArrayKey, int nIndex, int nDefaultValue)
{
int nRet = nDefaultValue;
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isNumeric())
nRet = (*arrayValue)[nIndex].asInt();
}
return nRet;
}
double JsonDictionary::getFloatValueFromArray(const char *pszArrayKey, int nIndex, double fDefaultValue)
{
double fRet = fDefaultValue;
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isNumeric())
fRet = (*arrayValue)[nIndex].asDouble();
}
return fRet;
}
bool JsonDictionary::getBoolValueFromArray(const char *pszArrayKey, int nIndex, bool bDefaultValue)
{
bool bRet = bDefaultValue;
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isNumeric())
bRet = (*arrayValue)[nIndex].asBool();
}
return bRet;
}
const char * JsonDictionary::getStringValueFromArray(const char *pszArrayKey, int nIndex)
{
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isString())
return (*arrayValue)[nIndex].asCString();
}
return NULL;
}
JsonDictionary * JsonDictionary::getSubItemFromArray(const char *pszArrayKey, int nIndex)
{
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
{
if ((*arrayValue)[nIndex].isArray() || (*arrayValue)[nIndex].isObject())
{
JsonDictionary * pNewDictionary = new JsonDictionary();
pNewDictionary->initWithValue((*arrayValue)[nIndex]);
return pNewDictionary;
}
}
return NULL;
}
DicItemType JsonDictionary::getItemTypeFromArray(const char *pszArrayKey, int nIndex)
{
CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex);
if (arrayValue)
return (DicItemType)((*arrayValue)[nIndex].type());
return (DicItemType)CSJson::nullValue;
}
inline bool JsonDictionary::isKeyValidate(const char *pszKey, CSJson::Value& root)
{
if (root.isNull() || !root.isMember(pszKey))
return false;
return true;
}
inline CSJson::Value * JsonDictionary::validateArrayItem(const char *pszArrayKey, int nIndex)
{
if (!isKeyValidate(pszArrayKey, m_cValue) && !m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue))
return NULL;
if (!m_cValue[pszArrayKey].isValidIndex(nIndex))
return NULL;
return &m_cValue[pszArrayKey];
}
}

View File

@ -46,18 +46,18 @@ namespace cs {
EDIC_TYPEOBJECT EDIC_TYPEOBJECT
}DicItemType; }DicItemType;
class CSJsonDictionary class JsonDictionary
{ {
public: public:
CSJsonDictionary(); JsonDictionary();
~CSJsonDictionary(); ~JsonDictionary();
public: public:
void initWithDescription(const char *pszDescription); void initWithDescription(const char *pszDescription);
void insertItem(const char *pszKey, int nValue); void insertItem(const char *pszKey, int nValue);
void insertItem(const char *pszKey, double fValue); void insertItem(const char *pszKey, double fValue);
void insertItem(const char *pszKey, const char * pszValue); void insertItem(const char *pszKey, const char * pszValue);
void insertItem(const char *pszKey, CSJsonDictionary * subDictionary); void insertItem(const char *pszKey, JsonDictionary * subDictionary);
void insertItem(const char *pszKey, bool bValue); void insertItem(const char *pszKey, bool bValue);
bool deleteItem(const char *pszKey); bool deleteItem(const char *pszKey);
void cleanUp(); void cleanUp();
@ -67,20 +67,21 @@ namespace cs {
double getItemFloatValue(const char *pszKey, double fDefaultValue); double getItemFloatValue(const char *pszKey, double fDefaultValue);
const char * getItemStringValue(const char *pszKey); const char * getItemStringValue(const char *pszKey);
bool getItemBoolvalue(const char *pszKey, bool bDefaultValue); bool getItemBoolvalue(const char *pszKey, bool bDefaultValue);
CSJsonDictionary * getSubDictionary(const char *pszKey); JsonDictionary * getSubDictionary(const char *pszKey);
std::string getDescription(); std::string getDescription();
bool insertItemToArray(const char *pszArrayKey, int nValue); bool insertItemToArray(const char *pszArrayKey, int nValue);
bool insertItemToArray(const char *pszArrayKey, double fValue); bool insertItemToArray(const char *pszArrayKey, double fValue);
bool insertItemToArray(const char *pszArrayKey, const char * pszValue); bool insertItemToArray(const char *pszArrayKey, const char * pszValue);
bool insertItemToArray(const char *pszArrayKey, CSJsonDictionary * subDictionary); bool insertItemToArray(const char *pszArrayKey, JsonDictionary * subDictionary);
int getArrayItemCount(const char *pszArrayKey); int getArrayItemCount(const char *pszArrayKey);
int getIntValueFromArray(const char *pszArrayKey, int nIndex, int nDefaultValue); int getIntValueFromArray(const char *pszArrayKey, int nIndex, int nDefaultValue);
double getFloatValueFromArray(const char *pszArrayKey, int nIndex, double fDefaultValue); double getFloatValueFromArray(const char *pszArrayKey, int nIndex, double fDefaultValue);
bool getBoolValueFromArray(const char *pszArrayKey, int nIndex, bool bDefaultValue);
const char * getStringValueFromArray(const char *pszArrayKey, int nIndex); const char * getStringValueFromArray(const char *pszArrayKey, int nIndex);
CSJsonDictionary *getSubItemFromArray(const char *pszArrayKey, int nIndex); JsonDictionary *getSubItemFromArray(const char *pszArrayKey, int nIndex);
DicItemType getItemTypeFromArray(const char *pszArrayKey, int nIndex); DicItemType getItemTypeFromArray(const char *pszArrayKey, int nIndex);
int getItemCount(); int getItemCount();
@ -89,7 +90,7 @@ namespace cs {
std::vector<std::string> getAllMemberNames(); std::vector<std::string> getAllMemberNames();
protected: protected:
CSJson::Value _value; CSJson::Value m_cValue;
private: private:
void initWithValue(CSJson::Value& value); void initWithValue(CSJson::Value& value);

View File

@ -0,0 +1,289 @@
/****************************************************************************
Copyright (c) 2013 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.
****************************************************************************/
#include "DictionaryHelper.h"
NS_CC_EXT_BEGIN
static DictionaryHelper* sharedHelper = NULL;
DictionaryHelper::DictionaryHelper()
{
}
DictionaryHelper::~DictionaryHelper()
{
}
DictionaryHelper* DictionaryHelper::shareHelper()
{
if (!sharedHelper) {
sharedHelper = new DictionaryHelper();
}
return sharedHelper;
}
void DictionaryHelper::purgeDictionaryHelper()
{
CC_SAFE_DELETE(sharedHelper);
}
cocos2d::Dictionary* DictionaryHelper::getSubDictionary(cocos2d::Dictionary* root,const char* key)
{
if (!root) {
return NULL;
}
cocos2d::Object* obj = root->objectForKey(key);
if (!obj) {
return NULL;
}
return (cocos2d::Dictionary*)(obj);
}
int DictionaryHelper::getIntValue(cocos2d::Dictionary* root,const char* key)
{
if (!root) {
return 0;
}
cocos2d::Object* obj = root->objectForKey(key);
if (!obj) {
return 0;
}
cocos2d::String* cstr = (cocos2d::String*)(obj);
return cstr->intValue();
}
float DictionaryHelper::getFloatValue(cocos2d::Dictionary* root,const char* key)
{
if (!root) {
return 0.0;
}
cocos2d::Object* obj = root->objectForKey(key);
if (!obj) {
return 0.0f;
}
cocos2d::String* cstr = (cocos2d::String*)(obj);
return cstr->floatValue();
}
const char* DictionaryHelper::getStringValue(cocos2d::Dictionary* root,const char* key)
{
if (!root) {
return NULL;
}
cocos2d::Object* obj = root->objectForKey(key);
if (!obj) {
return NULL;
}
cocos2d::String* cstr = (cocos2d::String*)(obj);
return cstr->_string.c_str();
}
bool DictionaryHelper::getBooleanValue(cocos2d::Dictionary* root,const char* key)
{
return this->getIntValue(root, key);
}
cocos2d::Array* DictionaryHelper::getArrayValue(cocos2d::Dictionary *root, const char *key)
{
if (!root) {
return NULL;
}
cocos2d::Object* obj = root->objectForKey(key);
if (!obj) {
return NULL;
}
cocos2d::Array* array = (cocos2d::Array*)(obj);
return array;
}
cocos2d::Object* DictionaryHelper::checkObjectExist(cocos2d::Dictionary *root, const char *key)
{
if (!root) {
return NULL;
}
return root->objectForKey(key);
}
int DictionaryHelper::objectToIntValue(cocos2d::Object *obj)
{
if (!obj)
{
return 0;
}
cocos2d::String* cstr = (cocos2d::String*)(obj);
return cstr->intValue();
}
float DictionaryHelper::objectToFloatValue(cocos2d::Object *obj)
{
if (!obj)
{
return 0.0f;
}
cocos2d::String* cstr = (cocos2d::String*)(obj);
return cstr->floatValue();
}
const char* DictionaryHelper::objectToStringValue(cocos2d::Object *obj)
{
if (!obj)
{
return NULL;
}
cocos2d::String* cstr = (cocos2d::String*)(obj);
return cstr->_string.c_str();
}
bool DictionaryHelper::objectToBooleanValue(cocos2d::Object *obj)
{
if (!obj)
{
return 0;
}
return this->objectToIntValue(obj);
}
cocos2d::Array* DictionaryHelper::objectToCCArray(cocos2d::Object *obj)
{
if (!obj)
{
return NULL;
}
cocos2d::Array* array = (cocos2d::Array*)(obj);
return array;
}
cs::JsonDictionary* DictionaryHelper::getSubDictionary_json(cs::JsonDictionary* root,const char* key)
{
if (!root)
{
return NULL;
}
return root->getSubDictionary(key);
}
int DictionaryHelper::getIntValue_json(cs::JsonDictionary* root,const char* key)
{
if (!root)
{
return 0;
}
return root->getItemIntValue(key, 0);
}
float DictionaryHelper::getFloatValue_json(cs::JsonDictionary* root,const char* key)
{
if (!root)
{
return 0.0f;
}
return root->getItemFloatValue(key, 0.0);
}
const char* DictionaryHelper::getStringValue_json(cs::JsonDictionary* root,const char* key)
{
if (!root)
{
return NULL;
}
return root->getItemStringValue(key);
}
bool DictionaryHelper::getBooleanValue_json(cs::JsonDictionary* root,const char* key)
{
if (!root)
{
return 0;
}
return root->getItemBoolvalue(key, false);
}
int DictionaryHelper::getArrayCount_json(cs::JsonDictionary* root,const char* key)
{
if (!root)
{
return 0;
}
return root->getArrayItemCount(key);
}
int DictionaryHelper::getIntValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx)
{
if (!root)
{
return 0;
}
return root->getIntValueFromArray(arrayKey, idx, 0);
}
float DictionaryHelper::getFloatValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx)
{
if (!root)
{
return 0.0f;
}
return root->getFloatValueFromArray(arrayKey, idx, 0.0);
}
bool DictionaryHelper::getBoolValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx)
{
if (!root)
{
return false;
}
return root->getBoolValueFromArray(arrayKey, idx, false);
}
const char* DictionaryHelper::getStringValueFromArray_json(cs::JsonDictionary *root, const char *arrayKey, int idx)
{
if (!root)
{
return NULL;
}
return root->getStringValueFromArray(arrayKey, idx);
}
cs::JsonDictionary* DictionaryHelper::getDictionaryFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx)
{
if (!root)
{
return NULL;
}
return root->getSubItemFromArray(arrayKey, idx);
}
bool DictionaryHelper::checkObjectExist_json(cs::JsonDictionary *root, const char *key)
{
if (!root)
{
return false;
}
return root->isKeyValidate(key);
}
NS_CC_EXT_END

View File

@ -0,0 +1,72 @@
/****************************************************************************
Copyright (c) 2013 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 __DICTIONARYHELPER_H__
#define __DICTIONARYHELPER_H__
#include "cocos2d.h"
#include "cocos-ext.h"
#include "ExtensionMacros.h"
#define DICTOOL DictionaryHelper::shareHelper()
NS_CC_EXT_BEGIN
class DictionaryHelper
{
public:
DictionaryHelper();
~DictionaryHelper();
static DictionaryHelper* shareHelper();
static void purgeDictionaryHelper();
cocos2d::Dictionary* getSubDictionary(cocos2d::Dictionary* root,const char* key);
int getIntValue(cocos2d::Dictionary* root,const char* key);
float getFloatValue(cocos2d::Dictionary* root,const char* key);
const char* getStringValue(cocos2d::Dictionary* root,const char* key);
bool getBooleanValue(cocos2d::Dictionary* root,const char* key);
cocos2d::Array* getArrayValue(cocos2d::Dictionary* root,const char* key);
cocos2d::Object* checkObjectExist(cocos2d::Dictionary* root,const char* key);
int objectToIntValue(cocos2d::Object* obj);
float objectToFloatValue(cocos2d::Object* obj);
const char* objectToStringValue(cocos2d::Object* obj);
bool objectToBooleanValue(cocos2d::Object* obj);
cocos2d::Array* objectToCCArray(cocos2d::Object* obj);
cs::JsonDictionary* getSubDictionary_json(cs::JsonDictionary* root,const char* key);
int getIntValue_json(cs::JsonDictionary* root,const char* key);
float getFloatValue_json(cs::JsonDictionary* root,const char* key);
const char* getStringValue_json(cs::JsonDictionary* root,const char* key);
bool getBooleanValue_json(cs::JsonDictionary* root,const char* key);
int getArrayCount_json(cs::JsonDictionary* root,const char* key);
int getIntValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx);
float getFloatValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx);
bool getBoolValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx);
const char* getStringValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx);
cs::JsonDictionary* getDictionaryFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx);
bool checkObjectExist_json(cs::JsonDictionary* root,const char* key);
};
NS_CC_EXT_END
#endif /* defined(__CocoGUI__DictionaryHelper__) */

Some files were not shown because too many files have changed in this diff Show More