Merge branch 'develop' into new_shader_test

This commit is contained in:
Huabing.Xu 2013-09-09 18:18:31 +08:00
commit d7d914feb1
75 changed files with 1032 additions and 956 deletions

View File

@ -1 +1 @@
fd0dee451420604712c1327679395cd1faca91b6
0bd142a09d7aacd3dbff8f23c7a14966430e9c01

View File

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

View File

@ -61,7 +61,7 @@ typedef struct _hashSelectorEntry
{
ccArray *timers;
Object *target; // hash key (retained)
unsigned int timerIndex;
int timerIndex;
Timer *currentTimer;
bool currentTimerSalvaged;
bool paused;
@ -320,7 +320,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in
}
else
{
for (unsigned int i = 0; i < element->timers->num; ++i)
for (int i = 0; i < element->timers->num; ++i)
{
Timer *timer = (Timer*)element->timers->arr[i];
@ -356,7 +356,7 @@ void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Object *target)
if (element)
{
for (unsigned int i = 0; i < element->timers->num; ++i)
for (int i = 0; i < element->timers->num; ++i)
{
Timer *pTimer = (Timer*)(element->timers->arr[i]);
@ -521,7 +521,7 @@ bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Object *target)
return false;
}else
{
for (unsigned int i = 0; i < element->timers->num; ++i)
for (int i = 0; i < element->timers->num; ++i)
{
Timer *timer = (Timer*)element->timers->arr[i];

View File

@ -581,7 +581,7 @@ Spawn* Spawn::create(Array *arrayOfActions)
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
if (count > 1)
{
for (unsigned int i = 1; i < arrayOfActions->count(); ++i)
for (int i = 1; i < arrayOfActions->count(); ++i)
{
prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(i)));
}
@ -2100,7 +2100,7 @@ void Animate::update(float t)
}
Array* frames = _animation->getFrames();
unsigned int numberOfFrames = frames->count();
int numberOfFrames = frames->count();
SpriteFrame *frameToDisplay = NULL;
for( int i=_nextFrame; i < numberOfFrames; i++ ) {

View File

@ -41,7 +41,7 @@ typedef struct _hashElement
{
struct _ccArray *actions;
Object *target;
unsigned int actionIndex;
int actionIndex;
Action *currentAction;
bool currentActionSalvaged;
bool paused;
@ -87,9 +87,9 @@ void ActionManager::actionAllocWithHashElement(tHashElement *pElement)
}
void ActionManager::removeActionAtIndex(unsigned int uIndex, tHashElement *pElement)
void ActionManager::removeActionAtIndex(int index, tHashElement *pElement)
{
Action *pAction = (Action*)pElement->actions->arr[uIndex];
Action *pAction = (Action*)pElement->actions->arr[index];
if (pAction == pElement->currentAction && (! pElement->currentActionSalvaged))
{
@ -97,10 +97,10 @@ void ActionManager::removeActionAtIndex(unsigned int uIndex, tHashElement *pElem
pElement->currentActionSalvaged = true;
}
ccArrayRemoveObjectAtIndex(pElement->actions, uIndex, true);
ccArrayRemoveObjectAtIndex(pElement->actions, index, true);
// update actionIndex in case we are in tick. looping over the actions
if (pElement->actionIndex >= uIndex)
if (pElement->actionIndex >= index)
{
pElement->actionIndex--;
}

View File

@ -119,7 +119,7 @@ public:
protected:
// declared in ActionManager.m
void removeActionAtIndex(unsigned int uIndex, struct _hashElement *pElement);
void removeActionAtIndex(int index, struct _hashElement *pElement);
void deleteHashElement(struct _hashElement *pElement);
void actionAllocWithHashElement(struct _hashElement *pElement);
void update(float dt);

View File

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

View File

@ -60,8 +60,8 @@ const Color4F Color4F::BLUE(0,0,1,1);
const Color4F Color4F::RED(1,0,0,1);
const Color4F Color4F::MAGENTA(1,0,1,1);
const Color4F Color4F::BLACK(0,0,0,1);
const Color4F Color4F::ORANGE(1,0.5,0,1);
const Color4F Color4F::GRAY(0.65,0.65,0.65,1);
const Color4F Color4F::ORANGE(1,0.5f,0,1);
const Color4F Color4F::GRAY(0.65f,0.65f,0.65f,1);
const BlendFunc BlendFunc::DISABLE = {GL_ONE, GL_ZERO};
const BlendFunc BlendFunc::ALPHA_PREMULTIPLIED = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA};

View File

@ -153,7 +153,7 @@ bool KeypadDispatcher::dispatchKeypadMSG(ccKeypadMSGType nMsgType)
if (_toRemove)
{
_toRemove = false;
for (unsigned int i = 0; i < _handlersToRemove->num; ++i)
for (int i = 0; i < _handlersToRemove->num; ++i)
{
forceRemoveDelegate((KeypadDelegate*)_handlersToRemove->arr[i]);
}
@ -163,7 +163,7 @@ bool KeypadDispatcher::dispatchKeypadMSG(ccKeypadMSGType nMsgType)
if (_toAdd)
{
_toAdd = false;
for (unsigned int i = 0; i < _handlersToAdd->num; ++i)
for (int i = 0; i < _handlersToAdd->num; ++i)
{
forceAddDelegate((KeypadDelegate*)_handlersToAdd->arr[i]);
}

View File

@ -940,7 +940,7 @@ void LabelBMFont::updateLabel()
int skip = 0;
Array* children = getChildren();
for (unsigned int j = 0; j < children->count(); j++)
for (int j = 0; j < children->count(); j++)
{
Sprite* characterSprite;
unsigned int justSkipped = 0;

View File

@ -56,7 +56,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
Array* children = theLabel->getChildrenLetters();
for (unsigned int j = 0; j < children->count(); j++)
for (int j = 0; j < children->count(); j++)
{
Sprite* characterSprite;
unsigned int justSkipped = 0;

View File

@ -1123,7 +1123,7 @@ bool LayerMultiplex::initWithArray(Array* arrayOfLayers)
return false;
}
void LayerMultiplex::switchTo(unsigned int n)
void LayerMultiplex::switchTo(int n)
{
CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" );
@ -1134,7 +1134,7 @@ void LayerMultiplex::switchTo(unsigned int n)
this->addChild((Node*)_layers->getObjectAtIndex(n));
}
void LayerMultiplex::switchToAndReleaseMe(unsigned int n)
void LayerMultiplex::switchToAndReleaseMe(int n)
{
CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" );

View File

@ -388,11 +388,11 @@ public:
/** switches to a certain layer indexed by n.
The current (old) layer will be removed from it's parent with 'cleanup=true'.
*/
void switchTo(unsigned int n);
void switchTo(int n);
/** release the current layer and switches to another layer indexed by n.
The current (old) layer will be removed from it's parent with 'cleanup=true'.
*/
void switchToAndReleaseMe(unsigned int n);
void switchToAndReleaseMe(int n);
protected:
unsigned int _enabledLayer;

View File

@ -806,7 +806,7 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle
pRet->_subItems = Array::create();
pRet->_subItems->retain();
for (unsigned int z=0; z < menuItems->count(); z++)
for (int z=0; z < menuItems->count(); z++)
{
MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
pRet->_subItems->addObject(menuItem);
@ -824,7 +824,7 @@ MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callba
pRet->_subItems = Array::create();
pRet->_subItems->retain();
for (unsigned int z=0; z < menuItems->count(); z++)
for (int z=0; z < menuItems->count(); z++)
{
MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
pRet->_subItems->addObject(menuItem);

View File

@ -272,7 +272,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
// Find new AtlasIndex
int newAtlasIndex = 0;
for( unsigned int i=0;i < _children->count();i++)
for( int i=0;i < _children->count();i++)
{
ParticleSystem* pNode = (ParticleSystem*)_children->getObjectAtIndex(i);
if( pNode == child )

View File

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

View File

@ -372,7 +372,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
CCASSERT(isOK, "CCParticleSystem: error init image with Data");
CC_BREAK_IF(!isOK);
setTexture(TextureCache::getInstance()->addUIImage(image, textureName.c_str()));
setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str()));
image->release();
}
@ -405,7 +405,7 @@ bool ParticleSystem::initWithTotalParticles(unsigned int numberOfParticles)
if (_batchNode)
{
for (unsigned int i = 0; i < _totalParticles; i++)
for (int i = 0; i < _totalParticles; i++)
{
_particles[i].atlasIndex=i;
}
@ -1020,12 +1020,12 @@ bool ParticleSystem::isActive() const
return _isActive;
}
unsigned int ParticleSystem::getTotalParticles() const
int ParticleSystem::getTotalParticles() const
{
return _totalParticles;
}
void ParticleSystem::setTotalParticles(unsigned int var)
void ParticleSystem::setTotalParticles(int var)
{
CCASSERT( var <= _allocatedParticles, "Particle: resizing particle array only supported for quads");
_totalParticles = var;
@ -1070,7 +1070,7 @@ void ParticleSystem::setBatchNode(ParticleBatchNode* batchNode)
if( batchNode ) {
//each particle needs a unique index
for (unsigned int i = 0; i < _totalParticles; i++)
for (int i = 0; i < _totalParticles; i++)
{
_particles[i].atlasIndex=i;
}

View File

@ -356,8 +356,8 @@ public:
inline void setEmissionRate(float rate) { _emissionRate = rate; };
/** maximum particles of the system */
virtual unsigned int getTotalParticles() const;
virtual void setTotalParticles(unsigned int totalParticles);
virtual int getTotalParticles() const;
virtual void setTotalParticles(int totalParticles);
/** does the alpha value modify color */
inline void setOpacityModifyRGB(bool opacityModifyRGB) { _opacityModifyRGB = opacityModifyRGB; };
@ -446,7 +446,7 @@ protected:
float _emitCounter;
//! particle idx
unsigned int _particleIdx;
int _particleIdx;
// Optimization
//CC_UPDATE_PARTICLE_IMP updateParticleImp;
@ -461,13 +461,13 @@ protected:
//true if scaled or rotated
bool _transformSystemDirty;
// Number of allocated particles
unsigned int _allocatedParticles;
int _allocatedParticles;
/** Is the emitter active */
bool _isActive;
/** Quantity of particles that are being simulated at the moment */
unsigned int _particleCount;
int _particleCount;
/** How many seconds the emitter will run. -1 means 'forever' */
float _duration;
/** sourcePosition of the emitter */
@ -516,7 +516,7 @@ protected:
/** emission rate of the particles */
float _emissionRate;
/** maximum particles of the system */
unsigned int _totalParticles;
int _totalParticles;
/** conforms to CocosNodeTexture protocol */
Texture2D* _texture;
/** conforms to CocosNodeTexture protocol */

View File

@ -227,7 +227,7 @@ void ParticleSystemQuad::setDisplayFrame(SpriteFrame *spriteFrame)
void ParticleSystemQuad::initIndices()
{
for(unsigned int i = 0; i < _totalParticles; ++i)
for(int i = 0; i < _totalParticles; ++i)
{
const unsigned int i6 = i*6;
const unsigned int i4 = i*4;
@ -401,7 +401,7 @@ void ParticleSystemQuad::draw()
CHECK_GL_ERROR_DEBUG();
}
void ParticleSystemQuad::setTotalParticles(unsigned int tp)
void ParticleSystemQuad::setTotalParticles(int tp)
{
// If we are setting the total number of particles to a number higher
// than what is allocated, we need to allocate new arrays
@ -447,7 +447,7 @@ void ParticleSystemQuad::setTotalParticles(unsigned int tp)
// Init particles
if (_batchNode)
{
for (unsigned int i = 0; i < _totalParticles; i++)
for (int i = 0; i < _totalParticles; i++)
{
_particles[i].atlasIndex=i;
}

View File

@ -94,7 +94,7 @@ public:
virtual void postStep() override;
virtual void draw() override;
virtual void setBatchNode(ParticleBatchNode* batchNode) override;
virtual void setTotalParticles(unsigned int tp) override;
virtual void setTotalParticles(int tp) override;
private:
#if CC_TEXTURE_ATLAS_USE_VAO

View File

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

View File

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

View File

@ -1504,7 +1504,7 @@ bool Image::initWithS3TCData(const unsigned char * data, int dataLen)
}
else //decompressed data length
{
for (unsigned int i = 0; i < _numberOfMipmaps && (width || height); ++i)
for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;
@ -1523,7 +1523,7 @@ bool Image::initWithS3TCData(const unsigned char * data, int dataLen)
int decodeOffset = 0;
width = _width; height = _height;
for (unsigned int i = 0; i < _numberOfMipmaps && (width || height); ++i)
for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;
@ -1629,7 +1629,7 @@ bool Image::initWithATITCData(const unsigned char *data, int dataLen)
}
else //decompressed data length
{
for (unsigned int i = 0; i < _numberOfMipmaps && (width || height); ++i)
for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;
@ -1647,7 +1647,7 @@ bool Image::initWithATITCData(const unsigned char *data, int dataLen)
int decodeOffset = 0;
width = _width; height = _height;
for (unsigned int i = 0; i < _numberOfMipmaps && (width || height); ++i)
for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -46,7 +46,7 @@ static void atitc_decode_block(uint8_t **blockData,
(*blockData) += 2;
//extract the msb flag
msb = (colorValue0 & 0x8000);
msb = (colorValue0 & 0x8000) != 0;
/* the channel is r5g6b5 , 16 bits */
rb0 = (colorValue0 << 3 | colorValue0 << 9) & 0xf800f8;
@ -152,8 +152,8 @@ static void atitc_decode_block(uint8_t **blockData,
//Decode ATITC encode data to RGB32
void atitc_decode(uint8_t *encodeData, //in_data
uint8_t *decodeData, //out_data
const unsigned int pixelsWidth,
const unsigned int pixelsHeight,
const int pixelsWidth,
const int pixelsHeight,
ATITCDecodeFlag decodeFlag)
{
uint32_t *decodeBlockData = (uint32_t *)decodeData;

View File

@ -38,8 +38,8 @@ enum class ATITCDecodeFlag
//Decode ATITC encode data to RGB32
void atitc_decode(uint8_t *encode_data,
uint8_t *decode_data,
const unsigned int pixelsWidth,
const unsigned int pixelsHeight,
const int pixelsWidth,
const int pixelsHeight,
ATITCDecodeFlag decodeFlag
);

View File

@ -140,8 +140,8 @@ static void s3tc_decode_block(uint8_t **blockData,
//Decode S3TC encode data to RGB32
void s3tc_decode(uint8_t *encodeData, //in_data
uint8_t *decodeData, //out_data
const unsigned int pixelsWidth,
const unsigned int pixelsHeight,
const int pixelsWidth,
const int pixelsHeight,
S3TCDecodeFlag decodeFlag)
{
uint32_t *decodeBlockData = (uint32_t *)decodeData;

View File

@ -38,8 +38,8 @@ enum class S3TCDecodeFlag
//Decode S3TC encode data to RGB32
void s3tc_decode(uint8_t *encode_data,
uint8_t *decode_data,
const unsigned int pixelsWidth,
const unsigned int pixelsHeight,
const int pixelsWidth,
const int pixelsHeight,
S3TCDecodeFlag decodeFlag
);

View File

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

View File

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

View File

@ -35,7 +35,6 @@ int Application::run()
PVRFrameEnableControlWindow(false);
// Main message loop:
MSG msg;
LARGE_INTEGER nFreq;
LARGE_INTEGER nLast;
LARGE_INTEGER nNow;

View File

@ -187,8 +187,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x,
EGLView* eglView = EGLView::getInstance();
if(nullptr == eglView) return;
s_mouseX /= eglView->getFrameZoomFactor();
s_mouseY /= eglView->getFrameZoomFactor();
s_mouseX *= eglView->getFrameZoomFactor();
s_mouseY *= eglView->getFrameZoomFactor();
if(s_captured)
{
@ -336,8 +336,8 @@ void EGLView::swapBuffers()
bool EGLView::windowShouldClose()
{
if(_mainWindow)
return glfwWindowShouldClose(_mainWindow);
if(_mainWindow)
return glfwWindowShouldClose(_mainWindow) != 0;
else
return true;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -363,7 +363,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
void SpriteBatchNode::swap(int oldIndex, int newIndex)
{
CCASSERT(oldIndex>=0 && oldIndex < _descendants.size() && newIndex >=0 && newIndex < _descendants.size(), "Invalid index");
CCASSERT(oldIndex>=0 && oldIndex < (int)_descendants.size() && newIndex >=0 && newIndex < (int)_descendants.size(), "Invalid index");
V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads();
std::swap( quads[oldIndex], quads[newIndex] );

View File

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

View File

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

View File

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

View File

@ -108,7 +108,7 @@ void ParallaxNode::addChild(Node *child, int z, const Point& ratio, const Point&
}
void ParallaxNode::removeChild(Node* child, bool cleanup)
{
for( unsigned int i=0;i < _parallaxArray->num;i++)
for( int i=0;i < _parallaxArray->num;i++)
{
PointObject *point = (PointObject*)_parallaxArray->arr[i];
if( point->getChild()->isEqual(child))
@ -148,7 +148,7 @@ void ParallaxNode::visit()
Point pos = this->absolutePosition();
if( ! pos.equals(_lastPosition) )
{
for(unsigned int i=0; i < _parallaxArray->num; i++ )
for( int i=0; i < _parallaxArray->num; i++ )
{
PointObject *point = (PointObject*)_parallaxArray->arr[i];
float x = -pos.x + pos.x * point->getRatio().x + point->getOffset().x;

View File

@ -476,7 +476,7 @@ unsigned int TMXLayer::atlasIndexForExistantZ(unsigned int z)
unsigned int TMXLayer::atlasIndexForNewZ(int z)
{
// XXX: This can be improved with a sort of binary search
unsigned int i=0;
int i=0;
for (i=0; i< _atlasIndexArray->num ; i++)
{
int val = (size_t) _atlasIndexArray->arr[i];

View File

@ -460,7 +460,7 @@ void TouchDispatcher::touches(Set *pTouches, Event *pEvent, unsigned int uIndex)
if (_toRemove)
{
_toRemove = false;
for (unsigned int i = 0; i < _handlersToRemove->num; ++i)
for (int i = 0; i < _handlersToRemove->num; ++i)
{
forceRemoveDelegate((TouchDelegate*)_handlersToRemove->arr[i]);
}

View File

@ -556,7 +556,7 @@ void ScrollView::visit()
if(_children)
{
unsigned int i=0;
int i=0;
// draw children zOrder < 0
for( ; i < _children->count(); i++ )

View File

@ -75,7 +75,7 @@ void ArrayForObjectSorting::removeSortedObject(SortableObject* object)
if (this->count() == 0) {
return;
}
unsigned int idx;
int idx;
SortableObject* foundObj;
idx = this->indexOfSortedObject(object);
@ -91,7 +91,7 @@ void ArrayForObjectSorting::removeSortedObject(SortableObject* object)
void ArrayForObjectSorting::setObjectID_ofSortedObject(unsigned int tag, SortableObject* object)
{
SortableObject* foundObj;
unsigned int idx;
int idx;
idx = this->indexOfSortedObject(object);
if (idx < this->count() && idx != CC_INVALID_INDEX)
@ -117,7 +117,7 @@ SortableObject* ArrayForObjectSorting::objectWithObjectID(unsigned int tag)
return NULL;
}
unsigned int idx;
int idx;
SortableObject* foundObj;
foundObj = new SortedObject();

View File

@ -184,13 +184,13 @@ void TableView::insertCellAtIndex(unsigned int idx)
TableViewCell* cell = NULL;
int newIdx = 0;
cell = (TableViewCell*)_cellsUsed->objectWithObjectID(idx);
cell = static_cast<TableViewCell*>(_cellsUsed->objectWithObjectID(idx));
if (cell)
{
newIdx = _cellsUsed->indexOfSortedObject(cell);
for (unsigned int i=newIdx; i<_cellsUsed->count(); i++)
for (int i=newIdx; i<_cellsUsed->count(); i++)
{
cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(i);
cell = static_cast<TableViewCell*>(_cellsUsed->getObjectAtIndex(i));
this->_setIndexForCell(cell->getIdx()+1, cell);
}
}

2
plugin

@ -1 +1 @@
Subproject commit c2c2e562c6d92f95b47b16ce97056e5617368920
Subproject commit d583b83c5806a0d44788095dfc541fb2812c600e

View File

@ -89,6 +89,7 @@ Classes/MutiTouchTest/MutiTouchTest.cpp \
Classes/NodeTest/NodeTest.cpp \
Classes/ParallaxTest/ParallaxTest.cpp \
Classes/ParticleTest/ParticleTest.cpp \
Classes/PerformanceTest/PerformanceAllocTest.cpp \
Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \
Classes/PerformanceTest/PerformanceParticleTest.cpp \
Classes/PerformanceTest/PerformanceSpriteTest.cpp \

View File

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

View File

@ -1,4 +1,4 @@
#include "LabelTestNew.h"
#include "LabelTestNew.h"
#include "../testResource.h"
enum {

View File

@ -0,0 +1,483 @@
/*
*
*/
#include "PerformanceAllocTest.h"
#include <algorithm>
// Enable profiles for this file
#undef CC_PROFILER_DISPLAY_TIMERS
#define CC_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers()
#undef CC_PROFILER_PURGE_ALL
#define CC_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers()
#undef CC_PROFILER_START
#define CC_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__)
#undef CC_PROFILER_STOP
#define CC_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__)
#undef CC_PROFILER_RESET
#define CC_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__)
#undef CC_PROFILER_START_CATEGORY
#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingBeginTimingBlock(__name__); } while(0)
#undef CC_PROFILER_STOP_CATEGORY
#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingEndTimingBlock(__name__); } while(0)
#undef CC_PROFILER_RESET_CATEGORY
#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingResetTimingBlock(__name__); } while(0)
#undef CC_PROFILER_START_INSTANCE
#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ ProfilingBeginTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0)
#undef CC_PROFILER_STOP_INSTANCE
#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ ProfilingEndTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0)
#undef CC_PROFILER_RESET_INSTANCE
#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ ProfilingResetTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0)
static std::function<PerformceAllocScene*()> createFunctions[] =
{
CL(NodeCreateTest),
CL(NodeDeallocTest),
CL(SpriteCreateEmptyTest),
CL(SpriteCreateTest),
CL(SpriteDeallocTest),
};
#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))
enum {
kTagInfoLayer = 1,
kTagBase = 20000,
};
enum {
kMaxNodes = 15000,
kNodesIncrease = 500,
};
static int g_curCase = 0;
////////////////////////////////////////////////////////
//
// AllocBasicLayer
//
////////////////////////////////////////////////////////
AllocBasicLayer::AllocBasicLayer(bool bControlMenuVisible, int nMaxCases, int nCurCase)
: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase)
{
}
void AllocBasicLayer::showCurrentTest()
{
int nodes = ((PerformceAllocScene*)getParent())->getQuantityOfNodes();
auto scene = createFunctions[_curCase]();
g_curCase = _curCase;
if (scene)
{
scene->initWithQuantityOfNodes(nodes);
Director::getInstance()->replaceScene(scene);
scene->release();
}
}
////////////////////////////////////////////////////////
//
// PerformceAllocScene
//
////////////////////////////////////////////////////////
void PerformceAllocScene::initWithQuantityOfNodes(unsigned int nNodes)
{
//srand(time());
auto s = Director::getInstance()->getWinSize();
// Title
auto label = LabelTTF::create(title().c_str(), "Arial", 40);
addChild(label, 1);
label->setPosition(Point(s.width/2, s.height-32));
label->setColor(Color3B(255,255,40));
// Subtitle
std::string strSubTitle = subtitle();
if(strSubTitle.length())
{
auto l = LabelTTF::create(strSubTitle.c_str(), "Thonburi", 16);
addChild(l, 1);
l->setPosition(Point(s.width/2, s.height-80));
}
lastRenderedCount = 0;
currentQuantityOfNodes = 0;
quantityOfNodes = nNodes;
MenuItemFont::setFontSize(65);
auto decrease = MenuItemFont::create(" - ", [&](Object *sender) {
quantityOfNodes -= kNodesIncrease;
if( quantityOfNodes < 0 )
quantityOfNodes = 0;
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
CC_PROFILER_PURGE_ALL();
srand(0);
});
decrease->setColor(Color3B(0,200,20));
auto increase = MenuItemFont::create(" + ", [&](Object *sender) {
quantityOfNodes += kNodesIncrease;
if( quantityOfNodes > kMaxNodes )
quantityOfNodes = kMaxNodes;
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
CC_PROFILER_PURGE_ALL();
srand(0);
});
increase->setColor(Color3B(0,200,20));
auto menu = Menu::create(decrease, increase, NULL);
menu->alignItemsHorizontally();
menu->setPosition(Point(s.width/2, s.height/2+15));
addChild(menu, 1);
auto infoLabel = LabelTTF::create("0 nodes", "Marker Felt", 30);
infoLabel->setColor(Color3B(0,200,20));
infoLabel->setPosition(Point(s.width/2, s.height/2-15));
addChild(infoLabel, 1, kTagInfoLayer);
auto menuLayer = new AllocBasicLayer(true, MAX_LAYER, g_curCase);
addChild(menuLayer);
menuLayer->release();
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
srand(0);
}
std::string PerformceAllocScene::title()
{
return "No title";
}
std::string PerformceAllocScene::subtitle()
{
return "";
}
void PerformceAllocScene::updateQuantityLabel()
{
if( quantityOfNodes != lastRenderedCount )
{
auto infoLabel = static_cast<LabelTTF*>( getChildByTag(kTagInfoLayer) );
char str[20] = {0};
sprintf(str, "%u nodes", quantityOfNodes);
infoLabel->setString(str);
lastRenderedCount = quantityOfNodes;
}
}
const char * PerformceAllocScene::profilerName()
{
return _profilerName;
}
void PerformceAllocScene::updateProfilerName()
{
snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), quantityOfNodes);
}
void PerformceAllocScene::onExitTransitionDidStart()
{
Scene::onExitTransitionDidStart();
auto director = Director::getInstance();
auto sched = director->getScheduler();
sched->unscheduleSelector(SEL_SCHEDULE(&PerformceAllocScene::dumpProfilerInfo), this);
}
void PerformceAllocScene::onEnterTransitionDidFinish()
{
Scene::onEnterTransitionDidFinish();
auto director = Director::getInstance();
auto sched = director->getScheduler();
CC_PROFILER_PURGE_ALL();
sched->scheduleSelector(SEL_SCHEDULE(&PerformceAllocScene::dumpProfilerInfo), this, 2, false);
}
void PerformceAllocScene::dumpProfilerInfo(float dt)
{
CC_PROFILER_DISPLAY_TIMERS();
}
////////////////////////////////////////////////////////
//
// NodeCreateTest
//
////////////////////////////////////////////////////////
void NodeCreateTest::updateQuantityOfNodes()
{
currentQuantityOfNodes = quantityOfNodes;
}
void NodeCreateTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Node: %lu\n", sizeof(Node));
scheduleUpdate();
}
void NodeCreateTest::update(float dt)
{
// iterate using fast enumeration protocol
Node **nodes = new Node*[quantityOfNodes];
CC_PROFILER_START(this->profilerName());
for( int i=0; i<quantityOfNodes; ++i)
nodes[i] = Node::create();
CC_PROFILER_STOP(this->profilerName());
delete [] nodes;
}
std::string NodeCreateTest::title()
{
return "Node Create Perf test.";
}
std::string NodeCreateTest::subtitle()
{
return "Node Create Perf test. See console";
}
const char* NodeCreateTest::testName()
{
return "Node::create()";
}
////////////////////////////////////////////////////////
//
// NodeDeallocTest
//
////////////////////////////////////////////////////////
void NodeDeallocTest::updateQuantityOfNodes()
{
currentQuantityOfNodes = quantityOfNodes;
}
void NodeDeallocTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Node: %lu\n", sizeof(Node));
scheduleUpdate();
}
void NodeDeallocTest::update(float dt)
{
// iterate using fast enumeration protocol
Node **nodes = new Node*[quantityOfNodes];
for( int i=0; i<quantityOfNodes; ++i) {
nodes[i] = new Node;
nodes[i]->init();
}
CC_PROFILER_START(this->profilerName());
for( int i=0; i<quantityOfNodes; ++i)
nodes[i]->release();
CC_PROFILER_STOP(this->profilerName());
delete [] nodes;
}
std::string NodeDeallocTest::title()
{
return "Node Dealloc Perf test.";
}
std::string NodeDeallocTest::subtitle()
{
return "Node Dealloc Perf test. See console";
}
const char* NodeDeallocTest::testName()
{
return "Node::~Node()";
}
////////////////////////////////////////////////////////
//
// SpriteCreateEmptyTest
//
////////////////////////////////////////////////////////
void SpriteCreateEmptyTest::updateQuantityOfNodes()
{
currentQuantityOfNodes = quantityOfNodes;
}
void SpriteCreateEmptyTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Sprite: %lu\n", sizeof(Sprite));
scheduleUpdate();
}
void SpriteCreateEmptyTest::update(float dt)
{
// iterate using fast enumeration protocol
Sprite **sprites = new Sprite*[quantityOfNodes];
Sprite::create("Images/grossini.png");
CC_PROFILER_START(this->profilerName());
for( int i=0; i<quantityOfNodes; ++i)
sprites[i] = Sprite::create();
CC_PROFILER_STOP(this->profilerName());
delete [] sprites;
}
std::string SpriteCreateEmptyTest::title()
{
return "Create Empty Sprite";
}
std::string SpriteCreateEmptyTest::subtitle()
{
return "Create Empty Sprite Perf test. See console";
}
const char* SpriteCreateEmptyTest::testName()
{
return "Sprite::create(void)";
}
////////////////////////////////////////////////////////
//
// SpriteCreateTest
//
////////////////////////////////////////////////////////
void SpriteCreateTest::updateQuantityOfNodes()
{
currentQuantityOfNodes = quantityOfNodes;
}
void SpriteCreateTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of Sprite: %lu\n", sizeof(Sprite));
scheduleUpdate();
}
void SpriteCreateTest::update(float dt)
{
// iterate using fast enumeration protocol
Sprite **sprites = new Sprite*[quantityOfNodes];
Sprite::create("Images/grossini.png");
CC_PROFILER_START(this->profilerName());
for( int i=0; i<quantityOfNodes; ++i)
sprites[i] = Sprite::create("Images/grossini.png");
CC_PROFILER_STOP(this->profilerName());
delete [] sprites;
}
std::string SpriteCreateTest::title()
{
return "Create Sprite";
}
std::string SpriteCreateTest::subtitle()
{
return "Create Empty Sprite. See console";
}
const char* SpriteCreateTest::testName()
{
return "Sprite::create(\"image\")";
}
////////////////////////////////////////////////////////
//
// SpriteDeallocTest
//
////////////////////////////////////////////////////////
void SpriteDeallocTest::updateQuantityOfNodes()
{
currentQuantityOfNodes = quantityOfNodes;
}
void SpriteDeallocTest::initWithQuantityOfNodes(unsigned int nNodes)
{
PerformceAllocScene::initWithQuantityOfNodes(nNodes);
printf("Size of sprite: %lu\n", sizeof(Sprite));
scheduleUpdate();
}
void SpriteDeallocTest::update(float dt)
{
// iterate using fast enumeration protocol
Sprite **sprites = new Sprite*[quantityOfNodes];
for( int i=0; i<quantityOfNodes; ++i) {
sprites[i] = new Sprite;
sprites[i]->init();
}
CC_PROFILER_START(this->profilerName());
for( int i=0; i<quantityOfNodes; ++i)
sprites[i]->release();
CC_PROFILER_STOP(this->profilerName());
delete [] sprites;
}
std::string SpriteDeallocTest::title()
{
return "Sprite Dealloc Perf test.";
}
std::string SpriteDeallocTest::subtitle()
{
return "Sprite Dealloc Perf test. See console";
}
const char* SpriteDeallocTest::testName()
{
return "Sprite::~Sprite()";
}
///----------------------------------------
void runAllocPerformanceTest()
{
auto scene = createFunctions[g_curCase]();
scene->initWithQuantityOfNodes(kNodesIncrease);
Director::getInstance()->replaceScene(scene);
scene->release();
}

View File

@ -0,0 +1,112 @@
/*
*
*/
#ifndef __PERFORMANCE_ALLOC_TEST_H__
#define __PERFORMANCE_ALLOC_TEST_H__
#include "PerformanceTest.h"
#include "support/CCProfiling.h"
class AllocBasicLayer : public PerformBasicLayer
{
public:
AllocBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0);
virtual void showCurrentTest();
};
class PerformceAllocScene : public Scene
{
public:
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual std::string title();
virtual std::string subtitle();
virtual void updateQuantityOfNodes() = 0;
const char* profilerName();
void updateProfilerName();
// for the profiler
virtual const char* testName() = 0;
void updateQuantityLabel();
int getQuantityOfNodes() { return quantityOfNodes; }
void dumpProfilerInfo(float dt);
// overrides
virtual void onExitTransitionDidStart() override;
virtual void onEnterTransitionDidFinish() override;
protected:
char _profilerName[256];
int lastRenderedCount;
int quantityOfNodes;
int currentQuantityOfNodes;
};
class NodeCreateTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class NodeDeallocTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class SpriteCreateEmptyTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class SpriteCreateTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class SpriteDeallocTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
void runAllocPerformanceTest();
#endif // __PERFORMANCE_ALLOC_TEST_H__

View File

@ -153,7 +153,7 @@ void NodeChildrenMainScene::initWithQuantityOfNodes(unsigned int nNodes)
updateQuantityOfNodes();
updateProfilerName();
CC_PROFILER_PURGE_ALL();
srandom(0);
srand(0);
});
decrease->setColor(Color3B(0,200,20));
auto increase = MenuItemFont::create(" + ", [&](Object *sender) {
@ -165,7 +165,7 @@ void NodeChildrenMainScene::initWithQuantityOfNodes(unsigned int nNodes)
updateQuantityOfNodes();
updateProfilerName();
CC_PROFILER_PURGE_ALL();
srandom(0);
srand(0);
});
increase->setColor(Color3B(0,200,20));
@ -186,7 +186,7 @@ void NodeChildrenMainScene::initWithQuantityOfNodes(unsigned int nNodes)
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
srandom(0);
srand(0);
}
std::string NodeChildrenMainScene::title()

View File

@ -5,6 +5,7 @@
#include "PerformanceSpriteTest.h"
#include "PerformanceTextureTest.h"
#include "PerformanceTouchesTest.h"
#include "PerformanceAllocTest.h"
enum
{
@ -17,11 +18,12 @@ struct {
std::function<void(Object*)> callback;
} g_testsName[] =
{
{ "PerformanceNodeChildrenTest", [](Object*sender){runNodeChildrenTest();} },
{ "PerformanceParticleTest",[](Object*sender){runParticleTest();} },
{ "PerformanceSpriteTest",[](Object*sender){runSpriteTest();} },
{ "PerformanceTextureTest",[](Object*sender){runTextureTest();} },
{ "PerformanceTouchesTest",[](Object*sender){runTouchesTest();} },
{ "Alloc Test", [](Object*sender){runAllocPerformanceTest(); } },
{ "NodeChildren Test", [](Object*sender){runNodeChildrenTest();} },
{ "Particle Test",[](Object*sender){runParticleTest();} },
{ "Sprite Perf Test",[](Object*sender){runSpriteTest();} },
{ "Texture Perf Test",[](Object*sender){runTextureTest();} },
{ "Touches Perf Test",[](Object*sender){runTouchesTest();} },
};
static const int g_testMax = sizeof(g_testsName)/sizeof(g_testsName[0]);

View File

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

View File

@ -73,6 +73,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/NodeTest/NodeTest.cpp \
../Classes/ParallaxTest/ParallaxTest.cpp \
../Classes/ParticleTest/ParticleTest.cpp \
../Classes/PerformanceTest/PerformanceAllocTest.cpp \
../Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \
../Classes/PerformanceTest/PerformanceParticleTest.cpp \
../Classes/PerformanceTest/PerformanceSpriteTest.cpp \

View File

@ -157,6 +157,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O
<ClCompile Include="..\Classes\ExtensionsTest\TableViewTest\TableViewTestScene.cpp" />
<ClCompile Include="..\Classes\FileUtilsTest\FileUtilsTest.cpp" />
<ClCompile Include="..\Classes\LabelTest\LabelTestNew.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceAllocTest.cpp" />
<ClCompile Include="..\Classes\SpineTest\SpineTest.cpp" />
<ClCompile Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.cpp" />
<ClCompile Include="..\Classes\VisibleRect.cpp" />

View File

@ -555,6 +555,9 @@
<ClCompile Include="..\Classes\LabelTest\LabelTestNew.cpp">
<Filter>Classes\LabelTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\PerformanceTest\PerformanceAllocTest.cpp">
<Filter>Classes\PerformanceTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">

View File

@ -1 +1 @@
03e60de189259aa934135a3492ddbe49112cda61
fe014a4c9bc5fb6471d516b0e288b0287708c53c

@ -1 +1 @@
Subproject commit f966a8fc67e1a388b167c8b56279ff3e444b3351
Subproject commit e57e43aaf1aea16ecefad50de1c7db8c401468a5