static void array_Value(CCArray * aArray, const cocos2d::ValueVector & value) { cocos2d::ValueVector::const_iterator beg = value.begin(); cocos2d::ValueVector::const_iterator end = value.end(); for (; beg != end; ++beg) { const Value & v = *beg; if (v.getType() == Value::Type::MAP) { CCDictionary * dict = new CCDictionary(); dict->init(); dictionary_Value(dict, v.asValueMap()); aArray->addObject(dict); dict->release(); } else if (v.getType() == Value::Type::VECTOR) { CCArray * arr = new CCArray(); arr->init(); array_Value(arr, v.asValueVector()); aArray->addObject(arr); arr->release(); } else { CCString * str = new CCString(); if (v.getType() == Value::Type::DOUBLE) str->initWithFormat("%f", v.asDouble()); else str->initWithFormat("%s", v.asString().c_str()); aArray->addObject(str); str->release(); } } }
void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, CCTexture2D *pobTexture) { const char *pszPath = CCFileUtils::fullPathFromRelativePath(pszPlist); CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath); addSpriteFramesWithDictionary(dict, pobTexture); dict->release(); }
void CCSpriteFrameCache::removeSpriteFramesFromFile(const char* plist) { const char* path = CCFileUtils::fullPathFromRelativePath(plist); CCDictionary<std::string, CCObject*>* dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(path); removeSpriteFramesFromDictionary((CCDictionary<std::string, CCSpriteFrame*>*)dict); dict->release(); }
bool CCParticleSystem::initWithFile(const char *plistFile) { bool bRet = false; m_sPlistFile = CCFileUtils::fullPathFromRelativePath(plistFile); CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(m_sPlistFile.c_str()); CCAssert( dict != NULL, "Particles: file not found"); bRet = this->initWithDictionary(dict); dict->release(); return bRet; }
bool CCParticleSystem::initWithFile(const char *plistFile) { bool bRet = false; m_sPlistFile = CCFileUtils::sharedFileUtils()->fullPathForFilename(plistFile); CCDictionary *dict = CCDictionary::createWithContentsOfFileThreadSafe(m_sPlistFile.c_str()); CCAssert( dict != NULL, "Particles: file not found"); bRet = this->initWithDictionary(dict); dict->release(); return bRet; }
static int tolua_Cocos2dx_CCTableView_registerScriptHandler(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"CCTableView",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnumber(tolua_S, 3, 0, &tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else #endif { CCTableView* self = (CCTableView*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'registerScriptHandler'", NULL); #endif if (NULL == self->getDelegate()) { LUA_TableViewDelegate* delegate = new LUA_TableViewDelegate(); if (NULL == delegate) return 0; CCDictionary* userDict = static_cast<CCDictionary*>(self->getUserObject()); if (NULL == userDict) { userDict = new CCDictionary(); if (NULL == userDict) return 0; self->setUserObject(userDict); userDict->release(); } userDict->setObject(delegate, KEY_TABLEVIEW_DELEGATE); self->setDelegate(delegate); delegate->release(); } LUA_FUNCTION nFunID = ( toluafix_ref_function(tolua_S,2,0)); int scriptHandlerType = ((int) tolua_tonumber(tolua_S,3,0)); self->registerScriptHandler(nFunID,scriptHandlerType); } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'registerScriptHandler'.",&tolua_err); return 0; #endif }
void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *_plistPath, const char *_imagePath) { std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(_plistPath); CCDictionary *dict = CCDictionary::createWithContentsOfFileThreadSafe(path.c_str()); CCTexture2D *pobTexture = CCTextureCache::sharedTextureCache()->addImage(_imagePath); addSpriteFrameFromDict(dict, pobTexture, _imagePath); dict->release(); }
void startElement(void *ctx, const XML_Char *name, const XML_Char **atts) { std::string sName((char*)name); if( sName == "dict" ) { CCDictionary<std::string, CCObject*> *pNewDict = new CCDictionary<std::string, CCObject*>(); if(! m_pRootDict) { m_pRootDict = pNewDict; pNewDict->autorelease(); } else { CCAssert(m_pCurDict && !m_sCurKey.empty(), ""); m_pCurDict->setObject(pNewDict, m_sCurKey); pNewDict->release(); m_sCurKey.clear(); } m_pCurDict = pNewDict; m_tDictStack.push(m_pCurDict); m_tState = SAX_DICT; } else if(sName == "key") { m_tState = SAX_KEY; } else if(sName == "integer") { m_tState = SAX_INT; } else if(sName == "real") { m_tState = SAX_REAL; } else if(sName == "string") { m_tState = SAX_STRING; } else { if (sName == "array") { m_bInArray = true; m_pArray = new CCMutableArray<CCObject*>(); } m_tState = SAX_NONE; } }
void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) { const char *pszPath = CCFileUtils::fullPathFromRelativePath(pszPlist); CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath); string texturePath(""); CCDictionary<std::string, CCObject*>* metadataDict = (CCDictionary<std::string, CCObject*>*)dict->objectForKey(string("metadata")); if (metadataDict) { // try to read texture file name from meta data texturePath = string(valueForKey("textureFileName", metadataDict)); } if (! texturePath.empty()) { // build texture path relative to plist file texturePath = CCFileUtils::fullPathFromRelativeFile(texturePath.c_str(), pszPath); } else { // build texture path by replacing file extension texturePath = pszPath; // remove .xxx size_t startPos = texturePath.find_last_of("."); texturePath = texturePath.erase(startPos); // append .png texturePath = texturePath.append(".png"); CCLOG("cocos2d: CCSpriteFrameCache: Trying to use file %s as texture", texturePath.c_str()); } CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage(texturePath.c_str()); if (pTexture) { addSpriteFramesWithDictionary(dict, pTexture); } else { CCLOG("cocos2d: CCSpriteFrameCache: Couldn't load texture"); } dict->release(); }
static int tolua_Cocos2dx_CCTableView_setDataSource(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"CCTableView",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { CCTableView* self = (CCTableView*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'setDataSource'", NULL); #endif LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); if (NULL == dataSource) return 0; CCDictionary* userDict = static_cast<CCDictionary*>(self->getUserObject()); if (NULL == userDict) { userDict = new CCDictionary(); if (NULL == userDict) return 0; self->setUserObject(userDict); userDict->release(); } userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); self->setDataSource(dataSource); dataSource->release(); return 0; } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'setDataSource'.",&tolua_err); return 0; #endif }
static int tolua_Cocos2dx_CCTableView_create00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S, 1, "CCTableView", 0, &tolua_err) || !tolua_isusertype(tolua_S, 2, "CCSize", 0, &tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); if (NULL == dataSource) return 0; CCSize size = *((CCSize*) tolua_tousertype(tolua_S,2,0)); CCTableView* tolua_ret = CCTableView::create(dataSource, size); if (NULL == tolua_ret) return 0; tolua_ret->reloadData(); CCDictionary* userDict = new CCDictionary(); userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); tolua_ret->setUserObject(userDict); userDict->release(); dataSource->release(); int nID = (int)tolua_ret->m_uID; int* pLuaID = &tolua_ret->m_nLuaID; toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCTableView"); return 1; } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'create'.",&tolua_err); return 0; #endif }
//------------------------------------------------------------------------- // 加载贴图 void FKAnimateExRes::_LoadTextureAsync( const char* szResName ) { string strPathName = CCFileUtils::sharedFileUtils()->fullPathForFilename( szResName ); if( !m_SaxParser.init("UTF-8") ) return; m_SaxParser.setDelegator( &m_SaxDelegator ); if( !m_SaxParser.parse( strPathName.c_str() ) ) return; vector<string> vecPlists = m_SaxDelegator.m_vecPlists; for( unsigned int i = 0; i < vecPlists.size(); ++i ) { string strFullPath = CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile( vecPlists[i].c_str(), strPathName.c_str() ); CCDictionary *pDict = CCDictionary::createWithContentsOfFileThreadSafe( strFullPath.c_str() ); if( pDict == NULL ) continue; string strTexturePath(""); CCDictionary* pMetadataDict = (CCDictionary*)pDict->objectForKey("metadata"); if( pMetadataDict ) strTexturePath = pMetadataDict->valueForKey("textureFileName")->getCString(); if( !strTexturePath.empty() ) { strTexturePath = CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile( strTexturePath.c_str(), strPathName.c_str() ); } else { strTexturePath = vecPlists[i].c_str(); size_t unStartPos = strTexturePath.find_last_of("."); strTexturePath = strTexturePath.erase( unStartPos ); strTexturePath = strTexturePath.append(".png"); } pDict->release(); m_mapTextureLoadInfo[strTexturePath] = false; CCTextureCache::sharedTextureCache()->addImageAsync( strTexturePath.c_str(),this, callfuncO_selector(FKAnimateExRes::_OnImageLoadOver) ); } }
void plist_startElement(void *ctx, const xmlChar *name, const xmlChar **atts) { CCDictMaker *pMaker = (CCDictMaker*)(ctx); std::string sName((char*)name); if( sName == "dict" ) { CCDictionary<std::string, CCObject*> *pNewDict = new CCDictionary<std::string, CCObject*>(); if(! pMaker->m_pRootDict) { pMaker->m_pRootDict = pNewDict; pNewDict->autorelease(); } else { CCAssert(pMaker->m_pCurDict && !pMaker->m_sCurKey.empty(), ""); pMaker->m_pCurDict->setObject(pNewDict, pMaker->m_sCurKey); pNewDict->release(); pMaker->m_sCurKey.clear(); } pMaker->m_pCurDict = pNewDict; pMaker->m_tDictStack.push(pMaker->m_pCurDict); pMaker->m_tState = SAX_DICT; } else if(sName == "key") { pMaker->m_tState = SAX_KEY; } else if(sName == "integer") { pMaker->m_tState = SAX_INT; } else if(sName == "real") { pMaker->m_tState = SAX_REAL; } else if(sName == "string") { pMaker->m_tState = SAX_STRING; } else { pMaker->m_tState = SAX_NONE; } }
static int tolua_Cocos2dx_CCTableView_create01(lua_State* tolua_S) { tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"CCTableView",0,&tolua_err) || !tolua_isusertype(tolua_S, 2, "CCSize", 0, &tolua_err) || !tolua_isusertype(tolua_S,3,"CCNode",0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else { LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); if (NULL == dataSource) return 0; CCSize size = *((CCSize*) tolua_tousertype(tolua_S,2,0)); CCNode* node = static_cast<CCNode*>(tolua_tousertype(tolua_S, 3, 0)); CCTableView* tolua_ret = CCTableView::create(dataSource,size,node); if (NULL == tolua_ret) return 0; tolua_ret->reloadData(); CCDictionary* userDict = new CCDictionary(); userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); tolua_ret->setUserObject(userDict); userDict->release(); dataSource->release(); int nID = (int)tolua_ret->m_uID; int* pLuaID = &tolua_ret->m_nLuaID; toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCTableView"); return 1; } return 0; tolua_lerror: return tolua_Cocos2dx_CCTableView_create00(tolua_S); }
int CCPreLoad::addSingle(const char* pic, int type, int size) { int ret = -1; CCDictionary* dic = new CCDictionary(); CCString* str = new CCString(); CCString* str1 = new CCString(); do{ str->initWithFormat("%d", type); str1->initWithFormat("%d", size); dic->setObject(str1, "size"); dic->setObject(str, "type"); m_dict->setObject(dic, pic); ret = 0; }while(0); dic->release(); str->release(); str1->release(); return ret; }
JNIEXPORT void JNICALL Java_cn_sharesdk_ShareSDKUtils_onJavaCallback (JNIEnv * env, jclass thiz, jstring resp) { CCJSONConverter* json = CCJSONConverter::sharedConverter(); const char* ccResp = env->GetStringUTFChars(resp, JNI_FALSE); CCLog("ccResp = %s", ccResp); CCDictionary* dic = json->dictionaryFrom(ccResp); env->ReleaseStringUTFChars(resp, ccResp); CCNumber* status = (CCNumber*) dic->objectForKey("status"); // Success = 1, Fail = 2, Cancel = 3 CCNumber* action = (CCNumber*) dic->objectForKey("action"); // 1 = ACTION_AUTHORIZING, 8 = ACTION_USER_INFOR,9 = ACTION_SHARE CCNumber* platform = (CCNumber*) dic->objectForKey("platform"); CCDictionary* res = (CCDictionary*) dic->objectForKey("res"); // TODO add codes here if(1 == status->getIntValue()){ callBackComplete(action->getIntValue(), platform->getIntValue(), res); }else if(2 == status->getIntValue()){ callBackError(action->getIntValue(), platform->getIntValue(), res); }else{ callBackCancel(action->getIntValue(), platform->getIntValue(), res); } dic->release(); }
bool CCParticleSystem::initWithFileFullPath(const char *plistFile) { bool bRet = false; CCDictionary *dict = CCDictionary::createWithContentsOfFileThreadSafe(plistFile); CCAssert( dict != NULL, "Particles: file not found"); // XXX compute path from a path, should define a function somewhere to do it string listFilePath = plistFile; if (listFilePath.find('/') != string::npos) { listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); bRet = this->initWithDictionary(dict, listFilePath.c_str()); } else { bRet = this->initWithDictionary(dict, ""); } dict->release(); return bRet; }
static void dictionary_Value(CCDictionary * aDict, const cocos2d::ValueMap & value) { cocos2d::ValueMap::const_iterator beg = value.begin(); cocos2d::ValueMap::const_iterator end = value.end(); for (; beg != end; ++beg) { const std::string & key = (*beg).first; const cocos2d::Value & v = (*beg).second; if (v.getType() == Value::Type::MAP) { CCDictionary * d = new CCDictionary(); d->init(); dictionary_Value(d, v.asValueMap()); aDict->setObject(d, key); d->release(); } else if (v.getType() == Value::Type::VECTOR) { CCArray * a = new CCArray(); a->init(); array_Value(a, v.asValueVector()); aDict->setObject(a, key); a->release(); } else { CCString * str = new CCString(); if (v.getType() == Value::Type::DOUBLE) str->initWithFormat("%f", v.asDouble()); else str->initWithFormat("%s", v.asString().c_str()); aDict->setObject(str, key); str->release(); } } }
void startElement(void *ctx, const char *name, const char **atts) { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(atts); std::string sName((char*)name); if( sName == "dict" ) { m_pCurDict = new CCDictionary(); if (m_eResultType == SAX_RESULT_DICT && ! m_pRootDict) { // Because it will call m_pCurDict->release() later, so retain here. m_pRootDict = m_pCurDict; m_pRootDict->retain(); } m_tState = SAX_DICT; CCSAXState preState = SAX_NONE; if (! m_tStateStack.empty()) { preState = m_tStateStack.top(); } if (SAX_ARRAY == preState) { // add the dictionary into the array m_pArray->addObject(m_pCurDict); } else if (SAX_DICT == preState) { // add the dictionary into the pre dictionary CCAssert(! m_tDictStack.empty(), "The state is wrong!"); CCDictionary* pPreDict = m_tDictStack.top(); pPreDict->setObject(m_pCurDict, m_sCurKey); } m_pCurDict->release(); // record the dict state m_tStateStack.push(m_tState); m_tDictStack.push(m_pCurDict); } else if(sName == "key") { m_tState = SAX_KEY; } else if(sName == "integer") { m_tState = SAX_INT; } else if(sName == "real") { m_tState = SAX_REAL; } else if(sName == "string") { m_tState = SAX_STRING; } else if (sName == "array") { m_tState = SAX_ARRAY; m_pArray = new CCArray(); if (m_eResultType == SAX_RESULT_ARRAY && m_pRootArray == NULL) { m_pRootArray = m_pArray; m_pRootArray->retain(); } CCSAXState preState = SAX_NONE; if (! m_tStateStack.empty()) { preState = m_tStateStack.top(); } //CCSAXState preState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top(); if (preState == SAX_DICT) { m_pCurDict->setObject(m_pArray, m_sCurKey); } else if (preState == SAX_ARRAY) { CCAssert(! m_tArrayStack.empty(), "The state is worng!"); CCArray* pPreArray = m_tArrayStack.top(); pPreArray->addObject(m_pArray); } m_pArray->release(); // record the array state m_tStateStack.push(m_tState); m_tArrayStack.push(m_pArray); } else { m_tState = SAX_NONE; } }
void AsyncLoadPlist::loadPlistAsync(const char *pszPlist, cocos2d::CCObject *target, SEL_CallFuncO selector) { CCAssert(pszPlist, "plist filename should not be NULL"); // 读取plist数据,获得图片路径 const char *pszPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pszPlist).c_str(); CCDictionary *dict = CCDictionary::createWithContentsOfFileThreadSafe(pszPath); std::string texturePath(""); CCDictionary* metadataDict = (CCDictionary*)dict->objectForKey("metadata"); if (metadataDict) { // try to read texture file name from meta data texturePath = metadataDict->valueForKey("textureFileName")->getCString(); } // CCDictionary::createWithContentsOfFileThreadSafe 需要释放dict dict->release(); if (! texturePath.empty()) { // build texture path relative to plist file texturePath = CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile(texturePath.c_str(), pszPath); } else { CCAssert(0, "在plist文件中没有找到图片文件"); return; } // 从texturePath中取文件名 如/../../filename.png 则filename.png std::string textureFileName = texturePath.substr(texturePath.rfind('/') + 1); // 从TextureCache中找到纹理就直接返回 CCTexture2D *texture = CCTextureCache::sharedTextureCache()->textureForKey(textureFileName.c_str()); if (texture != NULL) { if (target && selector) { (target->*selector)(CCString::create(pszPlist)); } return; } // lazy init if (s_pSem == NULL) { #if CC_ASYNC_TEXTURE_CACHE_USE_NAMED_SEMAPHORE s_pSem = sem_open(CC_ASYNC_TEXTURE_CACHE_SEMAPHORE, O_CREAT, 0644, 0); if( s_pSem == SEM_FAILED ) { CCLOG( "CCTextureCache async thread semaphore init error: %s\n", strerror( errno ) ); s_pSem = NULL; return; } #else int semInitRet = sem_init(&s_sem, 0, 0); if( semInitRet < 0 ) { CCLOG( "CCTextureCache async thread semaphore init error: %s\n", strerror( errno ) ); return; } s_pSem = &s_sem; #endif s_pLoadStructQueue = new std::queue<LoadStruct*>(); s_pImageQueue = new std::queue<ImageInfo*>(); pthread_mutex_init(&s_loadStructQueueMutex, NULL); pthread_mutex_init(&s_ImageInfoMutex, NULL); pthread_create(&s_loadingThread, NULL, loadImage, NULL); need_quit = false; } if (0 == s_nAsyncRefCount) { CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(AsyncLoadPlist::loadPlistAsyncCallBack), this, 0, false); } ++s_nAsyncRefCount; if (target) { target->retain(); } // generate async struct LoadStruct *data = new LoadStruct(); data->texturePath = texturePath.c_str(); data->plistFileName = pszPlist; data->target = target; data->selector = selector; // add async struct into queue pthread_mutex_lock(&s_loadStructQueueMutex); s_pLoadStructQueue->push(data); pthread_mutex_unlock(&s_loadStructQueueMutex); sem_post(s_pSem); }
// the XML parser calls here with all the elements void CCTMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { CC_UNUSED_PARAM(ctx); CCTMXMapInfo *pTMXMapInfo = this; std::string elementName = (char*)name; std::map<std::string, std::string> *attributeDict = new std::map<std::string, std::string>(); if (atts && atts[0]) { for(int i = 0; atts[i]; i += 2) { std::string key = (char*)atts[i]; std::string value = (char*)atts[i+1]; attributeDict->insert(pair<std::string, std::string>(key, value)); } } if (elementName == "map") { std::string version = valueForKey("version", attributeDict); if ( version != "1.0") { CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str()); } std::string orientationStr = valueForKey("orientation", attributeDict); if (orientationStr == "orthogonal") pTMXMapInfo->setOrientation(CCTMXOrientationOrtho); else if (orientationStr == "isometric") pTMXMapInfo->setOrientation(CCTMXOrientationIso); else if(orientationStr == "hexagonal") pTMXMapInfo->setOrientation(CCTMXOrientationHex); else CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", pTMXMapInfo->getOrientation()); CCSize s; s.width = (float)atof(valueForKey("width", attributeDict)); s.height = (float)atof(valueForKey("height", attributeDict)); pTMXMapInfo->setMapSize(s); s.width = (float)atof(valueForKey("tilewidth", attributeDict)); s.height = (float)atof(valueForKey("tileheight", attributeDict)); pTMXMapInfo->setTileSize(s); // The parent element is now "map" pTMXMapInfo->setParentElement(TMXPropertyMap); } else if (elementName == "tileset") { // If this is an external tileset then start parsing that std::string externalTilesetFilename = valueForKey("source", attributeDict); if (externalTilesetFilename != "") { // Tileset file will be relative to the map file. So we need to convert it to an absolute path if (m_sTMXFileName.find_last_of("/") != string::npos) { string dir = m_sTMXFileName.substr(0, m_sTMXFileName.find_last_of("/") + 1); externalTilesetFilename = dir + externalTilesetFilename; } else { externalTilesetFilename = m_sResources + "/" + externalTilesetFilename; } externalTilesetFilename = CCFileUtils::sharedFileUtils()->fullPathForFilename(externalTilesetFilename.c_str()); m_uCurrentFirstGID = (unsigned int)atoi(valueForKey("firstgid", attributeDict)); pTMXMapInfo->parseXMLFile(externalTilesetFilename.c_str()); } else { CCTMXTilesetInfo *tileset = new CCTMXTilesetInfo(); tileset->m_sName = valueForKey("name", attributeDict); if (m_uCurrentFirstGID == 0) { tileset->m_uFirstGid = (unsigned int)atoi(valueForKey("firstgid", attributeDict)); } else { tileset->m_uFirstGid = m_uCurrentFirstGID; m_uCurrentFirstGID = 0; } tileset->m_uSpacing = (unsigned int)atoi(valueForKey("spacing", attributeDict)); tileset->m_uMargin = (unsigned int)atoi(valueForKey("margin", attributeDict)); CCSize s; s.width = (float)atof(valueForKey("tilewidth", attributeDict)); s.height = (float)atof(valueForKey("tileheight", attributeDict)); tileset->m_tTileSize = s; pTMXMapInfo->getTilesets()->addObject(tileset); tileset->release(); } } else if (elementName == "tile") { CCTMXTilesetInfo* info = (CCTMXTilesetInfo*)pTMXMapInfo->getTilesets()->lastObject(); CCDictionary *dict = new CCDictionary(); pTMXMapInfo->setParentGID(info->m_uFirstGid + atoi(valueForKey("id", attributeDict))); pTMXMapInfo->getTileProperties()->setObject(dict, pTMXMapInfo->getParentGID()); CC_SAFE_RELEASE(dict); pTMXMapInfo->setParentElement(TMXPropertyTile); } else if (elementName == "layer") { CCTMXLayerInfo *layer = new CCTMXLayerInfo(); layer->m_sName = valueForKey("name", attributeDict); CCSize s; s.width = (float)atof(valueForKey("width", attributeDict)); s.height = (float)atof(valueForKey("height", attributeDict)); layer->m_tLayerSize = s; std::string visible = valueForKey("visible", attributeDict); layer->m_bVisible = !(visible == "0"); std::string opacity = valueForKey("opacity", attributeDict); if( opacity != "" ) { layer->m_cOpacity = (unsigned char)(255 * atof(opacity.c_str())); } else { layer->m_cOpacity = 255; } float x = (float)atof(valueForKey("x", attributeDict)); float y = (float)atof(valueForKey("y", attributeDict)); layer->m_tOffset = ccp(x,y); pTMXMapInfo->getLayers()->addObject(layer); layer->release(); // The parent element is now "layer" pTMXMapInfo->setParentElement(TMXPropertyLayer); } else if (elementName == "objectgroup") { CCTMXObjectGroup *objectGroup = new CCTMXObjectGroup(); objectGroup->setGroupName(valueForKey("name", attributeDict)); CCPoint positionOffset; positionOffset.x = (float)atof(valueForKey("x", attributeDict)) * pTMXMapInfo->getTileSize().width; positionOffset.y = (float)atof(valueForKey("y", attributeDict)) * pTMXMapInfo->getTileSize().height; objectGroup->setPositionOffset(positionOffset); pTMXMapInfo->getObjectGroups()->addObject(objectGroup); objectGroup->release(); // The parent element is now "objectgroup" pTMXMapInfo->setParentElement(TMXPropertyObjectGroup); } else if (elementName == "image") { CCTMXTilesetInfo* tileset = (CCTMXTilesetInfo*)pTMXMapInfo->getTilesets()->lastObject(); // build full path std::string imagename = valueForKey("source", attributeDict); if (m_sTMXFileName.find_last_of("/") != string::npos) { string dir = m_sTMXFileName.substr(0, m_sTMXFileName.find_last_of("/") + 1); tileset->m_sSourceImage = dir + imagename; } else { tileset->m_sSourceImage = m_sResources + (m_sResources.size() ? "/" : "") + imagename; } } else if (elementName == "data") { std::string encoding = valueForKey("encoding", attributeDict); std::string compression = valueForKey("compression", attributeDict); if( encoding == "base64" ) { int layerAttribs = pTMXMapInfo->getLayerAttribs(); pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64); pTMXMapInfo->setStoringCharacters(true); if( compression == "gzip" ) { layerAttribs = pTMXMapInfo->getLayerAttribs(); pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip); } else if (compression == "zlib") { layerAttribs = pTMXMapInfo->getLayerAttribs(); pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib); } CCAssert( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" ); } CCAssert( pTMXMapInfo->getLayerAttribs() != TMXLayerAttribNone, "TMX tile map: Only base64 and/or gzip/zlib maps are supported" ); } else if (elementName == "object") { char buffer[32] = {0}; CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject(); // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties CCDictionary *dict = new CCDictionary(); // Parse everything automatically const char* pArray[] = {"name", "type", "width", "height", "gid"}; for(size_t i = 0; i < sizeof(pArray)/sizeof(pArray[0]); ++i ) { const char* key = pArray[i]; CCString* obj = new CCString(valueForKey(key, attributeDict)); if( obj ) { obj->autorelease(); dict->setObject(obj, key); } } // But X and Y since they need special treatment // X const char* value = valueForKey("x", attributeDict); if (value) { int x = atoi(value) + (int)objectGroup->getPositionOffset().x; sprintf(buffer, "%d", x); CCString* pStr = new CCString(buffer); pStr->autorelease(); dict->setObject(pStr, "x"); } // Y value = valueForKey("y", attributeDict); if (value) { int y = atoi(value) + (int)objectGroup->getPositionOffset().y; // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) y = (int)(m_tMapSize.height * m_tTileSize.height) - y - atoi(valueForKey("height", attributeDict)); sprintf(buffer, "%d", y); CCString* pStr = new CCString(buffer); pStr->autorelease(); dict->setObject(pStr, "y"); } // Add the object to the objectGroup objectGroup->getObjects()->addObject(dict); dict->release(); // The parent element is now "object" pTMXMapInfo->setParentElement(TMXPropertyObject); } else if (elementName == "property") { if ( pTMXMapInfo->getParentElement() == TMXPropertyNone ) { CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'", valueForKey("name", attributeDict), valueForKey("value",attributeDict) ); } else if ( pTMXMapInfo->getParentElement() == TMXPropertyMap ) { // The parent element is the map CCString *value = new CCString(valueForKey("value", attributeDict)); std::string key = valueForKey("name", attributeDict); pTMXMapInfo->getProperties()->setObject(value, key.c_str()); value->release(); } else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer ) { // The parent element is the last layer CCTMXLayerInfo* layer = (CCTMXLayerInfo*)pTMXMapInfo->getLayers()->lastObject(); CCString *value = new CCString(valueForKey("value", attributeDict)); std::string key = valueForKey("name", attributeDict); // Add the property to the layer layer->getProperties()->setObject(value, key.c_str()); value->release(); } else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup ) { // The parent element is the last object group CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject(); CCString *value = new CCString(valueForKey("value", attributeDict)); const char* key = valueForKey("name", attributeDict); objectGroup->getProperties()->setObject(value, key); value->release(); } else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject ) { // The parent element is the last object CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject(); CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject(); const char* propertyName = valueForKey("name", attributeDict); CCString *propertyValue = new CCString(valueForKey("value", attributeDict)); dict->setObject(propertyValue, propertyName); propertyValue->release(); } else if ( pTMXMapInfo->getParentElement() == TMXPropertyTile ) { CCDictionary* dict = (CCDictionary*)pTMXMapInfo->getTileProperties()->objectForKey(pTMXMapInfo->getParentGID()); const char* propertyName = valueForKey("name", attributeDict); CCString *propertyValue = new CCString(valueForKey("value", attributeDict)); dict->setObject(propertyValue, propertyName); propertyValue->release(); } } else if (elementName == "polygon") { // find parent object's dict and add polygon-points to it CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject(); CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject(); // get points value string const char* value = valueForKey("points", attributeDict); if(value) { CCArray* pPointsArray = new CCArray; // parse points string into a space-separated set of points stringstream pointsStream(value); string pointPair; while(std::getline(pointsStream, pointPair, ' ')) { // parse each point combo into a comma-separated x,y point stringstream pointStream(pointPair); string xStr,yStr; char buffer[32] = {0}; CCDictionary* pPointDict = new CCDictionary; // set x if(std::getline(pointStream, xStr, ',')) { int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x; sprintf(buffer, "%d", x); CCString* pStr = new CCString(buffer); pStr->autorelease(); pPointDict->setObject(pStr, "x"); } // set y if(std::getline(pointStream, yStr, ',')) { int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y; sprintf(buffer, "%d", y); CCString* pStr = new CCString(buffer); pStr->autorelease(); pPointDict->setObject(pStr, "y"); } // add to points array pPointsArray->addObject(pPointDict); pPointDict->release(); } dict->setObject(pPointsArray, "points"); pPointsArray->release(); } } else if (elementName == "polyline") { // find parent object's dict and add polyline-points to it // CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject(); // CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject(); // TODO: dict->setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"]; CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject(); CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject(); // get points value string const char* value = valueForKey("points", attributeDict); if(value) { CCArray* pPointsArray = new CCArray; // parse points string into a space-separated set of points stringstream pointsStream(value); string pointPair; while(std::getline(pointsStream, pointPair, ' ')) { // parse each point combo into a comma-separated x,y point stringstream pointStream(pointPair); string xStr,yStr; char buffer[32] = {0}; CCDictionary* pPointDict = new CCDictionary; // set x if(std::getline(pointStream, xStr, ',')) { int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x; sprintf(buffer, "%d", x); CCString* pStr = new CCString(buffer); pStr->autorelease(); pPointDict->setObject(pStr, "x"); } // set y if(std::getline(pointStream, yStr, ',')) { int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y; sprintf(buffer, "%d", y); CCString* pStr = new CCString(buffer); pStr->autorelease(); pPointDict->setObject(pStr, "y"); } // add to points array pPointsArray->addObject(pPointDict); pPointDict->release(); } dict->setObject(pPointsArray, "points"); pPointsArray->release(); } } if (attributeDict) { attributeDict->clear(); delete attributeDict; } }
// loads info about all tiles,sets self.contentSize & screenLoadRectExtension // creates & adds tiles for dynamic usage if batchNode void CCBigImage::prepareTilesWithFileExtensionZ(string plistFile, string extension, int tilesZ) { // load plist with image & tiles info CCDictionary *dict = CCDictionary::createWithContentsOfFile(plistFile.c_str()); if ( !dict ) { CCLOGERROR("CCBigImage#prepareTilesWithFile:extension:z: can not load dictionary from file: %s", plistFile.c_str()); return; } // load image size CCDictionary *sourceDict = (CCDictionary*)dict->objectForKey(std::string("Source")); CCSize size = CCSizeFromString(valueForKey("Size", sourceDict)); this->setContentSize(size); // load tiles CCArray* array = (CCArray*)dict->objectForKey(std::string("Tiles")); _dynamicChildren = CCArray::createWithCapacity(array->count()); _dynamicChildren->retain(); // set screenLoadRectExtension = size of first tile if (array->count()) { CCDictionary *dict_ = (CCDictionary*)array->objectAtIndex(0); _screenLoadRectExtension = CCRectFromString(valueForKey("Rect", dict_)).size; } //read data and create nodes and add them for (int i=0; i<array->count(); i++) { CCDictionary* tileDict = (CCDictionary*)array->objectAtIndex(i); // All properties of Dictionary const char *spriteName = valueForKey("Name", tileDict); CCRect tileRect = CCRectFromString(valueForKey("Rect", tileDict)); // convert rect origin from top-left to bottom-left tileRect.origin.y = this->getContentSize().height - tileRect.origin.y - tileRect.size.height; // Use forced tile extension or original if tilesExtension isn't set if (!extension.empty()) { // Change extension string filename = string(spriteName); int index = filename.find('.'); string name = filename.substr(0, index); spriteName = (name+"."+extension).c_str(); } // Create & Add Tile (Dynamic Sprite Mode) UnloadableSpriteNode* tile = UnloadableSpriteNode::nodeWithImageForRect(spriteName, tileRect); this->addChild(tile, tilesZ); _dynamicChildren->addObject(tile); } //< for dict in arr dict->release(); }