Esempio n. 1
0
bool Properties::parseVec2(const char* str, Vec2* out)
{
    if (str)
    {
        float x, y;
        if (sscanf(str, "%f,%f", &x, &y) == 2)
        {
            if (out)
                out->set(x, y);
            return true;
        }
        else
        {
            CCLOGWARN("Error attempting to parse property as a two-dimensional vector: %s", str);
        }
    }

    if (out)
        out->set(0.0f, 0.0f);
    return false;
}
Esempio n. 2
0
bool Properties::parseVec4(const char* str, Vec4* out)
{
    if (str)
    {
        float x, y, z, w;
        if (sscanf(str, "%f,%f,%f,%f", &x, &y, &z, &w) == 4)
        {
            if (out)
                out->set(x, y, z, w);
            return true;
        }
        else
        {
            CCLOGWARN("Error attempting to parse property as a four-dimensional vector: %s", str);
        }
    }

    if (out)
        out->set(0.0f, 0.0f, 0.0f, 0.0f);
    return false;
}
Esempio n. 3
0
bool Properties::parseAxisAngle(const char* str, Quaternion* out)
{
    if (str)
    {
        float x, y, z, theta;
        if (sscanf(str, "%f,%f,%f,%f", &x, &y, &z, &theta) == 4)
        {
            if (out)
                out->set(Vec3(x, y, z), MATH_DEG_TO_RAD(theta));
            return true;
        }
        else
        {
            CCLOGWARN("Error attempting to parse property as an axis-angle rotation: %s", str);
        }
    }

    if (out)
        out->set(0.0f, 0.0f, 0.0f, 1.0f);
    return false;
}
Esempio n. 4
0
void RawStencilBufferTest::setup()
{
    glGetIntegerv(GL_STENCIL_BITS, &_stencilBits);
    if (_stencilBits < 3) {
        CCLOGWARN("Stencil must be enabled for the current GLView.");
    }
    
    for(int i = 0; i < _planeCount; ++i)
    {
        Sprite* sprite = Sprite::create(s_pathGrossini);
        sprite->setAnchorPoint(  Vec2(0.5, 0) );
        sprite->setScale( 2.5f );
        _sprites.pushBack(sprite);

        Sprite* sprite2 = Sprite::create(s_pathGrossini);
        sprite2->setAnchorPoint(  Vec2(0.5, 0) );
        sprite2->setScale( 2.5f );
        _spritesStencil.pushBack(sprite2);
    }

    Director::getInstance()->setAlphaBlending(true);
}
Esempio n. 5
0
bool CCTexture2D_richlabel::initWithRichString(const char *text, const char *fontName, float fontSize, const CCSize& dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    
	ccRichFontDefinition tempDef;
	
	tempDef._shadow._shadowEnabled = false;
	tempDef._stroke._strokeEnabled = false;
	
	
	tempDef._fontName      = std::string(fontName);
	tempDef._fontSize      = fontSize;
	tempDef._dimensions    = dimensions;
	tempDef._alignment     = hAlignment;
	tempDef._vertAlignment = vAlignment;
	tempDef._fontFillColor = ccWHITE;
    tempDef.m_shadowColor = 0;
    
	return initWithRichString(text, &tempDef);
	
#else
    CCLOGWARN("CCTexture2D_richlabel::initWithRichString only support iOS and Android");
    return false;
#endif
}
Esempio n. 6
0
void CCScrollBar::attachToCCScrollView(CCScrollView* scrollView, ccInsets insets, bool horizontal) {
    // it must have parent node
    CCNode* svParent = scrollView->getParent();
    if(!svParent) {
        CCLOGWARN("CCScrollView must be added to one node before calling attachToCCScrollView");
        return;
    }
    
	// save flag
	m_horizontal = horizontal;
	
	// add to scroll view
	float thumbLength = 0;
    CCPoint svOrigin = CCUtils::getOrigin(scrollView);
	CCSize svSize = scrollView->getViewSize();
	CCSize innerSize = scrollView->getContainer()->getContentSize();
	CCSize sbSize;
	if(horizontal) {
		sbSize = CCSizeMake(m_track->getContentSize().width,
							svSize.width - insets.left - insets.right);
		setContentSize(sbSize);
		setAnchorPoint(ccp(0, 0.5f));
		setPosition(ccp(svOrigin.x + svSize.width / 2, svOrigin.y + insets.bottom));
		setRotation(-90);
        UIWidget* svpWidght = dynamic_cast<UIWidget*>(svParent);
        if(svpWidght)
            svpWidght->addNode(this, MAX_INT);
        else
            svParent->addChild(this, MAX_INT);
		
		// thumb length
		if(m_fixedThumb)
			thumbLength = m_fixedThumb->getContentSize().height;
		else
			thumbLength = MIN(1, svSize.width / innerSize.width) * sbSize.height;
	} else {
		sbSize = CCSizeMake(m_track->getContentSize().width,
							svSize.height - insets.top - insets.bottom);
		setContentSize(sbSize);
		setAnchorPoint(ccp(1, 0.5f));
		setPosition(ccp(svOrigin.x + svSize.width - insets.right, svOrigin.y + svSize.height / 2));
        UIWidget* svpWidght = dynamic_cast<UIWidget*>(svParent);
        if(svpWidght)
            svpWidght->addNode(this, MAX_INT);
        else
            svParent->addChild(this, MAX_INT);
		
		// thumb length
		if(m_fixedThumb)
			thumbLength = m_fixedThumb->getContentSize().height;
		else
			thumbLength = MIN(1, svSize.height / innerSize.height) * sbSize.height;
	}
	
	// add track
	m_track->setPreferredSize(sbSize);
	m_track->setPosition(CCUtils::getLocalCenter(this));
	addChild(m_track);
	
	// clipping node to hold thumb
	CCClippingNode* thumbClipping = CCClippingNode::create(m_track);
	thumbClipping->ignoreAnchorPointForPosition(false);
	thumbClipping->setAnchorPoint(ccp(0.5f, 0.5f));
	thumbClipping->setContentSize(sbSize);
	thumbClipping->setPosition(CCUtils::getLocalCenter(this));
	thumbClipping->setAlphaThreshold(0.5f);
	thumbClipping->setScaleX((sbSize.width - 4) / sbSize.width);
	thumbClipping->setScaleY((sbSize.height - 4) / sbSize.height);
	addChild(thumbClipping);
	
	// thumb or fixed thumb
	if(m_thumb) {
		m_thumb->setPreferredSize(CCSizeMake(sbSize.width, thumbLength));
		m_thumb->setPosition(ccp(sbSize.width / 2,
								 sbSize.height - thumbLength / 2));
		thumbClipping->addChild(m_thumb);
	} else {
		m_fixedThumb->setPosition(ccp(sbSize.width / 2,
									  sbSize.height - thumbLength / 2));
		thumbClipping->addChild(m_fixedThumb);
	}
	
	// sync thumb position
	syncThumbPositionForCCScrollView(scrollView);
    
    // delegate
    m_oldCCDelegate = scrollView->getDelegate();
    scrollView->setDelegate(this);
    
    // init fade out
    if(m_initFadeOut) {
        m_fadingOut = true;
        CCUtils::setOpacityRecursively(this, 0);
    }
}
	void SimpleAudioEngine::rewindBackgroundMusic()
	{
        CCLOGWARN("Cannot rewind background in Emscripten");
	}
Esempio n. 8
0
//.mtl file should at the same directory with the same name if exist
bool Sprite3D::loadFromObj(const std::string& path)
{
    std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
    
    //find from the cache
    std::string key = fullPath + "#";
    auto mesh = MeshCache::getInstance()->getMesh(key);
    if (mesh)
    {
        _mesh = mesh;
        _mesh->retain();
        
        auto tex = Sprite3DMaterialCache::getInstance()->getSprite3DMaterial(key);
        setTexture(tex);
        
        genGLProgramState();
        
        return true;
    }
    
    //.mtl file directory
    std::string dir = "";
    auto last = fullPath.rfind("/");
    if (last != -1)
        dir = fullPath.substr(0, last + 1);
    
    ObjLoader::shapes_t shapes;
    std::string errstr = ObjLoader::LoadObj(shapes, fullPath.c_str(), dir.c_str());
    if (!errstr.empty())
        return false;
    
    //convert to mesh and material
    std::vector<unsigned short> indices;
    std::vector<std::string> matnames;
    std::string texname;
    for (auto it = shapes.shapes.begin(); it != shapes.shapes.end(); it++)
    {
        indices.insert(indices.end(), (*it).mesh.indices.begin(),(*it).mesh.indices.end());
        //indices.push_back((*it).mesh.indices);
        if (texname.empty())
            texname = (*it).material.diffuse_texname;
        else if (texname != (*it).material.diffuse_texname)
        {
            CCLOGWARN("cocos2d:WARNING: more than one texture in %s", path.c_str());
        }
            
        matnames.push_back(dir + (*it).material.diffuse_texname);
    }
    _mesh = Mesh::create(shapes.positions, shapes.normals, shapes.texcoords, indices);
    
    _mesh->retain();
    if (_mesh == nullptr)
        return false;
    
    if (matnames.size())
    {
        setTexture(matnames[0]);
    }
    genGLProgramState();
    
    //add to cache
    
    if (_texture)
    {
        Sprite3DMaterialCache::getInstance()->addSprite3DMaterial(key, _texture);
    }
    
    MeshCache::getInstance()->addMesh(key, _mesh);

    return true;
}
Esempio n. 9
0
bool GAFAsset::initWithImageData(const std::string& jsonPath)
{
		
	GAFData aConfigData;
	std::string fp = CCFileUtils::sharedFileUtils()->fullPathForFilename(jsonPath.c_str());
	
	aConfigData.delete_data = true;
	aConfigData.ptr = CCFileUtils::sharedFileUtils()->getFileData(fp.c_str(), "rb", &aConfigData.size);
	if (!aConfigData.ptr)
	{
		CCLOGERROR("Can not get data from json file : %s", jsonPath.c_str());
		return NULL;
	}

	if (!aConfigData.getBytes())
	{
		CCLOGWARN("can not init GAFAsset - invalid anImageData");
		return false;
	}
	
	CCDictionary* configDictionary = CCJSONConverter::sharedConverter()->dictionaryFrom( (const char *)aConfigData.getBytes());
	
	CCString *versionNode               = (CCString*)configDictionary->objectForKey(kVersionKey);
	
	if (!isAssetVersionPlayable(versionNode->getCString()))
	{
		return false;
	}
	CCArray *animationConfigFrames      = (CCArray *)configDictionary->objectForKey(kAnimationConfigFramesKey);
	CCArray *interactionObjectNodes     = (CCArray *)configDictionary->objectForKey(kInteractionObjectsKey);
	CCArray *standObjectsNodes          = (CCArray *)configDictionary->objectForKey(kStandObjectsKey);
	CCArray *textureAtlasNode           = (CCArray *)configDictionary->objectForKey(kTextureAtlasKey);
	CCArray *animationSequences         = (CCArray *)configDictionary->objectForKey(kAnimationSequencesKey);
	
	CCDictionary *objectNodes           = (CCDictionary *)configDictionary->objectForKey(kAnimationObjectsKey);
	CCDictionary *masksNodes            = (CCDictionary *)configDictionary->objectForKey(kAnimationMasksKey);
	CCDictionary *namedPartsNodes       = (CCDictionary *)configDictionary->objectForKey(kAnimationNamedPartsKey);

	
	if (!animationConfigFrames || !textureAtlasNode|| !objectNodes)
	{
		CCLOGERROR("Error while creating GAFAsset. Required subnodes in dictionary are missing.");
		return false;
	}
	
	CC_SAFE_RELEASE(_textureAtlas);
	
	if (!textureAtlasNode->count())
	{
		return false;
	}

	CCDictionary * atlasDictionary = (CCDictionary *)textureAtlasNode->objectAtIndex(0);
	float atlasScale = atlasScaleFromAtlasConfig(atlasDictionary);
	for (int i = 1; i < textureAtlasNode->count(); ++i)
	{
		CCDictionary * a = (CCDictionary *)textureAtlasNode->objectAtIndex(i);
		float as = atlasScaleFromAtlasConfig(a);
		if ( fabs(atlasScale - _currentDeviceScale) > fabs(as - _currentDeviceScale))
		{
			atlasDictionary = a;
			atlasScale = as;
		}
	}
	
	_usedAtlasContentScaleFactor = atlasScale;
	CCArray * atlasesInfo = (CCArray *)atlasDictionary->objectForKey(kAtlasInfoKey);
	if (!atlasesInfo)
	{
		CCLOGERROR("Error while creating GAFAsset.atlasesInfo subnode is missing in atlasDictionary.");
		return false;
	}
	
	_textureAtlas = GAFTextureAtlas::create(fp.c_str(), atlasDictionary);
	if (!_textureAtlas)
	{
		CCLOGERROR("Failed to initialize GAFAsset. GAFTextureAtlas could not be created.");
		return false;
	}
	CC_SAFE_RETAIN(_textureAtlas);
	
	if (_objects != objectNodes)
	{
		CC_SAFE_RELEASE(_objects);
		_objects = objectNodes;
		CC_SAFE_RETAIN(_objects);
	}
	
	if (_masks != masksNodes)
	{
		CC_SAFE_RELEASE(_masks);
		_masks	  = masksNodes;
		CC_SAFE_RETAIN(_masks);
	}
	
	if (_namedParts != namedPartsNodes)
	{
		CC_SAFE_RELEASE(_namedParts);
		_namedParts	  = namedPartsNodes;
		CC_SAFE_RETAIN(_namedParts);
	}
	
	if (interactionObjectNodes)
	{
		CC_SAFE_RELEASE(_interactionObjects);
		_interactionObjects = CCArray::create();
		CC_SAFE_RETAIN(_interactionObjects);
		
		for (int i = 0; i < interactionObjectNodes->count(); ++i)
		{
			CCDictionary * dict = (CCDictionary*)interactionObjectNodes->objectAtIndex(i);
			
			GAFInteractionObject * interObject = GAFInteractionObject::create(dict);
			if (interObject)
			{
				_interactionObjects->addObject(interObject);
			}
		}
	}
	
	if (standObjectsNodes)
	{
		CC_SAFE_RELEASE(_standObjects);
		_standObjects = CCArray::create();
		CC_SAFE_RETAIN(_standObjects);
		
		for (int i = 0; i < standObjectsNodes->count(); ++i)
		{
			CCDictionary * dict = (CCDictionary*)standObjectsNodes->objectAtIndex(i);
			
			GAFActionObject * interObject = GAFActionObject::create(dict);
			if (interObject)
			{
				_standObjects->addObject(interObject);
			}
		}
	}
	
	loadFramesFromConfigDictionary(configDictionary);
	
	if (animationSequences)
	{
		loadAnimationSequences(animationSequences);
	}
	return true;
}
bool BillboardParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname)
{
    bool ret = false;
    unsigned char *buffer = nullptr;
    unsigned char *deflated = nullptr;
    Image *image = nullptr;
    do 
    {
        int maxParticles = dictionary["maxParticles"].asInt();
        // self, not super
        if(this->initWithTotalParticles(maxParticles))
        {
            // Emitter name in particle designer 2.0
            _configName = dictionary["configName"].asString();

            // angle
            _angle = dictionary["angle"].asFloat();
            _angleVar = dictionary["angleVariance"].asFloat();

            // duration
            _duration = dictionary["duration"].asFloat();

            // blend function 
            if (_configName.length()>0)
            {
                _blendFunc.src = dictionary["blendFuncSource"].asFloat();
            }
            else
            {
                _blendFunc.src = dictionary["blendFuncSource"].asInt();
            }
            _blendFunc.dst = dictionary["blendFuncDestination"].asInt();

            // color
            _startColor.r = dictionary["startColorRed"].asFloat();
            _startColor.g = dictionary["startColorGreen"].asFloat();
            _startColor.b = dictionary["startColorBlue"].asFloat();
            _startColor.a = dictionary["startColorAlpha"].asFloat();

            _startColorVar.r = dictionary["startColorVarianceRed"].asFloat();
            _startColorVar.g = dictionary["startColorVarianceGreen"].asFloat();
            _startColorVar.b = dictionary["startColorVarianceBlue"].asFloat();
            _startColorVar.a = dictionary["startColorVarianceAlpha"].asFloat();

            _endColor.r = dictionary["finishColorRed"].asFloat();
            _endColor.g = dictionary["finishColorGreen"].asFloat();
            _endColor.b = dictionary["finishColorBlue"].asFloat();
            _endColor.a = dictionary["finishColorAlpha"].asFloat();

            _endColorVar.r = dictionary["finishColorVarianceRed"].asFloat();
            _endColorVar.g = dictionary["finishColorVarianceGreen"].asFloat();
            _endColorVar.b = dictionary["finishColorVarianceBlue"].asFloat();
            _endColorVar.a = dictionary["finishColorVarianceAlpha"].asFloat();

            // particle size
            _startSize = dictionary["startParticleSize"].asFloat();
            _startSizeVar = dictionary["startParticleSizeVariance"].asFloat();
            _endSize = dictionary["finishParticleSize"].asFloat();
            _endSizeVar = dictionary["finishParticleSizeVariance"].asFloat();

            // position
            float x = dictionary["sourcePositionx"].asFloat();
            float y = dictionary["sourcePositiony"].asFloat();
            this->setPosition( Vec2(x,y) );            
            _posVar.x = dictionary["sourcePositionVariancex"].asFloat();
            _posVar.y = dictionary["sourcePositionVariancey"].asFloat();

            // Spinning
            _startSpin = dictionary["rotationStart"].asFloat();
            _startSpinVar = dictionary["rotationStartVariance"].asFloat();
            _endSpin= dictionary["rotationEnd"].asFloat();
            _endSpinVar= dictionary["rotationEndVariance"].asFloat();

            _emitterMode = (Mode) dictionary["emitterType"].asInt();

            // Mode A: Gravity + tangential accel + radial accel
            if (_emitterMode == Mode::GRAVITY)
            {
                // gravity
                modeA.gravity.x = dictionary["gravityx"].asFloat();
                modeA.gravity.y = dictionary["gravityy"].asFloat();

                // speed
                modeA.speed = dictionary["speed"].asFloat();
                modeA.speedVar = dictionary["speedVariance"].asFloat();

                // radial acceleration
                modeA.radialAccel = dictionary["radialAcceleration"].asFloat();
                modeA.radialAccelVar = dictionary["radialAccelVariance"].asFloat();

                // tangential acceleration
                modeA.tangentialAccel = dictionary["tangentialAcceleration"].asFloat();
                modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].asFloat();

                // rotation is dir
                modeA.rotationIsDir = dictionary["rotationIsDir"].asBool();
            }

            // or Mode B: radius movement
            else if (_emitterMode == Mode::RADIUS)
            {
                if (_configName.length()>0)
                {
                    modeB.startRadius = dictionary["maxRadius"].asInt();
                }
                else
                {
                    modeB.startRadius = dictionary["maxRadius"].asFloat();
                }
                modeB.startRadiusVar = dictionary["maxRadiusVariance"].asFloat();
                if (_configName.length()>0)
                {
                    modeB.endRadius = dictionary["minRadius"].asInt();
                }
                else
                {
                    modeB.endRadius = dictionary["minRadius"].asFloat();
                }

                if (dictionary.find("minRadiusVariance") != dictionary.end())
                {
                    modeB.endRadiusVar = dictionary["minRadiusVariance"].asFloat();
                }
                else
                {
                    modeB.endRadiusVar = 0.0f;
                }

                if (_configName.length()>0)
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asInt();
                }
                else
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asFloat();
                }
                modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].asFloat();

            } else {
                CCASSERT( false, "Invalid emitterType in config file");
                CC_BREAK_IF(true);
            }

            // life span
            _life = dictionary["particleLifespan"].asFloat();
            _lifeVar = dictionary["particleLifespanVariance"].asFloat();

            // emission Rate
            _emissionRate = _totalParticles / _life;


            // Set a compatible default for the alpha transfer
            _opacityModifyRGB = false;

            // texture        
            // Try to get the texture from the cache
            std::string textureName = dictionary["textureFileName"].asString();

            size_t rPos = textureName.rfind('/');

            if (rPos != string::npos)
            {
                string textureDir = textureName.substr(0, rPos + 1);

                if (!dirname.empty() && textureDir != dirname)
                {
                    textureName = textureName.substr(rPos+1);
                    textureName = dirname + textureName;
                }
            }
            else if (!dirname.empty() && !textureName.empty())
            {
                textureName = dirname + textureName;
            }

            Texture2D *tex = nullptr;

            if (textureName.length() > 0)
            {
                // set not pop-up message box when load image failed
                bool notify = FileUtils::getInstance()->isPopupNotify();
                FileUtils::getInstance()->setPopupNotify(false);
                tex = Director::getInstance()->getTextureCache()->addImage(textureName);
                // reset the value of UIImage notify
                FileUtils::getInstance()->setPopupNotify(notify);
            }

            if (tex)
            {
                setTexture(tex);
            }
            else if( dictionary.find("textureImageData") != dictionary.end() )
            {                        
                std::string textureData = dictionary.at("textureImageData").asString();
                CCASSERT(!textureData.empty(), "");

                auto dataLen = textureData.size();
                if (dataLen != 0)
                {
                    // if it fails, try to get it from the base64-gzipped data    
                    int decodeLen = base64Decode((unsigned char*)textureData.c_str(), (unsigned int)dataLen, &buffer);
                    CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData");
                    CC_BREAK_IF(!buffer);

                    ssize_t deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated);
                    CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData");
                    CC_BREAK_IF(!deflated);

                    // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage()
                    image = new (std::nothrow) Image();
                    bool isOK = image->initWithImageData(deflated, deflatedLen);
                    CCASSERT(isOK, "CCParticleSystem: error init image with Data");
                    CC_BREAK_IF(!isOK);

                    setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str()));

                    image->release();
                }
            }

            _yCoordFlipped = dictionary.find("yCoordFlipped") == dictionary.end() ? 1 : dictionary.at("yCoordFlipped").asInt();

            if( !this->_texture)
                CCLOGWARN("cocos2d: Warning: ParticleSystemQuad system without a texture");
            ret = true;
        }
    } while (0);
    free(buffer);
    free(deflated);
    return ret;
}
CCObject* CCJSONParser::load(const char* json, size_t length) {
	// use memory input stream
	CCMemoryInputStream* mis = CCMemoryInputStream::create((char*)json, length);

	// status of yajl
	yajl_status stat;

	// get gen instance
	yajl_gen g = yajl_gen_alloc(NULL);

	// register callback
	ccJSONContext ctx;
    ctx.g = g;
    ctx.root = NULL;
    ctx.objStack = new vector<CCObject*>();
    ctx.flagStack = new vector<bool>();
	yajl_handle hand = yajl_alloc(&callbacks, NULL, (void*)&ctx);

	// config yajl
	yajl_gen_config(g, yajl_gen_beautify, 1);
	yajl_gen_config(g, yajl_gen_validate_utf8, 1);
	yajl_config(hand, yajl_allow_comments, 1);

	// parse
	char buf[4096];
	while(true) {
		// read data
		int rd = mis->read(buf, 4096);
		if (rd == 0)
			break;

		// parese data
		stat = yajl_parse(hand, (const unsigned char*)buf, rd);

		// if parse error, break
		if (stat != yajl_status_ok)
			break;
	}

	// complete parse
	stat = yajl_complete_parse(hand);

	// check error
	if (stat != yajl_status_ok) {
		unsigned char* str = yajl_get_error(hand, 1, (const unsigned char*)json, length);
		CCLOGWARN("parse json error: %s", str);
		yajl_free_error(hand, str);

		// when error, doesn't return anything
		ctx.root = NULL;
	}

	// free
	yajl_gen_free(g);
	yajl_free(hand);
	delete ctx.objStack;
	delete ctx.flagStack;

	// return
	return ctx.root;
}
Esempio n. 12
0
bool RapidParticle::initParticlePro( RapidParticle* particle  )
{
	bool ret = false;
	unsigned char *buffer = nullptr;
	unsigned char *deflated = nullptr;

	do 
	{
		int maxParticles = particle->getTotalParticles();;
		// self, not super
		if(this->initWithTotalParticles(maxParticles))
		{
			// angle
			_angle = particle->getAngle();
			_angleVar = particle->getAngleVar();

			// duration
			_duration = particle->getDuration();

			_blendFunc.src = particle->getBlendFunc().src;
			_blendFunc.dst = particle->getBlendFunc().dst;

			// color
			_startColor.r = particle->getStartColor().r;
			_startColor.g = particle->getStartColor().g;
			_startColor.b = particle->getStartColor().b;
			_startColor.a = particle->getStartColor().a;

			_startColorVar.r = particle->getStartColorVar().r;
			_startColorVar.g = particle->getStartColorVar().g;
			_startColorVar.b = particle->getStartColorVar().b;
			_startColorVar.a = particle->getStartColorVar().a;

			_endColor.r = particle->getEndColor().r;
			_endColor.g = particle->getEndColor().g;
			_endColor.b = particle->getEndColor().b;
			_endColor.a = particle->getEndColor().a;

			_endColorVar.r = particle->getEndColorVar().r;
			_endColorVar.g = particle->getEndColorVar().g;
			_endColorVar.b = particle->getEndColorVar().b;
			_endColorVar.a = particle->getEndColorVar().a;

			// particle size
			_startSize = particle->getStartSize();
			_startSizeVar = particle->getStartSizeVar();
			_endSize = particle->getEndSize();
			_endSizeVar = particle->getEndSizeVar();

			// position
			float x = particle->getSourcePosition().x;
			float y = particle->getSourcePosition().y;
			this->setPosition(x,y);            
			_posVar.x = particle->getPosVar().x;
			_posVar.y = particle->getPosVar().y;

			// Spinning
			_startSpin = particle->getStartSpin(); 
			_startSpinVar = particle->getStartSpinVar(); 
			_endSpin= particle->getEndSpin(); 
			_endSpinVar= particle->getEndSpinVar(); 

			_emitterMode = particle->getEmitterMode(); 

			// Mode A: Gravity + tangential accel + radial accel
			if (_emitterMode == Mode::GRAVITY)
			{
				// gravity
				modeA.gravity.x = particle->getGravity().x; 
				modeA.gravity.y = particle->getGravity().y; 

				// speed
				modeA.speed = particle->getSpeed(); 
				modeA.speedVar = particle->getSpeedVar(); 

				// radial acceleration
				modeA.radialAccel = particle->getRadialAccel(); 
				modeA.radialAccelVar = particle->getRadialAccelVar(); 

				// tangential acceleration
				modeA.tangentialAccel = particle->getTangentialAccel();
				modeA.tangentialAccelVar = particle->getTangentialAccelVar();

				// rotation is dir
				modeA.rotationIsDir = particle->getRotationIsDir();
			}

			// or Mode B: radius movement
			else if (_emitterMode == Mode::RADIUS)
			{
				modeB.startRadius = particle->getStartRadius();
				modeB.startRadiusVar = particle->getStartRadiusVar();

				modeB.endRadius = particle->getEndRadius();
				modeB.endRadiusVar = particle->getEndRadiusVar();

				modeB.rotatePerSecond = particle->getRotatePerSecond();
				modeB.rotatePerSecondVar = particle->getRotatePerSecondVar();

			} else {
				CCASSERT( false, "Invalid emitterType in config file");
				CC_BREAK_IF(true);
			}

			// life span
			_life = particle->getLife();
			_lifeVar = particle->getLifeVar();

			// emission Rate
			_emissionRate = _totalParticles / _life;

			//don't get the internal texture if a batchNode is used
			if (!_batchNode)
			{
				// Set a compatible default for the alpha transfer
				_opacityModifyRGB = false;

				Texture2D* tex = particle->getTexture();			//Ìùͼ

				if (tex)
				{
					setTexture(tex);
				}
				else
				{                        
					CCASSERT(tex != nullptr, "particle texture is null");
				}

				if( !this->_texture)
					CCLOGWARN("cocos2d: Warning: ParticleSystemQuad system without a texture");
			}
			ret = true;
		}
	} while (0);
	free(buffer);
	free(deflated);
	return ret;

}
Esempio n. 13
0
void TMXFileParser::textHandler(void* ctx, const char* text, int len)
{
    if (m_bFailed || m_stState.empty())
    {
        m_bFailed = true;
        return;
    }
    
    ParserState s = m_stState.top().first;
    StatePointer p = m_stState.top().second;
    
    switch (s)
    {
        case ParserState::ParseStart:
        case ParserState::ParseMapNode:
        case ParserState::ParseTileSetNode:
        case ParserState::ParseTileSetImageNode:
        case ParserState::ParseTileSetTileNode:
        case ParserState::ParseLayerNode:
        case ParserState::ParseObjectLayerNode:
        case ParserState::ParseObjectLayerObjectNode:
        case ParserState::ParsePropertyListNode:
        case ParserState::ParsePropertyListPropertyNode:
            PARSEFAILED("unexpected data.");
            break;
        case ParserState::ParseLayerDataNode:
            // 手动trim
            while (len > 0 && text[len - 1] > 0 && ::isspace(text[len - 1]))
                --len;
            while (len > 0 && text[0] > 0 && ::isspace(text[0]))
            {
                --len;
                ++text;
            }
            
            // 解码base64串
            if (len > 0)
            {
                unsigned char* pOut = nullptr;
                int decodeLen = base64Decode((const unsigned char*)text, len, &pOut);
                if (decodeLen == p.pTiledLayer->GetWidth() * p.pTiledLayer->GetHeight() * sizeof(uint32_t))
                {
                    // 解析图块数据
                    const uint32_t* pGid = reinterpret_cast<uint32_t*>(pOut);
                    for (uint32_t iY = 0; iY < p.pTiledLayer->GetHeight(); ++iY)
                    {
                        for (uint32_t iX = 0; iX < p.pTiledLayer->GetWidth(); ++iX)
                            p.pTiledLayer->SetGidOfXY(iX, p.pTiledLayer->GetHeight() - iY - 1, *(pGid++));
                    }
                    free(pOut);
                }
                else
                {
                    if (pOut)
                        free(pOut);
                    PARSEFAILED("failed to decode map data, size %d mistached.", decodeLen);
                }
            }
            else
            {
                CCLOGWARN("TMXFileParser: empty layer data.");
            }
            break;
        default:
            m_bFailed = true;
            CCASSERT(0, "TMXFileParser: unexpected code routine.");
            break;
    }
}
Esempio n. 14
0
bool CCPreLoad::cacheFramesForPlist(const char* plist, const char* textureFileName)
{
	bool ret = false;
	do{
		//private权限不好继承,直接挑出来改,Zwoptex.swf 1.0的version
		CCTexture2D *pobTexture = CCTextureCache::sharedTextureCache()->addImage(textureFileName);
		if(pobTexture == NULL)
			break;

		string pszPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist);
		CCDictionary *dictionary = CCDictionary::createWithContentsOfFileThreadSafe(pszPath.c_str());

		CCDictionary *framesDict = (CCDictionary*)dictionary->objectForKey("frames");
		int format = 0;

		CCDictElement* pElement = NULL;
		CCDICT_FOREACH(framesDict, pElement)
		{
			CCDictionary* frameDict = (CCDictionary*)pElement->getObject();
			std::string spriteFrameName = pElement->getStrKey();
			CCSpriteFrame* spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(spriteFrameName.c_str());
			if (spriteFrame)
			{
				continue;
			}
		    
			int format = 0;//就只挑这个
			if(format == 0) 
			{
				float x = frameDict->valueForKey("x")->floatValue();
				float y = frameDict->valueForKey("y")->floatValue();
				float w = frameDict->valueForKey("width")->floatValue();
				float h = frameDict->valueForKey("height")->floatValue();
				float ox = frameDict->valueForKey("offsetX")->floatValue();
				float oy = frameDict->valueForKey("offsetY")->floatValue();
				int ow = frameDict->valueForKey("originalWidth")->intValue();
				int oh = frameDict->valueForKey("originalHeight")->intValue();
				// check ow/oh
				if(!ow || !oh)
				{
					CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
				}
				// abs ow/oh
				ow = abs(ow);
				oh = abs(oh);
				// create frame
				spriteFrame = new CCSpriteFrame();
				spriteFrame->initWithTexture(pobTexture, 
											CCRectMake(x, y, w, h), 
											false,
											CCPointMake(ox, oy),
											CCSizeMake((float)ow, (float)oh)
											);
			} 

			// add sprite frame
			CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFrame(spriteFrame, spriteFrameName.c_str());
			m_tmpFrames.insert(make_pair(spriteFrameName,spriteFrame));
			spriteFrame->release();
		}
		dictionary->release();
		ret = true;
	}while(0);
Esempio n. 15
0
CCTexture2D* TextureHelper::addImageFromPlist(const char* plist)
{
	std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist);
	CCDictionary *dict = CCDictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
	CCDictionary *metadataDict = (CCDictionary*)dict->objectForKey("metadata");
	std::string pngPath = metadataDict->valueForKey("realTextureFileName")->getCString();
	CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addImage(pngPath.c_str());
	CCDictionary *framesDict = (CCDictionary*)dict->objectForKey("frames");
	int format = 0;
	CCSize textureSize = texture->getContentSize();

	if(metadataDict != NULL) 
	{
		format = metadataDict->valueForKey("format")->intValue();
	}

	CCAssert(format >=0 && format <= 3, "format is not supported for CCSpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");

	CCDictElement* pElement = NULL;
	CCDICT_FOREACH(framesDict, pElement)
	{
		CCRect rect;
		CCDictionary* frameDict = (CCDictionary*)pElement->getObject();
		std::string spriteFrameName = pElement->getStrKey();
	
		if(format == 0) 
		{
			float x = frameDict->valueForKey("x")->floatValue();
			float y = frameDict->valueForKey("y")->floatValue();
			float w = frameDict->valueForKey("width")->floatValue();
			float h = frameDict->valueForKey("height")->floatValue();
			float ox = frameDict->valueForKey("offsetX")->floatValue();
			float oy = frameDict->valueForKey("offsetY")->floatValue();
			int ow = frameDict->valueForKey("originalWidth")->intValue();
			int oh = frameDict->valueForKey("originalHeight")->intValue();
			if(!ow || !oh)
			{
				CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
			}
			ow = abs(ow);
			oh = abs(oh);
			rect = CCRectMake(x + ox,textureSize.height - y + oy,ow,oh);
		 } 
		 else if(format == 1 || format == 2) 
		 {
			  CCRect frame = CCRectFromString(frameDict->valueForKey("frame")->getCString());
			  frame.origin.y = textureSize.height - frame.origin.y;
			  bool rotated = false;

			  if (format == 2)
			  {
				  rotated = frameDict->valueForKey("rotated")->boolValue();
			  }

			  CCPoint offset = CCPointFromString(frameDict->valueForKey("offset")->getCString());
			  CCSize sourceSize = CCSizeFromString(frameDict->valueForKey("sourceSize")->getCString());
			  rect = frame;
		  } 
		  else if (format == 3)
		  {
			  CCSize spriteSize = CCSizeFromString(frameDict->valueForKey("spriteSize")->getCString());
			  CCPoint spriteOffset = CCPointFromString(frameDict->valueForKey("spriteOffset")->getCString());
			  CCSize spriteSourceSize = CCSizeFromString(frameDict->valueForKey("spriteSourceSize")->getCString());
			  CCRect textureRect = CCRectFromString(frameDict->valueForKey("textureRect")->getCString());
			  bool textureRotated = frameDict->valueForKey("textureRotated")->boolValue();
			  rect = textureRect;
		  }
		 rectMap.insert(std::pair<std::string,CCRect>(spriteFrameName,rect));
	}