JNIEXPORT void JNICALL Java_game_mobile_infinity_FacebookManager_jniCallbackPicture(JNIEnv* env, jobject thiz, jstring jid , jbyteArray jimage) { const char *id = env->GetStringUTFChars( jid, 0); CCString* cfbID = CCString::createWithFormat("%s",id); int len = env->GetArrayLength(jimage); char* byteData = (char*)malloc(len); env->GetByteArrayRegion(jimage,0,len,(jbyte*)byteData); CCImage* imf = new CCImage(); imf->initWithImageData(byteData,len); imf->autorelease(); CCTexture2D* pTexture = new CCTexture2D(); pTexture->initWithImage(imf); pTexture->autorelease(); CCSprite *sprit = CCSprite::createWithTexture(pTexture); Facebook_Manager::sharedInstance()->Callback_Picture(cfbID, sprit); env->ReleaseStringUTFChars( jid, id); }
void CCIDefineBitsJPEG3::loadImageData(UI8 * imageData){ this->decodeInfo(imageData); int start = this->findJpegStart(imageData); imageData +=start; CCImage::EImageFormat eImageFormat = CCImage::kFmtUnKnown; CCImage image; image.initWithImageData((void*)imageData, imageSize-start, eImageFormat); if (tagLength-6-this->alphaDataOffset>0) { int length = this->width*this->height; UI8 * data = new UI8[length]; int count = 0; count = ZipUtils::ccInflateMemoryWithHint(this->bitmapAlphaData, tagLength-6-this->alphaDataOffset, &data,length); UI8 * alphaData = new UI8[count]; memcpy(alphaData,data,count); delete [] data; this->createTextureWithImageAndAlpha(&image,alphaData); delete[] alphaData; } }
cocos2d::CCSprite* CreateOBBSprite(const char *name) { //#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) && !defined KINDLE__ // std::vector<std::string> paths; // paths.push_back("/mnt/sdcard/Android/obb"); // CCFileUtils::sharedFileUtils()->setSearchPaths(paths); //#endif std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("main.1.com.LudicrousGames.MonkeyDroid.zip"); unsigned long pSize; unsigned char * pData = 0; pData = CCFileUtils::sharedFileUtils()->getFileDataFromZip(fullPath.c_str(), name, &pSize); if(pData) { CCImage* img = new CCImage(); img->initWithImageData(pData, pSize); CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addUIImage(img, name); CCSprite* sprite = CCSprite::createWithTexture(texture); return sprite; } else { return NULL; } }
void VolatileTexture::reloadAllTextures() { isReloading = true; CCLOG("reload all texture"); std::list<VolatileTexture *>::iterator i = textures.begin(); while( i != textures.end() ) { VolatileTexture *vt = *i++; if (vt->m_bIsString) { vt->texture->initWithString(vt->m_strText.c_str(), vt->m_size, vt->m_alignment, vt->m_strFontName.c_str(), vt->m_fFontSize); } else { CCImage image; CCFileData data(vt->m_strFileName.c_str(), "rb"); unsigned long nSize = data.getSize(); unsigned char* pBuffer = data.getBuffer(); if (image.initWithImageData((void*)pBuffer, nSize, vt->m_FmtImage)) { vt->texture->initWithImage(&image); } } } isReloading = false; }
bool ScreenHelper::AddOBBSpriteToCache(const char *name, const char *plistName) { unsigned long pSize; unsigned char * pData = 0; //#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) && !defined KINDLE__ // std::vector<std::string> paths; // paths.push_back("/mnt/sdcard/Android/obb"); // CCFileUtils::sharedFileUtils()->setSearchPaths(paths); //#endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("main.1.com.LudicrousGames.MonkeyDroid.zip"); //CCLOG(fullPath.c_str()); pData = CCFileUtils::sharedFileUtils()->getFileDataFromZip(fullPath.c_str(), name, &pSize); //CCLOG("%d",pData); if(pData) { CCImage* img = new CCImage(); img->initWithImageData(pData, pSize); CCTextureCache::sharedTextureCache()->addUIImage(img, CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile(name, plistName)); CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(plistName); return true; } return false; #else CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(plistName,name); #endif }
NS_CC_BEGIN // // ParticleFire // static CCTexture2D* getDefaultTexture() { CCTexture2D* pTexture = NULL; CCImage* pImage = NULL; do { bool bRet = false; const char* key = "__firePngData"; pTexture = CCTextureCache::sharedTextureCache()->textureForKey(key); CC_BREAK_IF(pTexture != NULL); pImage = new CCImage(); CC_BREAK_IF(NULL == pImage); bRet = pImage->initWithImageData((void*)__firePngData, sizeof(__firePngData), kFmtPng); CC_BREAK_IF(!bRet); pTexture = CCTextureCache::sharedTextureCache()->addUIImage(pImage, key); } while (0); CC_SAFE_RELEASE(pImage); return pTexture; }
void CCSpriteEx::setTexture(CCTexture2D *texture) { // If batchnode, then texture id should be the same CCAssert(! m_pobBatchNode || texture->getName() == m_pobBatchNode->getTexture()->getName(), "CCSprite: Batched sprites should use the same texture as the batchnode"); // accept texture==nil as argument CCAssert( !texture || dynamic_cast<CCTexture2D*>(texture), "setTexture expects a CCTexture2D. Invalid argument"); if (NULL == texture) { // Gets the texture by key firstly. texture = CCTextureCache::sharedTextureCache()->textureForKey(CC_2x2_WHITE_IMAGE_KEY); // If texture wasn't in cache, create it from RAW data. if (NULL == texture) { CCImage* image = new CCImage(); bool isOK = image->initWithImageData(cc_2x2_white_image, sizeof(cc_2x2_white_image), CCImage::kFmtRawData, 2, 2, 8); CCAssert(isOK, "The 2x2 empty texture was created unsuccessfully."); texture = CCTextureCache::sharedTextureCache()->addUIImage(image, CC_2x2_WHITE_IMAGE_KEY); CC_SAFE_RELEASE(image); } } if (!m_pobBatchNode && m_pobTexture != texture) { CC_SAFE_RETAIN(texture); CC_SAFE_RELEASE(m_pobTexture); m_pobTexture = texture; if(m_shouldUpdateBlendFunc) updateBlendFunc(); } }
void ChatWidget::setRecHead(std::string *head) { float bw = 70; float bh = 70; if(head == 0 || head->size() == 0) return; if(m_toLabel) m_toLabel->setVisible(false); if(m_toHead && m_toHead->getParent()){ m_toHead->removeFromParentAndCleanup(true); m_toHead = 0; } CCImage *img = new CCImage; img->initWithImageData((void*)head->c_str(),head->size(), CCImage::kFmtUnKnown); CCTexture2D *texture = new CCTexture2D; texture->initWithImage(img); delete img; m_toHead = CCSprite::create(); m_toHead->initWithTexture(texture); CCSize headSize = m_toHead->getContentSize(); m_toHead->setScaleX(60 / headSize.width); m_toHead->setScaleY(60 / headSize.height); m_toButton->CCNode::addChild(m_toHead); m_toHead->setAnchorPoint(ccp(0.5,0.5)); m_toHead->setPosition(ccp(bw/2,bh/2)); }
void AskAsFriendDialog::finish() { LangDef *lang = ResourceMgr::getInstance()->getLangDef(); BasButton *okButton = new BasButton; okButton->setButtonInfo(lang->getStringById(StringEnum::Ok).data(),"fonts/uifont24.fnt","default","buttonbg", CCSizeMake(0,0)); okButton->setClickCB(m_okListener,m_okFunc); this->addChild(okButton); okButton->setBottomMargin(m_edgeSize); okButton->setBottom("parent",uilib::Bottom); okButton->setHorizontal("parent",0.75); BasButton *rejectButton = new BasButton; rejectButton->setButtonInfo(lang->getStringById(StringEnum::Reject).data(),"fonts/uifont24.fnt","default","buttonbg", CCSizeMake(0,0)); rejectButton->setClickCB(m_rejectListener,m_rejectFunc); this->addChild(rejectButton); rejectButton->setBottomMargin(m_edgeSize); rejectButton->setBottom("parent",uilib::Bottom); rejectButton->setHorizontal("parent",0.25); BasWidget *headWidget; if(!m_askHead.empty()){ CCImage *img = new CCImage; img->initWithImageData((void*)m_askHead.c_str(),m_askHead.size(), CCImage::kFmtUnKnown); CCTexture2D *texture = new CCTexture2D; texture->initWithImage(img); delete img; CCSprite *sprite = CCSprite::create(); sprite->initWithTexture(texture); headWidget = new BasNodeDelegateWidget(sprite); this->addChild(headWidget); headWidget->setHorizontal("parent",0.5); headWidget->setVertical("parent",0.3); }else{ CCSprite *sprite = CCSprite::createWithSpriteFrameName("headdefault.png"); headWidget = new BasNodeDelegateWidget(sprite); this->addChild(headWidget); headWidget->setHorizontal("parent",0.5); headWidget->setVertical("parent",0.3); } m_askWord.insert(0," "); TextScrollArea *area = new TextScrollArea; area->setTheme("",""); area->setTextInfo(m_askWord,getSystemFont(),40,ccWHITE); this->addChild(area); area->setLeft("parent",uilib::Left); area->setRight("parent",uilib::Right); area->setLeftMargin(10); area->setRightMargin(10); area->setTop(headWidget->getName(),uilib::Bottom); area->setBottom(rejectButton->getName(),uilib::Top); }
/* get buffer as CCImage */ CCImage* CCRenderTexture::newCCImage() { CCAssert(m_ePixelFormat == kCCTexture2DPixelFormat_RGBA8888, "only RGBA8888 can be saved as image"); if (NULL == m_pTexture) { return NULL; } const CCSize& s = m_pTexture->getContentSizeInPixels(); // to get the image size to save // if the saving image domain exeeds the buffer texture domain, // it should be cut int nSavedBufferWidth = (int)s.width; int nSavedBufferHeight = (int)s.height; GLubyte *pBuffer = NULL; GLubyte *pTempData = NULL; CCImage *pImage = new CCImage(); do { CC_BREAK_IF(! (pBuffer = new GLubyte[nSavedBufferWidth * nSavedBufferHeight * 4])); if(! (pTempData = new GLubyte[nSavedBufferWidth * nSavedBufferHeight * 4])) { delete[] pBuffer; pBuffer = NULL; break; } this->begin(); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0,0,nSavedBufferWidth, nSavedBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, pTempData); this->end(); // to get the actual texture data // #640 the image read from rendertexture is upseted for (int i = 0; i < nSavedBufferHeight; ++i) { memcpy(&pBuffer[i * nSavedBufferWidth * 4], &pTempData[(nSavedBufferHeight - i - 1) * nSavedBufferWidth * 4], nSavedBufferWidth * 4); } pImage->initWithImageData(pBuffer, nSavedBufferWidth * nSavedBufferHeight * 4, CCImage::kFmtRawData, nSavedBufferWidth, nSavedBufferHeight, 8); } while (0); CC_SAFE_DELETE_ARRAY(pBuffer); CC_SAFE_DELETE_ARRAY(pTempData); return pImage; }
void download(void* pCurl) { RawTile* pTile = ((curl_data*)pCurl)->pRawTile; TileResolver* pTileResolver = ((curl_data*)pCurl)->pTileResolver; //try { CCString strUrl = MapStrategyFactory::getStrategy(pTileResolver->getMapSourceId())->getUrl(pTile->x,pTile->y,pTile->z); std::string strResponse; CURLcode res; CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, strUrl.getCString()); curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); res = curl_easy_perform(curl); int retcode = 0; res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE , &retcode); double length; res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD , &length); if (res==CURLE_OK && retcode == 200 && ((int)length)>0 && strResponse.size()>0) { CCImage* pImage = new CCImage; pImage->initWithImageData((void*)strResponse.c_str(),(int)length); if(((TileResolver*)(pTileResolver))->put2Cache(pTile,pImage)) { ((PhysicMap* )(((TileResolver*)(pTileResolver))->m_pPhysicMap))->m_pHandler->addEvent(pTile,pImage); } curl_easy_cleanup(curl); delete (curl_data*)pCurl; pCurl = NULL; } } return ; }
void CAApplication::createStatsLabel() { CAImage* texture = NULL; CAImageCache *ImageCache = CAImageCache::sharedImageCache(); if( m_pFPSLabel && m_pSPFLabel ) { CC_SAFE_RELEASE_NULL(m_pFPSLabel); CC_SAFE_RELEASE_NULL(m_pSPFLabel); CC_SAFE_RELEASE_NULL(m_pDrawsLabel); ImageCache->removeImageForKey("cc_fps_images"); CCFileUtils::sharedFileUtils()->purgeCachedEntries(); } CAImagePixelFormat currentFormat = CAImage::defaultAlphaPixelFormat(); CAImage::setDefaultAlphaPixelFormat(kCAImagePixelFormat_RGBA4444); unsigned char *data = NULL; unsigned int data_len = 0; getFPSImageData(&data, &data_len); CCImage* image = new CCImage(); bool isOK = image->initWithImageData(data, data_len); if (!isOK) { CCLOGERROR("%s", "Fails: init fps_images"); return; } texture = ImageCache->addUIImage(image, "cc_fps_images"); CC_SAFE_RELEASE(image); float factor = CCEGLView::sharedOpenGLView()->getDesignResolutionSize().height / 640.0f; m_pFPSLabel = CALabel::createWithFrame(CCRect(0, 0, 100, 32)); m_pFPSLabel->retain(); m_pFPSLabel->setScale(factor); m_pFPSLabel->setColor(CAColor_blue); m_pSPFLabel = CALabel::createWithFrame(CCRect(0, 0, 100, 32)); m_pSPFLabel->retain(); m_pSPFLabel->setScale(factor); m_pSPFLabel->setColor(CAColor_yellow); m_pDrawsLabel = CALabel::createWithFrame(CCRect(0, 0, 100, 32)); m_pDrawsLabel->retain(); m_pDrawsLabel->setScale(factor); m_pDrawsLabel->setColor(CAColor_green); m_pDrawsLabel->setFrameOrigin(ccpAdd(ccp(0, 64*factor), CC_DIRECTOR_STATS_POSITION)); m_pSPFLabel->setFrameOrigin(ccpAdd(ccp(0, 32*factor), CC_DIRECTOR_STATS_POSITION)); m_pFPSLabel->setFrameOrigin(CC_DIRECTOR_STATS_POSITION); CAImage::setDefaultAlphaPixelFormat(currentFormat); }
CCSprite * NewsScene::getImageFromURL(const char* url) { CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if(curl) { string out = string(url); struct BufferStruct output; output.buffer = NULL; output.size = 0; curl_easy_setopt(curl, CURLOPT_URL, out.c_str()); string response; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &output); res = curl_easy_perform(curl); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res)); return NULL; } else { // FILE * fp; // fp = fopen( "loucura.png","w"); // if( fp ) // fprintf(fp, output.buffer ); // fclose( fp ); CCImage* img = new CCImage(); img->initWithImageData((void*)output.buffer, (long)output.size, CCImage::kFmtPng); cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D(); //TODO:: leak texture->initWithImage(img); CCSprite* sprBackground = CCSprite::create(texture); return sprBackground; // sprBackground->setAnchorPoint(ccp(0,0)); // sprBackground->setScale(1); // sprBackground->setPosition(ccp(0,0)); // // this->addChild(sprBackground); // // // cout << "Variable response : " << &output.buffer; } curl_easy_cleanup(curl); } curl_global_cleanup(); }
void CMainCityUI::imageLoadSuccessCallBack(string sTag, vector<char>* pBuffer) { CCImage* img = new CCImage; img->initWithImageData((unsigned char*)pBuffer->data(), pBuffer->size()); CCTexture2D* texture = new CCTexture2D(); texture->initWithImage(img); CLayout* headPart = (CLayout*)m_ui->findWidgetById("head_part"); CCSprite* head = (CCSprite*)headPart->getChildByTag(15); // head->removeFromParent(); //head->setTexture(texture); string path = HttpLoadImage::getInstance()->getStoragePath("download/fbImg",sTag.c_str())+".jpg"; string buff(pBuffer->begin(), pBuffer->end()); CCLOG("path: %s", path.c_str()); FILE *fp = fopen(path.c_str(), "wb+"); fwrite(buff.c_str(), 1, pBuffer->size(), fp); fclose(fp); // CCSprite *headbg = (CCSprite*)(m_ui->findWidgetById("headbg")); // CCClippingNode *clip = CCClippingNode::create(); // CCSprite *fbimg = CCSprite::createWithTexture(texture); // clip->addChild(fbimg); // // clip->setPosition(headbg->getPosition()); // clip->setContentSize(CCSizeMake(110,110)); // // static ccColor4F red ={1,0,1}; // float radius = 106; // const int nCount = 200; // const float angle = 2.0f* (float)M_PI/nCount; // CCPoint circle[nCount]; // for(int i=0; i<nCount; i++) // { // float radian = i*angle; // circle[i].x = radius * cosf(radian); // circle[i].y = radius * sinf(radian); // } // CCDrawNode *stencil= CCDrawNode::create(); // stencil->drawPolygon(circle,nCount,red,0,red); // clip->setStencil(stencil); // m_ui->addChild(clip); CCSprite *headBg = (CCSprite *)(headPart->findWidgetById("headbg")); CCSprite *headSpr = MakeFaceBookHeadToCircle(CCSprite::createWithTexture(texture)); headSpr->setTag(15); headSpr->setPosition(headBg->getPosition()); headPart->addChild(headSpr); head->removeFromParent(); img->release(); }
CCTexture2D* FileHelper::getImageFileByName(string pFileName){ //第一先获取文件的路径 string path = CCFileUtils::sharedFileUtils()->getWriteablePath() + pFileName; CCLOG("path = %s",path.c_str()); //创建一个文件指针 FILE* file = fopen(path.c_str(), "r"); if (file) { char* buf; //要获取的字符串 int len; //获取的长度 /*获取长度*/ fseek(file, 0, SEEK_END); //移到尾部 len = ftell(file); //提取长度 rewind(file); //回归原位 CCLOG("count the file content len = %d",len); //分配buf空间 buf = (char*)malloc(sizeof(char) * len + 1); if (!buf) { CCLOG("malloc space is not enough."); return NULL; } //读取文件 //读取进的buf,单位大小,长度,文件指针 int rLen = fread(buf, sizeof(char), len, file); buf[rLen] = '\0'; CCLOG("has read Length = %d",rLen); CCLOG("has read content = %s",buf); CCImage* img = new CCImage(); img->initWithImageData((unsigned char*)buf, len); CCLog("img size = %d, %d", img->getWidth(), img->getHeight()); CCTexture2D* texture2D = new CCTexture2D(); texture2D->initWithImage(img); texture2D->retain(); string result = buf; fclose(file); free(buf); return texture2D; } else CCLOG("open file error."); return NULL; }
void CAMediaManager::initAndroidImage() { CCImage *image =new CCImage(); image->autorelease(); if (image->initWithImageData((void*)m_pBuffer,n_fileSize,CCImage::kFmtJpg)) { this->getMediaDelegate()->getSelectedImage(image); CAScheduler::unschedule(schedule_selector(CAMediaManager::initAndroidImage), this); } }
void AwaiterInfoNode::OnProfileImageResponse(CCHttpClient* client, CCHttpResponse* response) { if(response->getResponseCode() == 200) { std::vector<char> *buffer = response->getResponseData(); bool imgInit; CCImage * img = new CCImage(); if (img->initWithImageData(&(*buffer)[0], buffer->size(), CCImage::kFmtUnKnown)) { imgInit = true; CCLOG("init using kFmtUnKnown"); } else { imgInit = false; CCLOG("failed to init using kFmtUnKnown"); } if(imgInit) { std::stringstream userKeyStringStream; userKeyStringStream << "profileimage_" << m_ActorID; std::string userKeyString = userKeyStringStream.str(); CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addUIImage(img, userKeyString.c_str()); // CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addUIImage(img, "sinhyub"); if (texture != NULL) { m_ProfileImage->initWithTexture(texture); // TODO : m_ProfileImage에 파일을 로딩시키고 그것을 적절한 위치에 배치해야함 // TODO : profile image scale CCSize imageSize = m_ProfileImage->getContentSize(); const float scaleX = ProfileImageWidth / imageSize.width; const float scaleY = ProfileImageHeight / imageSize.height; m_ProfileImage->setScaleX(scaleX); m_ProfileImage->setScaleY(scaleY); } } img->release(); } else { // TODO : default image display return; } }
void CCSprite::didReceiveFile(HttpRequest* r, char *data, uint32 len) { if(r == mRequest){ CCImage* img = new CCImage; img->initWithImageData(data, len); CCTextureCache *cache = CCTextureCache::sharedTextureCache(); CCTexture2D* texture = cache->addUIImage(img, r->mURL->getCString()); setTextureAndSize(texture); mRequest = NULL; delete img; if(mDelegate) mDelegate->didSpriteReceiveFile(this); } }
void CCAsyncSprite::setImage(const char *data, size_t size, const string &url){ CCImage::EImageFormat format = CCImage::kFmtUnKnown; size_t pos = url.find_last_of('.'); if (pos != string::npos) { string ext = url.substr(pos, url.size()+1); if (ext.compare(".png") == 0|| ext.compare(".PNG") == 0) { format = CCImage::kFmtPng; } else if (ext.compare(".jpg") == 0|| ext.compare(".JPG") == 0 || ext.compare(".jpeg") ||ext.compare(".JPEG") == 0){ format = CCImage::kFmtJpg; } if (format != CCImage::kFmtUnKnown) { CCImage* img = new CCImage; img->initWithImageData((void*)data, (long)size, format); setSpriteWithCCImage(img); img->saveToFile((CCFileUtils::sharedFileUtils()->getWritablePath()+m_strFileName).c_str()); } } }
//------------------------------------------------------------------------- bool FKCW_UI_ProgressIndicator::initWithMessage(const string& message) { if(!CCLayerColor::initWithColor(m_tagDimColor)) { return false; } // 保存消息 m_strMessage = message; // 创建Label m_pMsgLabel = CCLabelTTF::create(m_strMessage.c_str(), "Helvetica", 28 / CC_CONTENT_SCALE_FACTOR()); // 提示器 CCImage* image = new CCImage(); image->initWithImageData((void*)s_SpinnerPng, 1043); CCTexture2D* tex = new CCTexture2D(); tex->initWithImage(image); m_pIndicator = CCSprite::createWithTexture(tex); CC_SAFE_RETAIN(m_pIndicator); image->release(); tex->release(); _RelayOut(); addChild(m_pIndicator); addChild(m_pMsgLabel); // 开启事件 setTouchEnabled(true); setTouchMode(kCCTouchesOneByOne); setTouchPriority(-MAX_INT); setKeypadEnabled(true); // 开启帧更新 scheduleUpdate(); return true; }
bool CCProgressHUD::initWithMessage(const string& message) { if(!CCLayerColor::initWithColor(m_dimColor)) { return false; } // set message m_message = message; // create label m_msgLabel = CCLabelTTF::create(m_message.c_str(), "Helvetica", 28 / CC_CONTENT_SCALE_FACTOR()); // indicator CCImage* image = new CCImage(); image->initWithImageData((void*)s_spinner_png, 1043); CCTexture2D* tex = new CCTexture2D(); tex->initWithImage(image); m_indicator = CCSprite::createWithTexture(tex); CC_SAFE_RETAIN(m_indicator); CC_SAFE_RELEASE(image); CC_SAFE_RELEASE(tex); // layout relayout(); addChild(m_indicator); addChild(m_msgLabel); // enable event setTouchEnabled(true); setTouchMode(kCCTouchesOneByOne); setTouchPriority(-MAX_INT); setKeypadEnabled(true); // schedule update scheduleUpdate(); return true; }
void RequestTopaz::onHttpRequestCompletedNoEncrypt(CCNode *sender, void *data) { CCHttpResponse* res = (CCHttpResponse*) data; char dumpData[110*110*2]; // 프로필 사진 받아오기 실패 if (!res || !res->isSucceed()) { //CCLog("res failed. error buffer: %s", res->getErrorBuffer()); return; } // dump data std::vector<char> *buffer = res->getResponseData(); for (unsigned int i = 0 ; i < buffer->size() ; i++) dumpData[i] = (*buffer)[i]; dumpData[buffer->size()] = NULL; // make texture2D CCImage* img = new CCImage; img->initWithImageData(dumpData, (int)buffer->size()); CCTexture2D* texture = new CCTexture2D(); texture->initWithImage(img); // set CCSprite (profile 모음 리스트에 갱신) int numOfList = friendList.size(); int index = atoi(res->getHttpRequest()->getTag()); ProfileSprite* psp = ProfileSprite::GetObj(friendList[index]->GetImageUrl()); psp->SetSprite(texture); psp->SetLoadingDone(true); // 화면에 보이는 스프라이트 교체 if (spriteClassScroll == NULL) return; spriteClassScroll->ChangeSprite(-888*(numOfList-index), psp->GetProfile()); ((CCSprite*)spriteClassScroll->FindSpriteByTag(-777*(numOfList-index)))->setOpacity(255); }
void SpriteFrameCacheHelper::addSpriteFrameFromPak(const char *_plistPath, const char *_imagePath) { #if CS_TOOL_PLATFORM //! create CCDictionary from pak char *_pFileContent = NULL; int size = JsonReader::getFileBuffer(_plistPath, &_pFileContent); CSDictMaker dictMaker; CCDictionary *dict = dictMaker.dictionaryWithContentsOfCache(_pFileContent, size); //! create CCTexture2D from pak size = JsonReader::getFileBuffer(_imagePath, &_pFileContent); CCImage *img = new CCImage(); img->initWithImageData(_pFileContent, size); CCTexture2D *pobTexture = CCTextureCache::sharedTextureCache()->addUIImage(img, _imagePath); addSpriteFrameFromDict(dict, pobTexture, _imagePath); #endif }
void CAImageView::setImage(CAImage* texture) { // accept texture==nil as argument CCAssert( !texture || dynamic_cast<CAImage*>(texture), "setTexture expects a CCTexture2D. Invalid argument"); if (NULL == texture) { // Gets the texture by key firstly. texture = CCTextureCache::sharedTextureCache()->textureForKey(CC_2x2_WHITE_IMAGE_KEY); // If texture wasn't in cache, create it from RAW data. if (NULL == texture) { CCImage* image = new CCImage(); bool isOK = image->initWithImageData(cc_2x2_white_image, sizeof(cc_2x2_white_image), CCImage::kFmtRawData, 2, 2, 8); CCAssert(isOK, "The 2x2 empty texture was created unsuccessfully."); texture = CCTextureCache::sharedTextureCache()->addUIImage(image, CC_2x2_WHITE_IMAGE_KEY); CC_SAFE_RELEASE(image); } } CAView::setImage(texture); }
void HelloWorld::ChangeParticle(float scale, bool isBackgroundMove, int backgroundMoveSpeed, float angle, float angleVar, int destBlendFunc, int srcBlendFunc, float duration, float emissionRate, int emiiterMode, GLbyte endColorR,GLbyte endColorG,GLbyte endColorB,GLbyte endColorA, GLbyte endColorVarR,GLbyte endColorVarG,GLbyte endColorVarB,GLbyte endColorVarA, float endRadius,float endRadiusVar, float endSize,float endSizeVar, float endSpin,float endSpinVar, float gravityX,float gravityY, bool isAutoRemoveOnFinish, float life,float lifeVar, int positionType, float positionVarX,float positionVarY, float radialAccel,float radialAccelVar, float rotatePerSecond,float rotatePerSecondVar, float sourcePositionX,float sourcePositionY, float speed,float speedVar, GLbyte startColorR,GLbyte startColorG,GLbyte startColorB,GLbyte startColorA, GLbyte startColorVarR,GLbyte startColorVarG,GLbyte startColorVarB,GLbyte startColorVarA, float startRadius,float startRadiusVar, float startSize,float startSizeVar, float startSpin,float startSpinVar, float tangentialAccel,float tangentialAccelVar, char* plistPath,char* texturePath,char* textureImageData, unsigned int totalParticles ) { if (texturePath==NULL||strlen(texturePath)==0) { return; } //mBackground->setScale(scale); CCSize size= CCDirector::sharedDirector()->getWinSize(); if (totalParticles!=mEmiiter->getTotalParticles()) { mEmiiter->removeFromParentAndCleanup(true); mEmiiter=new CCParticleSystemQuad(); mEmiiter->initWithTotalParticles(totalParticles); mEmiiter->setPosition(ccp(size.width/2,size.height/2)); mEmiiter->setTexture(CCTextureCache::sharedTextureCache()->addImage("fire.png")); mBackground->addChild(mEmiiter,1); } //if (isBackgroundMove!=mIsBackgroundMove) //{ mIsBackgroundMove=isBackgroundMove; mBackground->stopAllActions(); mBackground->setPosition(ccp(size.width/2,size.height/2)); if (mIsBackgroundMove) { CCActionInterval* move1 = CCMoveBy::create(1.0 / backgroundMoveSpeed, CCPointMake(100,0) ); CCActionInterval* move2 = CCMoveBy::create(1.0 / backgroundMoveSpeed, CCPointMake(0,100) ); CCActionInterval* move3 = CCMoveBy::create(1.0 / backgroundMoveSpeed, CCPointMake(-100,0) ); CCActionInterval* move4 = CCMoveBy::create(1.0 / backgroundMoveSpeed, CCPointMake(0,-100) ); CCFiniteTimeAction* seq = CCSequence::create(move1, move2, move3,move4,NULL); mBackground->runAction( CCRepeatForever::create((CCActionInterval*)seq) ); } //} CCTexture2D *tex = NULL; if (texturePath!=NULL) { // set not pop-up message box when load image failed bool bNotify = CCFileUtils::sharedFileUtils()->isPopupNotify(); CCFileUtils::sharedFileUtils()->setPopupNotify(false); //tex = CCTextureCache::sharedTextureCache()->addImage(texturePath); if (tex==NULL) { std::string secondPath=plistPath; secondPath+="/"; secondPath+=texturePath; tex = CCTextureCache::sharedTextureCache()->addImage(secondPath.c_str()); } // reset the value of UIImage notify CCFileUtils::sharedFileUtils()->setPopupNotify(bNotify); } if (tex) { mEmiiter->setTexture(tex); } else { unsigned char *buffer = NULL; unsigned char *deflated = NULL; CCImage *image = NULL; CCAssert(textureImageData, ""); int dataLen = strlen(textureImageData); if(dataLen != 0) { // if it fails, try to get it from the base64-gzipped data int decodeLen = base64Decode((unsigned char*)textureImageData, (unsigned int)dataLen, &buffer); CCAssert( buffer != NULL, "CCParticleSystem: error decoding textureImageData"); int deflatedLen = ZipUtils::ccInflateMemory(buffer, decodeLen, &deflated); CCAssert( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); // For android, we should retain it in VolatileTexture::addCCImage which invoked in CCTextureCache::sharedTextureCache()->addUIImage() image = new CCImage(); bool isOK = image->initWithImageData(deflated, deflatedLen); CCAssert(isOK, "CCParticleSystem: error init image with Data"); mEmiiter->setTexture(CCTextureCache::sharedTextureCache()->addUIImage(image, texturePath)); image->release(); } CC_SAFE_DELETE_ARRAY(buffer); CC_SAFE_DELETE_ARRAY(deflated); } mEmiiter->setAngle(angle); mEmiiter->setAngleVar(angleVar); ccBlendFunc func; func.dst=destBlendFunc; func.src=srcBlendFunc; mEmiiter->setBlendFunc(func); mEmiiter->setDuration(duration); mEmiiter->setEmissionRate(emissionRate); mEmiiter->setEmitterMode(emiiterMode); ccColor4F endColor=ccc4FFromccc4B(ccc4(endColorR,endColorG,endColorB,endColorA)); mEmiiter->setEndColor(endColor); ccColor4F endColorVar=ccc4FFromccc4B(ccc4(endColorVarR,endColorVarG,endColorVarB,endColorVarA)); mEmiiter->setEndColorVar(endColorVar); if (emiiterMode==kCCParticleModeGravity ) { mEmiiter->setGravity(ccp(gravityX,gravityY)); mEmiiter->setSpeed(speed); mEmiiter->setSpeedVar(speedVar); mEmiiter->setTangentialAccel(tangentialAccel); mEmiiter->setTangentialAccelVar(tangentialAccelVar); mEmiiter->setRadialAccel(radialAccel); mEmiiter->setRadialAccelVar(radialAccelVar); } else if (emiiterMode==kCCParticleModeRadius) { mEmiiter->setStartRadius(startRadius); mEmiiter->setStartRadiusVar(startRadiusVar); mEmiiter->setEndRadius(endRadius); mEmiiter->setEndRadiusVar(endRadiusVar); mEmiiter->setRotatePerSecond(rotatePerSecond); mEmiiter->setRotatePerSecondVar(rotatePerSecondVar); } mEmiiter->setEndSize(endSize); mEmiiter->setEndSizeVar(endSizeVar); mEmiiter->setEndSpin(endSpin); mEmiiter->setEndSpinVar(endSpinVar); mEmiiter->setAutoRemoveOnFinish(isAutoRemoveOnFinish); mEmiiter->setLife(life); mEmiiter->setLifeVar(lifeVar); mEmiiter->setPositionType((tCCPositionType)positionType); mEmiiter->setPosVar(ccp(positionVarX,positionVarY)); mEmiiter->setSourcePosition(ccp(sourcePositionX,sourcePositionY)); ccColor4F startColor=ccc4FFromccc4B(ccc4(startColorR,startColorG,startColorB,startColorA)); mEmiiter->setStartColor(startColor); ccColor4F startColorVar=ccc4FFromccc4B(ccc4(startColorVarR,startColorVarG,startColorVarB,startColorVarA)); mEmiiter->setStartColorVar(startColorVar); mEmiiter->setStartSize(startSize); mEmiiter->setStartSizeVar(startSizeVar); mEmiiter->setTotalParticles(totalParticles); mEmiiter->resetSystem(); CCEGLView* eglView = CCEGLView::sharedOpenGLView(); eglView->setFrameZoomFactor(1.f * scale); }
bool CCParticleSystem::initWithDictionary(CCDictionary *dictionary, const char *dirname) { bool bRet = false; unsigned char *buffer = NULL; unsigned char *deflated = NULL; CCImage *image = NULL; do { int maxParticles = dictionary->valueForKey("maxParticles")->intValue(); // self, not super if(this->initWithTotalParticles(maxParticles)) { // angle m_fAngle = dictionary->valueForKey("angle")->floatValue(); m_fAngleVar = dictionary->valueForKey("angleVariance")->floatValue(); // duration m_fDuration = dictionary->valueForKey("duration")->floatValue(); // blend function m_tBlendFunc.src = dictionary->valueForKey("blendFuncSource")->intValue(); m_tBlendFunc.dst = dictionary->valueForKey("blendFuncDestination")->intValue(); // color m_tStartColor.r = dictionary->valueForKey("startColorRed")->floatValue(); m_tStartColor.g = dictionary->valueForKey("startColorGreen")->floatValue(); m_tStartColor.b = dictionary->valueForKey("startColorBlue")->floatValue(); m_tStartColor.a = dictionary->valueForKey("startColorAlpha")->floatValue(); m_tStartColorVar.r = dictionary->valueForKey("startColorVarianceRed")->floatValue(); m_tStartColorVar.g = dictionary->valueForKey("startColorVarianceGreen")->floatValue(); m_tStartColorVar.b = dictionary->valueForKey("startColorVarianceBlue")->floatValue(); m_tStartColorVar.a = dictionary->valueForKey("startColorVarianceAlpha")->floatValue(); m_tEndColor.r = dictionary->valueForKey("finishColorRed")->floatValue(); m_tEndColor.g = dictionary->valueForKey("finishColorGreen")->floatValue(); m_tEndColor.b = dictionary->valueForKey("finishColorBlue")->floatValue(); m_tEndColor.a = dictionary->valueForKey("finishColorAlpha")->floatValue(); m_tEndColorVar.r = dictionary->valueForKey("finishColorVarianceRed")->floatValue(); m_tEndColorVar.g = dictionary->valueForKey("finishColorVarianceGreen")->floatValue(); m_tEndColorVar.b = dictionary->valueForKey("finishColorVarianceBlue")->floatValue(); m_tEndColorVar.a = dictionary->valueForKey("finishColorVarianceAlpha")->floatValue(); // particle size m_fStartSize = dictionary->valueForKey("startParticleSize")->floatValue(); m_fStartSizeVar = dictionary->valueForKey("startParticleSizeVariance")->floatValue(); m_fEndSize = dictionary->valueForKey("finishParticleSize")->floatValue(); m_fEndSizeVar = dictionary->valueForKey("finishParticleSizeVariance")->floatValue(); // position float x = dictionary->valueForKey("sourcePositionx")->floatValue(); float y = dictionary->valueForKey("sourcePositiony")->floatValue(); this->setPosition( ccp(x,y) ); m_tPosVar.x = dictionary->valueForKey("sourcePositionVariancex")->floatValue(); m_tPosVar.y = dictionary->valueForKey("sourcePositionVariancey")->floatValue(); // Spinning m_fStartSpin = dictionary->valueForKey("rotationStart")->floatValue(); m_fStartSpinVar = dictionary->valueForKey("rotationStartVariance")->floatValue(); m_fEndSpin= dictionary->valueForKey("rotationEnd")->floatValue(); m_fEndSpinVar= dictionary->valueForKey("rotationEndVariance")->floatValue(); m_nEmitterMode = dictionary->valueForKey("emitterType")->intValue(); // Mode A: Gravity + tangential accel + radial accel if( m_nEmitterMode == kCCParticleModeGravity ) { // gravity modeA.gravity.x = dictionary->valueForKey("gravityx")->floatValue(); modeA.gravity.y = dictionary->valueForKey("gravityy")->floatValue(); // speed modeA.speed = dictionary->valueForKey("speed")->floatValue(); modeA.speedVar = dictionary->valueForKey("speedVariance")->floatValue(); // radial acceleration modeA.radialAccel = dictionary->valueForKey("radialAcceleration")->floatValue(); modeA.radialAccelVar = dictionary->valueForKey("radialAccelVariance")->floatValue(); // tangential acceleration modeA.tangentialAccel = dictionary->valueForKey("tangentialAcceleration")->floatValue(); modeA.tangentialAccelVar = dictionary->valueForKey("tangentialAccelVariance")->floatValue(); } // or Mode B: radius movement else if( m_nEmitterMode == kCCParticleModeRadius ) { modeB.startRadius = dictionary->valueForKey("maxRadius")->floatValue(); modeB.startRadiusVar = dictionary->valueForKey("maxRadiusVariance")->floatValue(); modeB.endRadius = dictionary->valueForKey("minRadius")->floatValue(); modeB.endRadiusVar = 0.0f; modeB.rotatePerSecond = dictionary->valueForKey("rotatePerSecond")->floatValue(); modeB.rotatePerSecondVar = dictionary->valueForKey("rotatePerSecondVariance")->floatValue(); } else { CCAssert( false, "Invalid emitterType in config file"); CC_BREAK_IF(true); } // life span m_fLife = dictionary->valueForKey("particleLifespan")->floatValue(); m_fLifeVar = dictionary->valueForKey("particleLifespanVariance")->floatValue(); // emission Rate m_fEmissionRate = m_uTotalParticles / m_fLife; //don't get the internal texture if a batchNode is used if (!m_pBatchNode) { // Set a compatible default for the alpha transfer m_bOpacityModifyRGB = false; // texture // Try to get the texture from the cache std::string textureName = dictionary->valueForKey("textureFileName")->getCString(); size_t rPos = textureName.rfind('/'); if (rPos != string::npos) { string textureDir = textureName.substr(0, rPos + 1); if (dirname != NULL && textureDir != dirname) { textureName = textureName.substr(rPos+1); textureName = string(dirname) + textureName; } } else { if (dirname != NULL) { textureName = string(dirname) + textureName; } } CCTexture2D *tex = NULL; if (textureName.length() > 0) { // set not pop-up message box when load image failed bool bNotify = CCFileUtils::sharedFileUtils()->isPopupNotify(); CCFileUtils::sharedFileUtils()->setPopupNotify(false); tex = CCTextureCache::sharedTextureCache()->addImage(textureName.c_str()); // reset the value of UIImage notify CCFileUtils::sharedFileUtils()->setPopupNotify(bNotify); } if (tex) { setTexture(tex); } else { const char *textureData = dictionary->valueForKey("textureImageData")->getCString(); CCAssert(textureData, ""); int dataLen = strlen(textureData); if(dataLen != 0) { // if it fails, try to get it from the base64-gzipped data int decodeLen = base64Decode((unsigned char*)textureData, (unsigned int)dataLen, &buffer); CCAssert( buffer != NULL, "CCParticleSystem: error decoding textureImageData"); CC_BREAK_IF(!buffer); int deflatedLen = ZipUtils::ccInflateMemory(buffer, decodeLen, &deflated); CCAssert( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); // For android, we should retain it in VolatileTexture::addCCImage which invoked in CCTextureCache::sharedTextureCache()->addUIImage() image = new CCImage(); bool isOK = image->initWithImageData(deflated, deflatedLen); CCAssert(isOK, "CCParticleSystem: error init image with Data"); CC_BREAK_IF(!isOK); setTexture(CCTextureCache::sharedTextureCache()->addUIImage(image, textureName.c_str())); image->release(); } } CCAssert( this->m_pTexture != NULL, "CCParticleSystem: error loading the texture"); } bRet = true; } } while (0); CC_SAFE_DELETE_ARRAY(buffer); CC_SAFE_DELETE_ARRAY(deflated); return bRet; }
void CCDirector::createStatsLabel() { CCTexture2D *texture = NULL; CCTextureCache *textureCache = CCTextureCache::sharedTextureCache(); if( m_pFPSLabel && m_pSPFLabel ) { CC_SAFE_RELEASE_NULL(m_pFPSLabel); CC_SAFE_RELEASE_NULL(m_pSPFLabel); CC_SAFE_RELEASE_NULL(m_pDrawsLabel); textureCache->removeTextureForKey("cc_fps_images"); CCFileUtils::sharedFileUtils()->purgeCachedEntries(); } CCTexture2DPixelFormat currentFormat = CCTexture2D::defaultAlphaPixelFormat(); CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444); unsigned char *data = NULL; unsigned int data_len = 0; getFPSImageData(&data, &data_len); CCImage* image = new CCImage(); bool isOK = image->initWithImageData(data, data_len); if (!isOK) { CCLOGERROR("%s", "Fails: init fps_images"); return; } texture = textureCache->addUIImage(image, "cc_fps_images"); CC_SAFE_RELEASE(image); /* We want to use an image which is stored in the file named ccFPSImage.c for any design resolutions and all resource resolutions. To achieve this, Firstly, we need to ignore 'contentScaleFactor' in 'CCAtlasNode' and 'CCLabelAtlas'. So I added a new method called 'setIgnoreContentScaleFactor' for 'CCAtlasNode', this is not exposed to game developers, it's only used for displaying FPS now. Secondly, the size of this image is 480*320, to display the FPS label with correct size, a factor of design resolution ratio of 480x320 is also needed. */ float factor = 1.0f; // CCEGLView::sharedOpenGLView()->getDesignResolutionSize().height / 320.0f; m_pFPSLabel = new CCLabelAtlas(); m_pFPSLabel->setIgnoreContentScaleFactor(true); m_pFPSLabel->initWithString("00.0", texture, 12, 32 , '.'); m_pFPSLabel->setScale(factor); m_pSPFLabel = new CCLabelAtlas(); m_pSPFLabel->setIgnoreContentScaleFactor(true); m_pSPFLabel->initWithString("0.000", texture, 12, 32, '.'); m_pSPFLabel->setScale(factor); m_pDrawsLabel = new CCLabelAtlas(); m_pDrawsLabel->setIgnoreContentScaleFactor(true); m_pDrawsLabel->initWithString("000", texture, 12, 32, '.'); m_pDrawsLabel->setScale(factor); CCTexture2D::setDefaultAlphaPixelFormat(currentFormat); m_pDrawsLabel->setPosition(ccpAdd(ccp(0, 34*factor), CC_DIRECTOR_STATS_POSITION)); m_pSPFLabel->setPosition(ccpAdd(ccp(0, 17*factor), CC_DIRECTOR_STATS_POSITION)); m_pFPSLabel->setPosition(CC_DIRECTOR_STATS_POSITION); }
CCTexture2D * CCTextureCache::addImage(const char * path) { CCAssert(path != NULL, "TextureCache: fileimage MUST not be NULL"); CCTexture2D * texture = NULL; // Split up directory and filename // MUTEX: // Needed since addImageAsync calls this method from a different thread m_pDictLock->lock(); // remove possible -HD suffix to prevent caching the same image twice (issue #1040) std::string pathKey = path; CCFileUtils::ccRemoveHDSuffixFromFile(pathKey); pathKey = CCFileUtils::fullPathFromRelativePath(pathKey.c_str()); texture = m_pTextures->objectForKey(pathKey); std::string fullpath = pathKey; // (CCFileUtils::fullPathFromRelativePath(path)); if( ! texture ) { std::string lowerCase(path); 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 // if ( [[path lowercaseString] hasSuffix:@".pvr"] ) do { if (std::string::npos != lowerCase.find(".pvr")) { #ifdef _POWERVR_SUPPORT_ texture = this->addPVRTCImage(fullpath.c_str()); #endif } // Issue #886: TEMPORARY FIX FOR TRANSPARENT JPEGS IN IOS4 else if (std::string::npos != lowerCase.find(".jpg") || std::string::npos != lowerCase.find(".jpeg")) { CCImage image; CCFileData data(fullpath.c_str(), "rb"); unsigned long nSize = data.getSize(); unsigned char* pBuffer = data.getBuffer(); CC_BREAK_IF(! image.initWithImageData((void*)pBuffer, nSize, CCImage::kFmtJpg)); texture = new CCTexture2D(); texture->initWithImage(&image); if( texture ) { #if CC_ENABLE_CACHE_TEXTTURE_DATA // cache the texture file name VolatileTexture::addImageTexture(texture, fullpath.c_str(), CCImage::kFmtJpg); #endif m_pTextures->setObject(texture, pathKey); texture->release(); } else { CCLOG("cocos2d: Couldn't add image:%s in CCTextureCache", path); } } else { // prevents overloading the autorelease pool CCImage image; CCFileData data(fullpath.c_str(), "rb"); unsigned long nSize = data.getSize(); unsigned char* pBuffer = data.getBuffer(); CC_BREAK_IF(! image.initWithImageData((void*)pBuffer, nSize, CCImage::kFmtPng)); texture = new CCTexture2D(); texture->initWithImage(&image); if( texture ) { #if CC_ENABLE_CACHE_TEXTTURE_DATA // cache the texture file name VolatileTexture::addImageTexture(texture, fullpath.c_str(), CCImage::kFmtPng); #endif m_pTextures->setObject(texture, pathKey); texture->release(); } else { CCLOG("cocos2d: Couldn't add image:%s in CCTextureCache", path); } } } while (0); } m_pDictLock->unlock(); return texture; }
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_CCImage_1richlabel_nativeGetSpriteFrameInfo (JNIEnv * env, jclass clazz, jstring jPlist, jstring jAtlas, jstring jImageName, jobject jFrame) { // get c string const char* plist = (const char*)env->GetStringUTFChars(jPlist, NULL); const char* atlas = (const char*)env->GetStringUTFChars(jAtlas, NULL); const char* imageName = (const char*)env->GetStringUTFChars(jImageName, NULL); // get sprite frame CLBitmapDC& bitmapDC = CLBitmapDC::sharedCLBitmapDC(); CCSpriteFrameCache* fc = CCSpriteFrameCache::sharedSpriteFrameCache(); if(!fc->spriteFrameByName(imageName)) { if(bitmapDC.m_decryptFunc) { // load encryptd data unsigned long len; char* data = (char*)CCFileUtils::sharedFileUtils()->getFileData(atlas, "rb", &len); // create texture int decLen; const char* dec = (*bitmapDC.m_decryptFunc)(data, (int)len, &decLen); CCImage* image = new CCImage(); image->initWithImageData((void*)dec, decLen); image->autorelease(); CCTexture2D* tex = CCTextureCache::sharedTextureCache()->addUIImage(image, atlas); // add fc->addSpriteFramesWithFile(plist, tex); // free if(data != dec) free((void*)dec); free(data); } else { fc->addSpriteFramesWithFile(plist, atlas); } } CCSpriteFrame* frame = fc->spriteFrameByName(imageName); // get java frame info jclass frameClass = env->FindClass("org/cocos2dx/lib/CCImage_richlabel$AtlasFrame"); jfieldID fid_x = env->GetFieldID(frameClass, "x", "I"); jfieldID fid_y = env->GetFieldID(frameClass, "y", "I"); jfieldID fid_w = env->GetFieldID(frameClass, "w", "I"); jfieldID fid_h = env->GetFieldID(frameClass, "h", "I"); jfieldID fid_offsetX = env->GetFieldID(frameClass, "offsetX", "I"); jfieldID fid_offsetY = env->GetFieldID(frameClass, "offsetY", "I"); jfieldID fid_sourceWidth = env->GetFieldID(frameClass, "sourceWidth", "I"); jfieldID fid_sourceHeight = env->GetFieldID(frameClass, "sourceHeight", "I"); jfieldID fid_rotated = env->GetFieldID(frameClass, "rotated", "Z"); // copy frame info to java object const CCSize& sourceSize = frame->getOriginalSizeInPixels(); bool rotated = frame->isRotated(); const CCRect& frameRect = frame->getRectInPixels(); const CCPoint& offset = frame->getOffsetInPixels(); env->SetIntField(jFrame, fid_x, (int)frameRect.origin.x); env->SetIntField(jFrame, fid_y, (int)frameRect.origin.y); env->SetIntField(jFrame, fid_w, (int)frameRect.size.width); env->SetIntField(jFrame, fid_h, (int)frameRect.size.height); env->SetIntField(jFrame, fid_offsetX, (int)offset.x); env->SetIntField(jFrame, fid_offsetY, (int)offset.y); env->SetIntField(jFrame, fid_sourceWidth, (int)sourceSize.width); env->SetIntField(jFrame, fid_sourceHeight, (int)sourceSize.height); env->SetBooleanField(jFrame, fid_rotated, rotated); // release env->DeleteLocalRef(frameClass); env->ReleaseStringUTFChars(jPlist, plist); env->ReleaseStringUTFChars(jAtlas, atlas); env->ReleaseStringUTFChars(jImageName, imageName); }
bool CCParticleSystem::initWithDictionary(CCDictionary<std::string, CCObject*> *dictionary) { bool bRet = false; unsigned char *buffer = NULL; unsigned char *deflated = NULL; CCImage *image = NULL; do { int maxParticles = atoi(valueForKey("maxParticles", dictionary)); // self, not super if(this->initWithTotalParticles(maxParticles)) { // angle m_fAngle = (float)atof(valueForKey("angle", dictionary)); m_fAngleVar = (float)atof(valueForKey("angleVariance", dictionary)); // duration m_fDuration = (float)atof(valueForKey("duration", dictionary)); // blend function m_tBlendFunc.src = atoi(valueForKey("blendFuncSource", dictionary)); m_tBlendFunc.dst = atoi(valueForKey("blendFuncDestination", dictionary)); // color m_tStartColor.r = (float)atof(valueForKey("startColorRed", dictionary)); m_tStartColor.g = (float)atof(valueForKey("startColorGreen", dictionary)); m_tStartColor.b = (float)atof(valueForKey("startColorBlue", dictionary)); m_tStartColor.a = (float)atof(valueForKey("startColorAlpha", dictionary)); m_tStartColorVar.r = (float)atof(valueForKey("startColorVarianceRed", dictionary)); m_tStartColorVar.g = (float)atof(valueForKey("startColorVarianceGreen", dictionary)); m_tStartColorVar.b = (float)atof(valueForKey("startColorVarianceBlue", dictionary)); m_tStartColorVar.a = (float)atof(valueForKey("startColorVarianceAlpha", dictionary)); m_tEndColor.r = (float)atof(valueForKey("finishColorRed", dictionary)); m_tEndColor.g = (float)atof(valueForKey("finishColorGreen", dictionary)); m_tEndColor.b = (float)atof(valueForKey("finishColorBlue", dictionary)); m_tEndColor.a = (float)atof(valueForKey("finishColorAlpha", dictionary)); m_tEndColorVar.r = (float)atof(valueForKey("finishColorVarianceRed", dictionary)); m_tEndColorVar.g = (float)atof(valueForKey("finishColorVarianceGreen", dictionary)); m_tEndColorVar.b = (float)atof(valueForKey("finishColorVarianceBlue", dictionary)); m_tEndColorVar.a = (float)atof(valueForKey("finishColorVarianceAlpha", dictionary)); // particle size m_fStartSize = (float)atof(valueForKey("startParticleSize", dictionary)); m_fStartSizeVar = (float)atof(valueForKey("startParticleSizeVariance", dictionary)); m_fEndSize = (float)atof(valueForKey("finishParticleSize", dictionary)); m_fEndSizeVar = (float)atof(valueForKey("finishParticleSizeVariance", dictionary)); // position float x = (float)atof(valueForKey("sourcePositionx", dictionary)); float y = (float)atof(valueForKey("sourcePositiony", dictionary)); this->setPosition( ccp(x,y) ); m_tPosVar.x = (float)atof(valueForKey("sourcePositionVariancex", dictionary)); m_tPosVar.y = (float)atof(valueForKey("sourcePositionVariancey", dictionary)); // Spinning m_fStartSpin = (float)atof(valueForKey("rotationStart", dictionary)); m_fStartSpinVar = (float)atof(valueForKey("rotationStartVariance", dictionary)); m_fEndSpin= (float)atof(valueForKey("rotationEnd", dictionary)); m_fEndSpinVar= (float)atof(valueForKey("rotationEndVariance", dictionary)); m_nEmitterMode = atoi(valueForKey("emitterType", dictionary)); // Mode A: Gravity + tangential accel + radial accel if( m_nEmitterMode == kCCParticleModeGravity ) { // gravity modeA.gravity.x = (float)atof(valueForKey("gravityx", dictionary)); modeA.gravity.y = (float)atof(valueForKey("gravityy", dictionary)); // speed modeA.speed = (float)atof(valueForKey("speed", dictionary)); modeA.speedVar = (float)atof(valueForKey("speedVariance", dictionary)); const char * pszTmp = NULL; // radial acceleration pszTmp = valueForKey("radialAcceleration", dictionary); modeA.radialAccel = (pszTmp) ? (float)atof(pszTmp) : 0; pszTmp = valueForKey("radialAccelVariance", dictionary); modeA.radialAccelVar = (pszTmp) ? (float)atof(pszTmp) : 0; // tangential acceleration pszTmp = valueForKey("tangentialAcceleration", dictionary); modeA.tangentialAccel = (pszTmp) ? (float)atof(pszTmp) : 0; pszTmp = valueForKey("tangentialAccelVariance", dictionary); modeA.tangentialAccelVar = (pszTmp) ? (float)atof(pszTmp) : 0; } // or Mode B: radius movement else if( m_nEmitterMode == kCCParticleModeRadius ) { modeB.startRadius = (float)atof(valueForKey("maxRadius", dictionary)); modeB.startRadiusVar = (float)atof(valueForKey("maxRadiusVariance", dictionary)); modeB.endRadius = (float)atof(valueForKey("minRadius", dictionary)); modeB.endRadiusVar = 0; modeB.rotatePerSecond = (float)atof(valueForKey("rotatePerSecond", dictionary)); modeB.rotatePerSecondVar = (float)atof(valueForKey("rotatePerSecondVariance", dictionary)); } else { CCAssert( false, "Invalid emitterType in config file"); CC_BREAK_IF(true); } // life span m_fLife = (float)atof(valueForKey("particleLifespan", dictionary)); m_fLifeVar = (float)atof(valueForKey("particleLifespanVariance", dictionary)); // emission Rate m_fEmissionRate = m_uTotalParticles / m_fLife; // texture // Try to get the texture from the cache char *textureName = (char *)valueForKey("textureFileName", dictionary); std::string fullpath = CCFileUtils::fullPathFromRelativeFile(textureName, m_sPlistFile.c_str()); CCTexture2D *tex = NULL; if (strlen(textureName) > 0) { // set not pop-up message box when load image failed bool bNotify = CCFileUtils::getIsPopupNotify(); CCFileUtils::setIsPopupNotify(false); tex = CCTextureCache::sharedTextureCache()->addImage(fullpath.c_str()); // reset the value of UIImage notify CCFileUtils::setIsPopupNotify(bNotify); } if (tex) { this->m_pTexture = tex; } else { char *textureData = (char*)valueForKey("textureImageData", dictionary); CCAssert(textureData, ""); int dataLen = strlen(textureData); if(dataLen != 0) { // if it fails, try to get it from the base64-gzipped data int decodeLen = base64Decode((unsigned char*)textureData, (unsigned int)dataLen, &buffer); CCAssert( buffer != NULL, "CCParticleSystem: error decoding textureImageData"); CC_BREAK_IF(!buffer); int deflatedLen = ZipUtils::ccInflateMemory(buffer, decodeLen, &deflated); CCAssert( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); image = new CCImage(); bool isOK = image->initWithImageData(deflated, deflatedLen); CCAssert(isOK, "CCParticleSystem: error init image with Data"); CC_BREAK_IF(!isOK); m_pTexture = CCTextureCache::sharedTextureCache()->addUIImage(image, fullpath.c_str()); } } CCAssert( this->m_pTexture != NULL, "CCParticleSystem: error loading the texture"); CC_BREAK_IF(!m_pTexture); this->m_pTexture->retain(); bRet = true; } } while (0); CC_SAFE_DELETE_ARRAY(buffer); CC_SAFE_DELETE_ARRAY(deflated); CC_SAFE_DELETE(image); return bRet; }