Merge branch 'develop' into console

Conflicts:
	cocos/scripting/auto-generated
This commit is contained in:
Ricardo Quesada 2013-12-04 21:58:11 -08:00
commit 6a034a91f1
100 changed files with 2877 additions and 2109 deletions

View File

@ -1 +1 @@
952fb6950a128b17bdd2a4ffb998c22319a95bf0
c3b97117ff38c9347b34f01a67fd7206af29194d

View File

@ -1 +1 @@
edaf6572f44b700ec70e3122e91b48d728ebce7a
133130a8ae8d6597399a7de05ba9b63ee55f5e2d

View File

@ -129,6 +129,7 @@ platform/CCThread.cpp \
../base/CCObject.cpp \
../base/CCSet.cpp \
../base/CCString.cpp \
../base/CCValue.cpp \
../base/etc1.cpp \
../base/s3tc.cpp \
../base/CCConsole.cpp \

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "CCActionInterval.h"
#include "CCNode.h"
#include "CCDirector.h"
#include "CCString.h"
NS_CC_BEGIN
//

View File

@ -198,21 +198,21 @@ Sequence* Sequence::createWithVariableList(FiniteTimeAction *pAction1, va_list a
return ((Sequence*)pPrev);
}
Sequence* Sequence::create(Array* arrayOfActions)
Sequence* Sequence::create(const Vector<FiniteTimeAction*>& arrayOfActions)
{
Sequence* pRet = NULL;
do
{
long count = arrayOfActions->count();
long count = arrayOfActions.size();
CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
auto prev = arrayOfActions.at(0);
if (count > 1)
{
for (long i = 1; i < count; ++i)
{
prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(i)));
prev = createWithTwoActions(prev, arrayOfActions.at(i));
}
}
else
@ -571,19 +571,19 @@ Spawn* Spawn::createWithVariableList(FiniteTimeAction *pAction1, va_list args)
return ((Spawn*)pPrev);
}
Spawn* Spawn::create(Array *arrayOfActions)
Spawn* Spawn::create(const Vector<FiniteTimeAction*>& arrayOfActions)
{
Spawn* pRet = NULL;
do
{
long count = arrayOfActions->count();
long count = arrayOfActions.size();
CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
auto prev = arrayOfActions.at(0);
if (count > 1)
{
for (int i = 1; i < arrayOfActions->count(); ++i)
for (int i = 1; i < arrayOfActions.size(); ++i)
{
prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(i)));
prev = createWithTwoActions(prev, arrayOfActions.at(i));
}
}
else
@ -591,7 +591,7 @@ Spawn* Spawn::create(Array *arrayOfActions)
// If only one action is added to Spawn, make up a Spawn by adding a simplest finite time action.
prev = createWithTwoActions(prev, ExtraAction::create());
}
pRet = (Spawn*)prev;
pRet = static_cast<Spawn*>(prev);
}while (0);
return pRet;
@ -2003,31 +2003,28 @@ Animate::~Animate()
CC_SAFE_DELETE(_splitTimes);
}
bool Animate::initWithAnimation(Animation *pAnimation)
bool Animate::initWithAnimation(Animation* animation)
{
CCASSERT( pAnimation!=NULL, "Animate: argument Animation must be non-NULL");
CCASSERT( animation!=NULL, "Animate: argument Animation must be non-NULL");
float singleDuration = pAnimation->getDuration();
float singleDuration = animation->getDuration();
if ( ActionInterval::initWithDuration(singleDuration * pAnimation->getLoops() ) )
if ( ActionInterval::initWithDuration(singleDuration * animation->getLoops() ) )
{
_nextFrame = 0;
setAnimation(pAnimation);
setAnimation(animation);
_origFrame = NULL;
_executedLoops = 0;
_splitTimes->reserve(pAnimation->getFrames()->count());
_splitTimes->reserve(animation->getFrames().size());
float accumUnitsOfTime = 0;
float newUnitOfTimeValue = singleDuration / pAnimation->getTotalDelayUnits();
float newUnitOfTimeValue = singleDuration / animation->getTotalDelayUnits();
Array* pFrames = pAnimation->getFrames();
CCARRAY_VERIFY_TYPE(pFrames, AnimationFrame*);
auto frames = animation->getFrames();
Object* pObj = NULL;
CCARRAY_FOREACH(pFrames, pObj)
for (auto& frame : frames)
{
AnimationFrame* frame = static_cast<AnimationFrame*>(pObj);
float value = (accumUnitsOfTime * newUnitOfTimeValue) / singleDuration;
accumUnitsOfTime += frame->getDelayUnits();
_splitTimes->push_back(value);
@ -2099,20 +2096,20 @@ void Animate::update(float t)
t = fmodf(t, 1.0f);
}
Array* frames = _animation->getFrames();
long numberOfFrames = frames->count();
auto frames = _animation->getFrames();
long numberOfFrames = frames.size();
SpriteFrame *frameToDisplay = NULL;
for( int i=_nextFrame; i < numberOfFrames; i++ ) {
float splitTime = _splitTimes->at(i);
if( splitTime <= t ) {
AnimationFrame* frame = static_cast<AnimationFrame*>(frames->getObjectAtIndex(i));
AnimationFrame* frame = frames.at(i);
frameToDisplay = frame->getSpriteFrame();
static_cast<Sprite*>(_target)->setDisplayFrame(frameToDisplay);
Dictionary* dict = frame->getUserInfo();
if( dict )
const ValueMap& dict = frame->getUserInfo();
if ( !dict.empty() )
{
//TODO: [[NSNotificationCenter defaultCenter] postNotificationName:AnimationFrameDisplayedNotification object:target_ userInfo:dict];
}
@ -2127,27 +2124,24 @@ void Animate::update(float t)
Animate* Animate::reverse() const
{
Array* pOldArray = _animation->getFrames();
Array* pNewArray = Array::createWithCapacity(pOldArray->count());
auto oldArray = _animation->getFrames();
Vector<AnimationFrame*> newArray(oldArray.size());
CCARRAY_VERIFY_TYPE(pOldArray, AnimationFrame*);
if (pOldArray->count() > 0)
if (oldArray.size() > 0)
{
Object* pObj = NULL;
CCARRAY_FOREACH_REVERSE(pOldArray, pObj)
for (auto iter = oldArray.crbegin(); iter != oldArray.crend(); ++iter)
{
AnimationFrame* pElement = static_cast<AnimationFrame*>(pObj);
if (! pElement)
AnimationFrame* animFrame = *iter;
if (!animFrame)
{
break;
}
pNewArray->addObject(pElement->clone());
newArray.pushBack(animFrame->clone());
}
}
Animation *newAnim = Animation::create(pNewArray, _animation->getDelayPerUnit(), _animation->getLoops());
Animation *newAnim = Animation::create(newArray, _animation->getDelayPerUnit(), _animation->getLoops());
newAnim->setRestoreOriginalFrame(_animation->getRestoreOriginalFrame());
return Animate::create(newAnim);
}

View File

@ -32,6 +32,7 @@ THE SOFTWARE.
#include "CCProtocols.h"
#include "CCSpriteFrame.h"
#include "CCAnimation.h"
#include <CCVector.h>
#include <vector>
NS_CC_BEGIN
@ -99,7 +100,7 @@ public:
* in lua :local create(local object1,local object2, ...)
* @endcode
*/
static Sequence* create(Array *arrayOfActions);
static Sequence* create(const Vector<FiniteTimeAction*>& arrayOfActions);
/** helper constructor to create an array of sequence-able actions */
static Sequence* createWithVariableList(FiniteTimeAction *pAction1, va_list args);
/** creates the action */
@ -246,7 +247,7 @@ public:
static Spawn* createWithVariableList(FiniteTimeAction *pAction1, va_list args);
/** helper constructor to create an array of spawned actions given an array */
static Spawn* create(Array *arrayOfActions);
static Spawn* create(const Vector<FiniteTimeAction*>& arrayOfActions);
/** creates the Spawn action */
static Spawn* createWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2);

View File

@ -32,15 +32,28 @@ THE SOFTWARE.
NS_CC_BEGIN
AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo)
{
auto ret = new AnimationFrame();
if (ret && ret->initWithSpriteFrame(spriteFrame, delayUnits, userInfo))
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
AnimationFrame::AnimationFrame()
: _spriteFrame(NULL)
, _delayUnits(0.0f)
, _userInfo(NULL)
{
}
bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, Dictionary* userInfo)
bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo)
{
setSpriteFrame(spriteFrame);
setDelayUnits(delayUnits);
@ -54,7 +67,6 @@ AnimationFrame::~AnimationFrame()
CCLOGINFO( "deallocing AnimationFrame: %p", this);
CC_SAFE_RELEASE(_spriteFrame);
CC_SAFE_RELEASE(_userInfo);
}
AnimationFrame* AnimationFrame::clone() const
@ -63,7 +75,7 @@ AnimationFrame* AnimationFrame::clone() const
auto frame = new AnimationFrame();
frame->initWithSpriteFrame(_spriteFrame->clone(),
_delayUnits,
_userInfo != NULL ? _userInfo->clone() : NULL);
_userInfo);
frame->autorelease();
return frame;
@ -80,7 +92,7 @@ Animation* Animation::create(void)
return pAnimation;
}
Animation* Animation::createWithSpriteFrames(Array *frames, float delay/* = 0.0f*/)
Animation* Animation::createWithSpriteFrames(const Vector<SpriteFrame*>& frames, float delay/* = 0.0f*/)
{
Animation *pAnimation = new Animation();
pAnimation->initWithSpriteFrames(frames, delay);
@ -89,7 +101,7 @@ Animation* Animation::createWithSpriteFrames(Array *frames, float delay/* = 0.0f
return pAnimation;
}
Animation* Animation::create(Array* arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops /* = 1 */)
Animation* Animation::create(const Vector<AnimationFrame*>& arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops /* = 1 */)
{
Animation *pAnimation = new Animation();
pAnimation->initWithAnimationFrames(arrayOfAnimationFrameNames, delayPerUnit, loops);
@ -99,49 +111,36 @@ Animation* Animation::create(Array* arrayOfAnimationFrameNames, float delayPerUn
bool Animation::init()
{
return initWithSpriteFrames(NULL, 0.0f);
_loops = 1;
_delayPerUnit = 0.0f;
return true;
}
bool Animation::initWithSpriteFrames(Array *pFrames, float delay/* = 0.0f*/)
bool Animation::initWithSpriteFrames(const Vector<SpriteFrame*>& frames, float delay/* = 0.0f*/)
{
CCARRAY_VERIFY_TYPE(pFrames, SpriteFrame*);
_loops = 1;
_delayPerUnit = delay;
Array* pTmpFrames = Array::create();
setFrames(pTmpFrames);
if (pFrames != NULL)
for (auto& spriteFrame : frames)
{
Object* pObj = NULL;
CCARRAY_FOREACH(pFrames, pObj)
{
SpriteFrame* frame = static_cast<SpriteFrame*>(pObj);
AnimationFrame *animFrame = new AnimationFrame();
animFrame->initWithSpriteFrame(frame, 1, NULL);
_frames->addObject(animFrame);
animFrame->release();
_totalDelayUnits++;
}
auto animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap());
_frames.pushBack(animFrame);
_totalDelayUnits++;
}
return true;
}
bool Animation::initWithAnimationFrames(Array* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops)
bool Animation::initWithAnimationFrames(const Vector<AnimationFrame*>& arrayOfAnimationFrames, float delayPerUnit, unsigned int loops)
{
CCARRAY_VERIFY_TYPE(arrayOfAnimationFrames, AnimationFrame*);
_delayPerUnit = delayPerUnit;
_loops = loops;
setFrames(Array::createWithArray(arrayOfAnimationFrames));
setFrames(arrayOfAnimationFrames);
Object* pObj = NULL;
CCARRAY_FOREACH(_frames, pObj)
for (auto& animFrame : _frames)
{
AnimationFrame* animFrame = static_cast<AnimationFrame*>(pObj);
_totalDelayUnits += animFrame->getDelayUnits();
}
return true;
@ -151,7 +150,6 @@ Animation::Animation()
: _totalDelayUnits(0.0f)
, _delayPerUnit(0.0f)
, _duration(0.0f)
, _frames(NULL)
, _restoreOriginalFrame(false)
, _loops(0)
{
@ -161,15 +159,12 @@ Animation::Animation()
Animation::~Animation(void)
{
CCLOGINFO("deallocing Animation: %p", this);
CC_SAFE_RELEASE(_frames);
}
void Animation::addSpriteFrame(SpriteFrame *pFrame)
void Animation::addSpriteFrame(SpriteFrame* spriteFrame)
{
AnimationFrame *animFrame = new AnimationFrame();
animFrame->initWithSpriteFrame(pFrame, 1.0f, NULL);
_frames->addObject(animFrame);
animFrame->release();
AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, 1.0f, ValueMap());
_frames.pushBack(animFrame);
// update duration
_totalDelayUnits++;

View File

@ -29,9 +29,11 @@ THE SOFTWARE.
#include "CCPlatformConfig.h"
#include "CCObject.h"
#include "CCArray.h"
#include "CCDictionary.h"
#include "CCValue.h"
#include "CCGeometry.h"
#include "CCSpriteFrame.h"
#include "CCVector.h"
#include <string>
NS_CC_BEGIN
@ -56,17 +58,10 @@ class CC_DLL AnimationFrame : public Object, public Clonable
{
public:
/**
* @js ctor
* Creates the animation frame with a spriteframe, number of delay units and a notification user info
* @since 3.0
*/
AnimationFrame();
/**
* @js NA
* @lua NA
*/
virtual ~AnimationFrame();
/** initializes the animation frame with a spriteframe, number of delay units and a notification user info */
bool initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, Dictionary* userInfo);
static AnimationFrame* create(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo);
SpriteFrame* getSpriteFrame() const { return _spriteFrame; };
@ -86,13 +81,12 @@ public:
/** @brief Gets user infomation
A AnimationFrameDisplayedNotification notification will be broadcast when the frame is displayed with this dictionary as UserInfo. If UserInfo is nil, then no notification will be broadcast.
*/
Dictionary* getUserInfo() const { return _userInfo; };
const ValueMap& getUserInfo() const { return _userInfo; };
ValueMap& getUserInfo() { return _userInfo; };
/** Sets user infomation */
void setUserInfo(Dictionary* userInfo)
void setUserInfo(const ValueMap& userInfo)
{
CC_SAFE_RETAIN(userInfo);
CC_SAFE_RELEASE(_userInfo);
_userInfo = userInfo;
}
@ -100,6 +94,20 @@ public:
virtual AnimationFrame *clone() const override;
protected:
/**
* @js ctor
*/
AnimationFrame();
/**
* @js NA
* @lua NA
*/
virtual ~AnimationFrame();
/** initializes the animation frame with a spriteframe, number of delay units and a notification user info */
bool initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo);
/** SpriteFrameName to be used */
SpriteFrame* _spriteFrame;
@ -107,7 +115,10 @@ protected:
float _delayUnits;
/** A AnimationFrameDisplayedNotification notification will be broadcast when the frame is displayed with this dictionary as UserInfo. If UserInfo is nil, then no notification will be broadcast. */
Dictionary* _userInfo;
ValueMap _userInfo;
private:
CC_DISALLOW_COPY_AND_ASSIGN(AnimationFrame);
};
@ -135,34 +146,13 @@ public:
The frames will be added with one "delay unit".
@since v0.99.5
*/
static Animation* createWithSpriteFrames(Array* arrayOfSpriteFrameNames, float delay = 0.0f);
static Animation* createWithSpriteFrames(const Vector<SpriteFrame*>& arrayOfSpriteFrameNames, float delay = 0.0f);
/* Creates an animation with an array of AnimationFrame, the delay per units in seconds and and how many times it should be executed.
@since v2.0
* @js NA
*/
static Animation* create(Array *arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops = 1);
/**
* @js ctor
*/
Animation();
/**
* @js NA
* @lua NA
*/
virtual ~Animation(void);
bool init();
/** Initializes a Animation with frames and a delay between frames
@since v0.99.5
*/
bool initWithSpriteFrames(Array *pFrames, float delay = 0.0f);
/** Initializes a Animation with AnimationFrame
@since v2.0
*/
bool initWithAnimationFrames(Array* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops);
static Animation* create(const Vector<AnimationFrame*>& arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops = 1);
/** Adds a SpriteFrame to a Animation.
The frame will be added with one "delay unit".
@ -199,13 +189,11 @@ public:
float getDuration() const;
/** Gets the array of AnimationFrames */
Array* getFrames() const { return _frames; };
const Vector<AnimationFrame*>& getFrames() const { return _frames; };
/** Sets the array of AnimationFrames */
void setFrames(Array* frames)
void setFrames(const Vector<AnimationFrame*>& frames)
{
CC_SAFE_RETAIN(frames);
CC_SAFE_RELEASE(_frames);
_frames = frames;
}
@ -225,6 +213,22 @@ public:
virtual Animation *clone() const override;
protected:
Animation();
virtual ~Animation(void);
/** Initializes a Animation */
bool init();
/** Initializes a Animation with frames and a delay between frames
@since v0.99.5
*/
bool initWithSpriteFrames(const Vector<SpriteFrame*>& arrayOfSpriteFrameNames, float delay = 0.0f);
/** Initializes a Animation with AnimationFrame
@since v2.0
*/
bool initWithAnimationFrames(const Vector<AnimationFrame*>& arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops);
/** total Delay units of the Animation. */
float _totalDelayUnits;
@ -235,13 +239,16 @@ protected:
float _duration;
/** array of AnimationFrames */
Array* _frames;
Vector<AnimationFrame*> _frames;
/** whether or not it shall restore the original frame when the animation finishes */
bool _restoreOriginalFrame;
/** how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... */
unsigned int _loops;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Animation);
};
// end of sprite_nodes group

View File

@ -55,25 +55,21 @@ void AnimationCache::destroyInstance()
bool AnimationCache::init()
{
_animations = new Dictionary;
_animations->init();
return true;
}
AnimationCache::AnimationCache()
: _animations(NULL)
{
}
AnimationCache::~AnimationCache()
{
CCLOGINFO("deallocing AnimationCache: %p", this);
CC_SAFE_RELEASE(_animations);
}
void AnimationCache::addAnimation(Animation *animation, const std::string& name)
{
_animations->setObject(animation, name);
_animations.insert(name, animation);
}
void AnimationCache::removeAnimation(const std::string& name)
@ -81,157 +77,143 @@ void AnimationCache::removeAnimation(const std::string& name)
if (name.size()==0)
return;
_animations->removeObjectForKey(name);
_animations.remove(name);
}
Animation* AnimationCache::getAnimation(const std::string& name)
{
return (Animation*)_animations->objectForKey(name);
return _animations.at(name);
}
void AnimationCache::parseVersion1(Dictionary* animations)
void AnimationCache::parseVersion1(const ValueMap& animations)
{
SpriteFrameCache *frameCache = SpriteFrameCache::getInstance();
DictElement* element = NULL;
CCDICT_FOREACH(animations, element)
for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter)
{
Dictionary* animationDict = static_cast<Dictionary*>(element->getObject());
Array* frameNames = static_cast<Array*>(animationDict->objectForKey("frames"));
float delay = animationDict->valueForKey("delay")->floatValue();
Animation* animation = NULL;
const ValueMap& animationDict = iter->second.asValueMap();
const ValueVector& frameNames = animationDict.at("frames").asValueVector();
float delay = animationDict.at("delay").asFloat();
Animation* animation = nullptr;
if ( frameNames == NULL )
if ( frameNames.empty() )
{
CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", element->getStrKey());
CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", iter->first.c_str());
continue;
}
Array* frames = Array::createWithCapacity(frameNames->count());
frames->retain();
Vector<AnimationFrame*> frames(frameNames.size());
Object* pObj = NULL;
CCARRAY_FOREACH(frameNames, pObj)
for (auto& frameName : frameNames)
{
const std::string& frameName = static_cast<String*>(pObj)->getCString();
SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName);
SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName.asString());
if ( ! spriteFrame ) {
CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", element->getStrKey(), frameName.c_str());
CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", iter->first.c_str(), frameName.asString().c_str());
continue;
}
AnimationFrame* animFrame = new AnimationFrame();
animFrame->initWithSpriteFrame(spriteFrame, 1, NULL);
frames->addObject(animFrame);
animFrame->release();
AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap());
frames.pushBack(animFrame);
}
if ( frames->count() == 0 ) {
CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", element->getStrKey());
if ( frames.size() == 0 )
{
CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", iter->first.c_str());
continue;
} else if ( frames->count() != frameNames->count() ) {
CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", element->getStrKey());
}
else if ( frames.size() != frameNames.size() )
{
CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", iter->first.c_str());
}
animation = Animation::create(frames, delay, 1);
AnimationCache::getInstance()->addAnimation(animation, element->getStrKey());
frames->release();
}
AnimationCache::getInstance()->addAnimation(animation, iter->first.c_str());
}
}
void AnimationCache::parseVersion2(Dictionary* animations)
void AnimationCache::parseVersion2(const ValueMap& animations)
{
SpriteFrameCache *frameCache = SpriteFrameCache::getInstance();
DictElement* element = NULL;
CCDICT_FOREACH(animations, element)
for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter)
{
const char* name = element->getStrKey();
Dictionary* animationDict = static_cast<Dictionary*>(element->getObject());
std::string name = iter->first;
const ValueMap& animationDict = iter->second.asValueMap();
const String* loops = animationDict->valueForKey("loops");
bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue();
const Value& loops = animationDict.at("loops");
bool restoreOriginalFrame = animationDict.at("restoreOriginalFrame").asBool();
Array* frameArray = static_cast<Array*>(animationDict->objectForKey("frames"));
const ValueVector& frameArray = animationDict.at("frames").asValueVector();
if ( frameArray == NULL ) {
CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", name);
if ( frameArray.empty() )
{
CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", name.c_str());
continue;
}
// Array of AnimationFrames
Array* array = Array::createWithCapacity(frameArray->count());
array->retain();
Vector<AnimationFrame*> array(frameArray.size());
Object* pObj = NULL;
CCARRAY_FOREACH(frameArray, pObj)
for (auto& obj : frameArray)
{
Dictionary* entry = static_cast<Dictionary*>(pObj);
const char* spriteFrameName = entry->valueForKey("spriteframe")->getCString();
const ValueMap& entry = obj.asValueMap();
std::string spriteFrameName = entry.at("spriteframe").asString();
SpriteFrame *spriteFrame = frameCache->getSpriteFrameByName(spriteFrameName);
if( ! spriteFrame ) {
CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", name, spriteFrameName);
CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", name.c_str(), spriteFrameName.c_str());
continue;
}
float delayUnits = entry->valueForKey("delayUnits")->floatValue();
Dictionary* userInfo = (Dictionary*)entry->objectForKey("notification");
float delayUnits = entry.at("delayUnits").asFloat();
const Value& userInfo = entry.at("notification");
AnimationFrame *animFrame = new AnimationFrame();
animFrame->initWithSpriteFrame(spriteFrame, delayUnits, userInfo);
AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asValueMap());
array->addObject(animFrame);
animFrame->release();
array.pushBack(animFrame);
}
float delayPerUnit = animationDict->valueForKey("delayPerUnit")->floatValue();
Animation *animation = new Animation();
animation->initWithAnimationFrames(array, delayPerUnit, 0 != loops->length() ? loops->intValue() : 1);
array->release();
float delayPerUnit = animationDict.at("delayPerUnit").asFloat();
Animation *animation = Animation::create(array, delayPerUnit, loops.getType() != Value::Type::NONE ? loops.asInt() : 1);
animation->setRestoreOriginalFrame(restoreOriginalFrame);
AnimationCache::getInstance()->addAnimation(animation, name);
animation->release();
}
}
void AnimationCache::addAnimationsWithDictionary(Dictionary* dictionary)
void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary)
{
Dictionary* animations = (Dictionary*)dictionary->objectForKey("animations");
if ( animations == NULL ) {
if ( dictionary.find("animations") == dictionary.end() )
{
CCLOG("cocos2d: AnimationCache: No animations were found in provided dictionary.");
return;
}
const Value& animations = dictionary.at("animations");
unsigned int version = 1;
Dictionary* properties = (Dictionary*)dictionary->objectForKey("properties");
if( properties )
{
version = properties->valueForKey("format")->intValue();
Array* spritesheets = (Array*)properties->objectForKey("spritesheets");
Object* pObj = NULL;
CCARRAY_FOREACH(spritesheets, pObj)
{
String* name = static_cast<String*>(pObj);
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(name->getCString());
}
if( dictionary.find("properties") != dictionary.end() )
{
const ValueMap& properties = dictionary.at("properties").asValueMap();
version = properties.at("format").asInt();
const ValueVector& spritesheets = properties.at("spritesheets").asValueVector();
std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString());
});
}
switch (version) {
case 1:
parseVersion1(animations);
parseVersion1(animations.asValueMap());
break;
case 2:
parseVersion2(animations);
parseVersion2(animations.asValueMap());
break;
default:
CCASSERT(false, "Invalid animation format");
@ -244,9 +226,9 @@ void AnimationCache::addAnimationsWithFile(const std::string& plist)
CCASSERT( plist.size()>0, "Invalid texture file name");
std::string path = FileUtils::getInstance()->fullPathForFilename(plist);
Dictionary* dict = Dictionary::createWithContentsOfFile(path.c_str());
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(path);
CCASSERT( dict, "CCAnimationCache: File could not be found");
CCASSERT( !dict.empty(), "CCAnimationCache: File could not be found");
addAnimationsWithDictionary(dict);
}

View File

@ -27,8 +27,8 @@ THE SOFTWARE.
#define __CC_ANIMATION_CACHE_H__
#include "CCObject.h"
#include "CCDictionary.h"
#include "CCMap.h"
#include "CCValue.h"
#include <string>
NS_CC_BEGIN
@ -104,7 +104,7 @@ public:
Make sure that the frames were previously loaded in the SpriteFrameCache.
@since v1.1
*/
void addAnimationsWithDictionary(Dictionary* dictionary);
void addAnimationsWithDictionary(const ValueMap& dictionary);
/** Adds an animation from a plist file.
Make sure that the frames were previously loaded in the SpriteFrameCache.
@ -115,11 +115,11 @@ public:
void addAnimationsWithFile(const std::string& plist);
private:
void parseVersion1(Dictionary* animations);
void parseVersion2(Dictionary* animations);
void parseVersion1(const ValueMap& animations);
void parseVersion2(const ValueMap& animations);
private:
Dictionary* _animations;
Map<std::string, Animation*> _animations;
static AnimationCache* s_pSharedAnimationCache;
};

View File

@ -39,13 +39,10 @@ static GLint g_sStencilBits = -1;
static void setProgram(Node *n, GLProgram *p)
{
n->setShaderProgram(p);
if (!n->getChildren()) return;
Object* pObj = NULL;
CCARRAY_FOREACH(n->getChildren(), pObj)
{
setProgram(static_cast<Node*>(pObj), p);
}
n->getChildren().forEach([p](Node* child){
setProgram(child, p);
});
}
ClippingNode::ClippingNode()

View File

@ -189,18 +189,18 @@ EventDispatcher::~EventDispatcher()
void EventDispatcher::visitTarget(Node* node)
{
int i = 0;
Array* children = node->getChildren();
int childrenCount = children ? children->count() : 0;
long i = 0;
auto& children = node->getChildren();
long childrenCount = children.size();
if(childrenCount > 0)
{
Node* child = nullptr;
// visit children zOrder < 0
for( ; i < childrenCount; i++ )
{
child = static_cast<Node*>( children->getObjectAtIndex(i) );
child = children.at(i);
if ( child && child->getZOrder() < 0 )
visitTarget(child);
@ -212,7 +212,7 @@ void EventDispatcher::visitTarget(Node* node)
for( ; i < childrenCount; i++ )
{
child = static_cast<Node*>( children->getObjectAtIndex(i) );
child = children.at(i);
if (child)
visitTarget(child);
}

View File

@ -248,20 +248,17 @@ void Label::alignText()
LabelTextFormatter::alignText(this);
int strLen = cc_wcslen(_currentUTF16String);
if (_children && _children->count() != 0)
{
for (auto child: *_children)
int strLen = cc_wcslen(_currentUTF16String);
_children.forEach([this, &strLen](Node* child){
if (child)
{
Node* pNode = static_cast<Node*>( child );
if (pNode)
{
int tag = pNode->getTag();
if(tag < 0 || tag >= strLen)
SpriteBatchNode::removeChild(pNode, true);
}
int tag = child->getTag();
if(tag < 0 || tag >= strLen)
SpriteBatchNode::removeChild(child, true);
}
}
});
_reusedLetter->setBatchNode(nullptr);
int vaildIndex = 0;
@ -376,7 +373,7 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F
{
spriteToUpdate->setBatchNode(this);
spriteToUpdate->setTexture(theTexture);
spriteToUpdate->setDisplayFrame(frame);
spriteToUpdate->setSpriteFrame(frame);
spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
}
@ -594,21 +591,18 @@ bool Label::isOpacityModifyRGB() const
void Label::setOpacityModifyRGB(bool isOpacityModifyRGB)
{
_isOpacityModifyRGB = isOpacityModifyRGB;
if (_children && _children->count() != 0)
{
for (auto child: *_children)
_children.forEach([this](Node* child){
if (child)
{
Node* pNode = static_cast<Node*>( child );
if (pNode)
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(child);
if (pRGBAProtocol)
{
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(pNode);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
}
}
});
_reusedLetter->setOpacityModifyRGB(true);
}
@ -640,13 +634,13 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
for (auto child: *_children)
{
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedOpacity(_displayedOpacity);
}
});
V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads();
int count = _textureAtlas->getTotalQuads();
long count = _textureAtlas->getTotalQuads();
Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
if (_isOpacityModifyRGB)
{
@ -706,14 +700,13 @@ void Label::updateDisplayedColor(const Color3B& parentColor)
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
for (auto child: *_children)
{
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedColor(_displayedColor);
}
});
V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads();
int count = _textureAtlas->getTotalQuads();
long count = _textureAtlas->getTotalQuads();
Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
// special opacity for premultiplied textures

View File

@ -746,18 +746,10 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel)
CC_SAFE_DELETE_ARRAY(tmp);
}
if (_children && _children->count() != 0)
{
Object* child;
CCARRAY_FOREACH(_children, child)
{
Node* pNode = static_cast<Node*>( child );
if (pNode)
{
pNode->setVisible(false);
}
}
}
_children.forEach([](Node* child){
child->setVisible(false);
});
this->createFontChars();
if (needUpdateLabel) {
@ -830,22 +822,16 @@ void LabelBMFont::setOpacity(GLubyte opacity)
void LabelBMFont::setOpacityModifyRGB(bool var)
{
_isOpacityModifyRGB = var;
if (_children && _children->count() != 0)
{
Object* child;
CCARRAY_FOREACH(_children, child)
_children.forEach([this](Node* child){
if (child)
{
Node* pNode = static_cast<Node*>( child );
if (pNode)
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(child);
if (pRGBAProtocol)
{
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(pNode);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
}
}
});
}
bool LabelBMFont::isOpacityModifyRGB() const
{
@ -854,28 +840,24 @@ bool LabelBMFont::isOpacityModifyRGB() const
void LabelBMFont::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
_displayedOpacity = _realOpacity * parentOpacity/255.0f;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedOpacity(_displayedOpacity);
}
});
}
void LabelBMFont::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
_displayedColor.r = _realColor.r * parentColor.r/255.0f;
_displayedColor.g = _realColor.g * parentColor.g/255.0f;
_displayedColor.b = _realColor.b * parentColor.b/255.0f;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedColor(_displayedColor);
}
});
}
bool LabelBMFont::isCascadeColorEnabled() const
@ -917,7 +899,7 @@ void LabelBMFont::updateLabel()
{
// Step 1: Make multiline
vector<unsigned short> str_whole = cc_utf16_vec_from_utf16_str(_string);
unsigned int stringLength = str_whole.size();
size_t stringLength = str_whole.size();
vector<unsigned short> multiline_string;
multiline_string.reserve( stringLength );
vector<unsigned short> last_word;
@ -928,8 +910,8 @@ void LabelBMFont::updateLabel()
float startOfLine = -1, startOfWord = -1;
int skip = 0;
Array* children = getChildren();
for (int j = 0; j < children->count(); j++)
auto children = getChildren();
for (int j = 0; j < children.size(); j++)
{
Sprite* characterSprite;
unsigned int justSkipped = 0;
@ -1068,7 +1050,7 @@ void LabelBMFont::updateLabel()
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
int size = multiline_string.size();
size_t size = multiline_string.size();
unsigned short* str_new = new unsigned short[size + 1];
for (int j = 0; j < size; ++j)
@ -1096,7 +1078,7 @@ void LabelBMFont::updateLabel()
if (_string[ctr] == '\n' || _string[ctr] == 0)
{
float lineWidth = 0.0f;
unsigned int line_length = last_line.size();
size_t line_length = last_line.size();
// if last line is empty we must just increase lineNumber and work with next line
if (line_length == 0)
{

View File

@ -499,15 +499,13 @@ void LayerRGBA::updateDisplayedOpacity(GLubyte parentOpacity)
if (_cascadeOpacityEnabled)
{
Object *obj = NULL;
CCARRAY_FOREACH(_children, obj)
{
_children.forEach([this](Node* obj){
RGBAProtocol *item = dynamic_cast<RGBAProtocol*>(obj);
if (item)
{
item->updateDisplayedOpacity(_displayedOpacity);
}
}
});
}
}
@ -519,15 +517,13 @@ void LayerRGBA::updateDisplayedColor(const Color3B& parentColor)
if (_cascadeColorEnabled)
{
Object *obj = NULL;
CCARRAY_FOREACH(_children, obj)
{
_children.forEach([this](Node* obj){
RGBAProtocol *item = dynamic_cast<RGBAProtocol*>(obj);
if (item)
{
item->updateDisplayedColor(_displayedColor);
}
}
});
}
}
@ -920,19 +916,14 @@ void LayerGradient::setCompressedInterpolation(bool compress)
LayerMultiplex::LayerMultiplex()
: _enabledLayer(0)
, _layers(NULL)
{
}
LayerMultiplex::~LayerMultiplex()
{
if (_layers)
{
for (auto& item : *_layers)
{
static_cast<Layer*>(item)->cleanup();
}
_layers->release();
}
_layers.forEach([](Layer* layer){
layer->cleanup();
});
}
LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)
@ -971,7 +962,7 @@ LayerMultiplex* LayerMultiplex::create()
return pRet;
}
LayerMultiplex* LayerMultiplex::createWithArray(Array* arrayOfLayers)
LayerMultiplex* LayerMultiplex::createWithArray(const Vector<Layer*>& arrayOfLayers)
{
LayerMultiplex* pRet = new LayerMultiplex();
if (pRet && pRet->initWithArray(arrayOfLayers))
@ -987,17 +978,13 @@ LayerMultiplex* LayerMultiplex::createWithArray(Array* arrayOfLayers)
void LayerMultiplex::addLayer(Layer* layer)
{
CCASSERT(_layers, "");
_layers->addObject(layer);
_layers.pushBack(layer);
}
bool LayerMultiplex::init()
{
if (Layer::init())
{
_layers = Array::create();
_layers->retain();
_enabledLayer = 0;
return true;
}
@ -1008,34 +995,32 @@ bool LayerMultiplex::initWithLayers(Layer *layer, va_list params)
{
if (Layer::init())
{
_layers = Array::createWithCapacity(5);
_layers->retain();
_layers->addObject(layer);
_layers.reserve(5);
_layers.pushBack(layer);
Layer *l = va_arg(params,Layer*);
while( l ) {
_layers->addObject(l);
_layers.pushBack(l);
l = va_arg(params,Layer*);
}
_enabledLayer = 0;
this->addChild((Node*)_layers->getObjectAtIndex(_enabledLayer));
this->addChild(_layers.at(_enabledLayer));
return true;
}
return false;
}
bool LayerMultiplex::initWithArray(Array* arrayOfLayers)
bool LayerMultiplex::initWithArray(const Vector<Layer*>& arrayOfLayers)
{
if (Layer::init())
{
_layers = Array::createWithCapacity(arrayOfLayers->count());
_layers->addObjectsFromArray(arrayOfLayers);
_layers->retain();
_layers.reserve(arrayOfLayers.size());
_layers.insert(arrayOfLayers);
_enabledLayer = 0;
this->addChild((Node*)_layers->getObjectAtIndex(_enabledLayer));
this->addChild(_layers.at(_enabledLayer));
return true;
}
return false;
@ -1043,27 +1028,26 @@ bool LayerMultiplex::initWithArray(Array* arrayOfLayers)
void LayerMultiplex::switchTo(int n)
{
CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" );
CCASSERT( n < _layers.size(), "Invalid index in MultiplexLayer switchTo message" );
this->removeChild((Node*)_layers->getObjectAtIndex(_enabledLayer), true);
this->removeChild(_layers.at(_enabledLayer), true);
_enabledLayer = n;
this->addChild((Node*)_layers->getObjectAtIndex(n));
this->addChild(_layers.at(n));
}
void LayerMultiplex::switchToAndReleaseMe(int n)
{
CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" );
CCASSERT( n < _layers.size(), "Invalid index in MultiplexLayer switchTo message" );
this->removeChild((Node*)_layers->getObjectAtIndex(_enabledLayer), true);
this->removeChild(_layers.at(_enabledLayer), true);
//[layers replaceObjectAtIndex:enabledLayer withObject:[NSNull null]];
_layers->replaceObjectAtIndex(_enabledLayer, NULL);
_layers.replace(_enabledLayer, nullptr);
_enabledLayer = n;
this->addChild((Node*)_layers->getObjectAtIndex(n));
this->addChild(_layers.at(n));
}
NS_CC_END

View File

@ -412,7 +412,7 @@ public:
@since v2.1
* @js NA
*/
static LayerMultiplex* createWithArray(Array* arrayOfLayers);
static LayerMultiplex* createWithArray(const Vector<Layer*>& arrayOfLayers);
/** creates a LayerMultiplex with one or more layers using a variable argument list.
* @code
@ -430,27 +430,7 @@ public:
* @lua NA
*/
static LayerMultiplex * createWithLayer(Layer* layer);
/**
* @js ctor
*/
LayerMultiplex();
/**
* @js NA
* @lua NA
*/
virtual ~LayerMultiplex();
virtual bool init();
/** initializes a MultiplexLayer with one or more layers using a variable argument list.
* @js NA
* @lua NA
*/
bool initWithLayers(Layer* layer, va_list params);
/** initializes a MultiplexLayer with an array of layers
@since v2.1
*/
bool initWithArray(Array* arrayOfLayers);
void addLayer(Layer* layer);
@ -464,8 +444,34 @@ public:
void switchToAndReleaseMe(int n);
protected:
/**
* @js ctor
*/
LayerMultiplex();
/**
* @js NA
* @lua NA
*/
virtual ~LayerMultiplex();
virtual bool init();
/** initializes a MultiplexLayer with one or more layers using a variable argument list.
* @js NA
* @lua NA
*/
bool initWithLayers(Layer* layer, va_list params);
/** initializes a MultiplexLayer with an array of layers
@since v2.1
*/
bool initWithArray(const Vector<Layer*>& arrayOfLayers);
unsigned int _enabledLayer;
Array* _layers;
Vector<Layer*> _layers;
private:
CC_DISALLOW_COPY_AND_ASSIGN(LayerMultiplex);
};

View File

@ -30,7 +30,6 @@ THE SOFTWARE.
#include "CCInteger.h"
#include "CCEventListenerTouch.h"
#include <vector>
#include <stdarg.h>
@ -38,18 +37,6 @@ using namespace std;
NS_CC_BEGIN
static std::vector<unsigned int> ccarray_to_std_vector(Array* pArray)
{
std::vector<unsigned int> ret;
Object* pObj;
CCARRAY_FOREACH(pArray, pObj)
{
Integer* pInteger = static_cast<Integer*>(pObj);
ret.push_back((unsigned int)pInteger->getValue());
}
return ret;
}
enum
{
kDefaultPadding = 5,
@ -81,36 +68,36 @@ Menu * Menu::create(MenuItem* item, ...)
return pRet;
}
Menu* Menu::createWithArray(Array* pArrayOfItems)
Menu* Menu::createWithArray(const Vector<MenuItem*>& arrayOfItems)
{
Menu *pRet = new Menu();
if (pRet && pRet->initWithArray(pArrayOfItems))
auto ret = new Menu();
if (ret && ret->initWithArray(arrayOfItems))
{
pRet->autorelease();
ret->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
CC_SAFE_DELETE(ret);
}
return pRet;
return ret;
}
Menu* Menu::createWithItems(MenuItem* item, va_list args)
{
Array* pArray = NULL;
Vector<MenuItem*> items;
if( item )
{
pArray = Array::create(item, NULL);
items.pushBack(item);
MenuItem *i = va_arg(args, MenuItem*);
while(i)
{
pArray->addObject(i);
items.pushBack(i);
i = va_arg(args, MenuItem*);
}
}
return Menu::createWithArray(pArray);
return Menu::createWithArray(items);
}
Menu* Menu::createWithItem(MenuItem* item)
@ -120,10 +107,10 @@ Menu* Menu::createWithItem(MenuItem* item)
bool Menu::init()
{
return initWithArray(NULL);
return initWithArray(Vector<MenuItem*>());
}
bool Menu::initWithArray(Array* pArrayOfItems)
bool Menu::initWithArray(const Vector<MenuItem*>& arrayOfItems)
{
if (Layer::init())
{
@ -137,16 +124,12 @@ bool Menu::initWithArray(Array* pArrayOfItems)
setPosition(Point(s.width/2, s.height/2));
if (pArrayOfItems != NULL)
int z=0;
for (auto& item : arrayOfItems)
{
int z=0;
Object* pObj = NULL;
CCARRAY_FOREACH(pArrayOfItems, pObj)
{
MenuItem* item = static_cast<MenuItem*>(pObj);
this->addChild(item, z);
z++;
}
this->addChild(item, z);
z++;
}
_selectedItem = NULL;
@ -242,7 +225,7 @@ bool Menu::onTouchBegan(Touch* touch, Event* event)
}
}
_selectedItem = this->itemForTouch(touch);
_selectedItem = this->getItemForTouch(touch);
if (_selectedItem)
{
_state = Menu::State::TRACKING_TOUCH;
@ -282,7 +265,7 @@ void Menu::onTouchCancelled(Touch* touch, Event* event)
void Menu::onTouchMoved(Touch* touch, Event* event)
{
CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchMoved] -- invalid state");
MenuItem *currentItem = this->itemForTouch(touch);
MenuItem *currentItem = this->getItemForTouch(touch);
if (currentItem != _selectedItem)
{
if (_selectedItem)
@ -306,33 +289,23 @@ void Menu::alignItemsVertically()
void Menu::alignItemsVerticallyWithPadding(float padding)
{
float height = -padding;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
{
height += child->getContentSize().height * child->getScaleY() + padding;
}
height += child->getContentSize().height * child->getScaleY() + padding;
}
}
});
float y = height / 2.0f;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
{
child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
y -= child->getContentSize().height * child->getScaleY() + padding;
}
child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
y -= child->getContentSize().height * child->getScaleY() + padding;
}
}
});
}
void Menu::alignItemsHorizontally(void)
@ -342,35 +315,23 @@ void Menu::alignItemsHorizontally(void)
void Menu::alignItemsHorizontallyWithPadding(float padding)
{
float width = -padding;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
{
width += child->getContentSize().width * child->getScaleX() + padding;
}
width += child->getContentSize().width * child->getScaleX() + padding;
}
}
});
float x = -width / 2.0f;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
{
child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
x += child->getContentSize().width * child->getScaleX() + padding;
}
child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
x += child->getContentSize().width * child->getScaleX() + padding;
}
}
});
}
void Menu::alignItemsInColumns(int columns, ...)
@ -386,54 +347,46 @@ void Menu::alignItemsInColumns(int columns, ...)
void Menu::alignItemsInColumns(int columns, va_list args)
{
CCASSERT(columns >= 0, "Columns must be >= 0");
Array* rows = Array::create();
ValueVector rows;
while (columns)
{
rows->addObject(Integer::create(columns));
rows.push_back(Value(columns));
columns = va_arg(args, int);
}
alignItemsInColumnsWithArray(rows);
}
void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
{
vector<unsigned int> rows = ccarray_to_std_vector(rowsArray);
int height = -5;
unsigned int row = 0;
unsigned int rowHeight = 0;
unsigned int columnsOccupied = 0;
unsigned int rowColumns;
int row = 0;
int rowHeight = 0;
int columnsOccupied = 0;
int rowColumns = 0;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
CCASSERT(row < rows.size(), "");
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
CCASSERT(row < rows.size(), "");
rowColumns = rows[row];
// can not have zero columns on a row
CCASSERT(rowColumns, "");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
height += rowHeight + 5;
columnsOccupied = 0;
rowHeight = 0;
++row;
}
height += rowHeight + 5;
columnsOccupied = 0;
rowHeight = 0;
++row;
}
}
}
});
// check if too many rows/columns for available menu items
CCASSERT(! columnsOccupied, "");
@ -447,17 +400,14 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
float x = 0.0;
float y = (float)(height / 2);
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
{
if (rowColumns == 0)
{
rowColumns = rows[row];
rowColumns = rows[row].asInt();
w = winSize.width / (1 + rowColumns);
x = w;
}
@ -482,7 +432,7 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
}
}
}
}
});
}
void Menu::alignItemsInRows(int rows, ...)
@ -497,65 +447,57 @@ void Menu::alignItemsInRows(int rows, ...)
void Menu::alignItemsInRows(int rows, va_list args)
{
Array* pArray = Array::create();
ValueVector array;
while (rows)
{
pArray->addObject(Integer::create(rows));
array.push_back(Value(rows));
rows = va_arg(args, int);
}
alignItemsInRowsWithArray(pArray);
alignItemsInRowsWithArray(array);
}
void Menu::alignItemsInRowsWithArray(Array* columnArray)
void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
{
vector<unsigned int> columns = ccarray_to_std_vector(columnArray);
vector<unsigned int> columnWidths;
vector<unsigned int> columnHeights;
vector<int> columnWidths;
vector<int> columnHeights;
int width = -10;
int columnHeight = -5;
unsigned int column = 0;
unsigned int columnWidth = 0;
unsigned int rowsOccupied = 0;
unsigned int columnRows;
int column = 0;
int columnWidth = 0;
int rowsOccupied = 0;
int columnRows;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
// check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
// check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
columnWidths.push_back(columnWidth);
columnHeights.push_back(columnHeight);
width += columnWidth + 10;
columnRows = columns[column];
// can't have zero rows on a column
CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
columnWidths.push_back(columnWidth);
columnHeights.push_back(columnHeight);
width += columnWidth + 10;
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
}
}
});
// check if too many rows/columns for available menu items.
CCASSERT(! rowsOccupied, "");
@ -568,59 +510,52 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray)
float x = (float)(-width / 2);
float y = 0.0;
if (_children && _children->count() > 0)
{
Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&](Node* child){
if (child)
{
Node* child = dynamic_cast<Node*>(pObject);
if (child)
if (columnRows == 0)
{
if (columnRows == 0)
{
columnRows = columns[column];
y = (float) columnHeights[column];
}
columnRows = columns[column].asInt();
y = (float) columnHeights[column];
}
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
}
}
});
}
MenuItem* Menu::itemForTouch(Touch *touch)
MenuItem* Menu::getItemForTouch(Touch *touch)
{
Point touchLocation = touch->getLocation();
if (_children && _children->count() > 0)
if (!_children.empty())
{
Object* pObject = NULL;
CCARRAY_FOREACH_REVERSE(_children, pObject)
for (auto iter = _children.crbegin(); iter != _children.crend(); ++iter)
{
MenuItem* child = dynamic_cast<MenuItem*>(pObject);
MenuItem* child = dynamic_cast<MenuItem*>(*iter);
if (child && child->isVisible() && child->isEnabled())
{
Point local = child->convertToNodeSpace(touchLocation);
Rect r = child->rect();
r.origin = Point::ZERO;
if (r.containsPoint(local))
{
return child;

View File

@ -27,8 +27,9 @@ THE SOFTWARE.
#include "CCMenuItem.h"
#include "CCLayer.h"
#include "CCVector.h"
#include "CCEventTouch.h"
#include "CCValue.h"
NS_CC_BEGIN
@ -63,7 +64,7 @@ public:
static Menu* create(MenuItem* item, ...) CC_REQUIRES_NULL_TERMINATION;
/** creates a Menu with a Array of MenuItem objects */
static Menu* createWithArray(Array* pArrayOfItems);
static Menu* createWithArray(const Vector<MenuItem*>& arrayOfItems);
/** creates a Menu with it's item, then use addChild() to add
* other items. It is used for script, it can't init with undetermined
@ -91,12 +92,12 @@ public:
/** align items in rows of columns */
void alignItemsInColumns(int columns, ...) CC_REQUIRES_NULL_TERMINATION;
void alignItemsInColumns(int columns, va_list args);
void alignItemsInColumnsWithArray(Array* rows);
void alignItemsInColumnsWithArray(const ValueVector& rows);
/** align items in columns of rows */
void alignItemsInRows(int rows, ...) CC_REQUIRES_NULL_TERMINATION;
void alignItemsInRows(int rows, va_list args);
void alignItemsInRowsWithArray(Array* columns);
void alignItemsInRowsWithArray(const ValueVector& columns);
virtual bool isEnabled() const { return _enabled; }
virtual void setEnabled(bool value) { _enabled = value; };
@ -129,12 +130,12 @@ protected:
bool init();
/** initializes a Menu with a NSArray of MenuItem objects */
bool initWithArray(Array* pArrayOfItems);
bool initWithArray(const Vector<MenuItem*>& arrayOfItems);
/** whether or not the menu will receive events */
bool _enabled;
MenuItem* itemForTouch(Touch * touch);
MenuItem* getItemForTouch(Touch * touch);
State _state;
MenuItem *_selectedItem;

View File

@ -810,13 +810,11 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle
{
MenuItemToggle *ret = new MenuItemToggle();
ret->MenuItem::initWithTarget(target, selector);
ret->_subItems = Array::create();
ret->_subItems->retain();
for (int z=0; z < menuItems->count(); z++)
{
MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
ret->_subItems->addObject(menuItem);
ret->_subItems.pushBack(menuItem);
}
ret->_selectedIndex = UINT_MAX;
@ -828,13 +826,11 @@ MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callba
{
MenuItemToggle *ret = new MenuItemToggle();
ret->MenuItem::initWithCallback(callback);
ret->_subItems = Array::create();
ret->_subItems->retain();
for (int z=0; z < menuItems->count(); z++)
{
MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
ret->_subItems->addObject(menuItem);
ret->_subItems.pushBack(menuItem);
}
ret->_selectedIndex = UINT_MAX;
@ -884,14 +880,13 @@ bool MenuItemToggle::initWithTarget(Object* target, SEL_MenuHandler selector, Me
bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem *item, va_list args)
{
MenuItem::initWithCallback(callback);
this->_subItems = Array::create();
this->_subItems->retain();
int z = 0;
MenuItem *i = item;
while(i)
{
z++;
_subItems->addObject(i);
_subItems.pushBack(i);
i = va_arg(args, MenuItem*);
}
_selectedIndex = UINT_MAX;
@ -910,11 +905,10 @@ MenuItemToggle* MenuItemToggle::create(MenuItem *item)
bool MenuItemToggle::initWithItem(MenuItem *item)
{
MenuItem::initWithCallback((const ccMenuCallback&)nullptr);
setSubItems(Array::create());
if (item)
{
_subItems->addObject(item);
_subItems.pushBack(item);
}
_selectedIndex = UINT_MAX;
this->setSelectedIndex(0);
@ -927,24 +921,19 @@ bool MenuItemToggle::initWithItem(MenuItem *item)
void MenuItemToggle::addSubItem(MenuItem *item)
{
_subItems->addObject(item);
_subItems.pushBack(item);
}
MenuItemToggle::~MenuItemToggle()
{
if (_subItems)
{
for (auto& item : *_subItems)
{
static_cast<MenuItem*>(item)->cleanup();
}
_subItems->release();
}
_subItems.forEach([](MenuItem* item){
item->cleanup();
});
}
void MenuItemToggle::setSelectedIndex(unsigned int index)
{
if( index != _selectedIndex && _subItems->count() > 0 )
if( index != _selectedIndex && _subItems.size() > 0 )
{
_selectedIndex = index;
MenuItem *currentItem = (MenuItem*)getChildByTag(kCurrentItem);
@ -953,7 +942,7 @@ void MenuItemToggle::setSelectedIndex(unsigned int index)
currentItem->removeFromParentAndCleanup(false);
}
MenuItem* item = (MenuItem*)_subItems->getObjectAtIndex(_selectedIndex);
MenuItem* item = _subItems.at(_selectedIndex);
this->addChild(item, 0, kCurrentItem);
Size s = item->getContentSize();
this->setContentSize(s);
@ -964,13 +953,13 @@ void MenuItemToggle::setSelectedIndex(unsigned int index)
void MenuItemToggle::selected()
{
MenuItem::selected();
static_cast<MenuItem*>(_subItems->getObjectAtIndex(_selectedIndex))->selected();
_subItems.at(_selectedIndex)->selected();
}
void MenuItemToggle::unselected()
{
MenuItem::unselected();
static_cast<MenuItem*>(_subItems->getObjectAtIndex(_selectedIndex))->unselected();
_subItems.at(_selectedIndex)->unselected();
}
void MenuItemToggle::activate()
@ -978,7 +967,7 @@ void MenuItemToggle::activate()
// update index
if( _enabled )
{
unsigned int newIndex = (_selectedIndex + 1) % _subItems->count();
unsigned int newIndex = (_selectedIndex + 1) % _subItems.size();
this->setSelectedIndex(newIndex);
}
MenuItem::activate();
@ -989,21 +978,15 @@ void MenuItemToggle::setEnabled(bool enabled)
{
MenuItem::setEnabled(enabled);
if(_subItems && _subItems->count() > 0)
{
Object* pObj = NULL;
CCARRAY_FOREACH(_subItems, pObj)
{
MenuItem* pItem = static_cast<MenuItem*>(pObj);
pItem->setEnabled(enabled);
}
}
_subItems.forEach([&enabled](MenuItem* item){
item->setEnabled(enabled);
});
}
}
MenuItem* MenuItemToggle::getSelectedItem()
{
return static_cast<MenuItem*>(_subItems->getObjectAtIndex(_selectedIndex));
return _subItems.at(_selectedIndex);
}
NS_CC_END

View File

@ -481,13 +481,11 @@ public:
* @js NA
* @lua NA
*/
inline Array* getSubItems() const { return _subItems; };
inline const Vector<MenuItem*>& getSubItems() const { return _subItems; };
inline Vector<MenuItem*>& getSubItems() { return _subItems; };
/** Sets the array that contains the subitems. */
inline void setSubItems(Array* items) {
CC_SAFE_RETAIN(items);
CC_SAFE_RELEASE(_subItems);
inline void setSubItems(const Vector<MenuItem*>& items) {
_subItems = items;
}
@ -513,7 +511,6 @@ protected:
*/
MenuItemToggle()
: _selectedIndex(0)
, _subItems(NULL)
{}
/**
* @js NA
@ -537,7 +534,7 @@ protected:
/** Array that contains the subitems. You can add/remove items in runtime, and you can replace the array with a new one.
@since v0.7.2
*/
Array* _subItems;
Vector<MenuItem*> _subItems;
private:
CC_DISALLOW_COPY_AND_ASSIGN(MenuItemToggle);

View File

@ -114,7 +114,6 @@ Node::Node(void)
// lazy alloc
, _grid(NULL)
, _ZOrder(0)
, _children(NULL)
, _parent(NULL)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
, _tag(Node::INVALID_TAG)
@ -169,22 +168,14 @@ Node::~Node()
CC_SAFE_RELEASE(_shaderProgram);
CC_SAFE_RELEASE(_userObject);
if(_children && _children->count() > 0)
for (auto& child : _children)
{
Object* child;
CCARRAY_FOREACH(_children, child)
if (child)
{
Node* node = static_cast<Node*>(child);
if (node)
{
node->_parent = NULL;
}
child->_parent = NULL;
}
}
// children
CC_SAFE_RELEASE(_children);
removeAllComponents();
CC_SAFE_DELETE(_componentContainer);
@ -406,7 +397,7 @@ void Node::setPositionY(float y)
long Node::getChildrenCount() const
{
return _children ? _children->count() : 0;
return _children.size();
}
/// camera getter: lazy alloc
@ -584,7 +575,9 @@ void Node::cleanup()
}
// timers
arrayMakeObjectsPerformSelector(_children, cleanup, Node*);
_children.forEach([](Node* child){
child->cleanup();
});
}
@ -596,25 +589,19 @@ const char* Node::description() const
// lazy allocs
void Node::childrenAlloc(void)
{
_children = Array::createWithCapacity(4);
_children->retain();
_children.reserve(4);
}
Node* Node::getChildByTag(int aTag)
{
CCASSERT( aTag != Node::INVALID_TAG, "Invalid tag");
if(_children && _children->count() > 0)
for (auto& child : _children)
{
Object* child;
CCARRAY_FOREACH(_children, child)
{
Node* pNode = static_cast<Node*>(child);
if(pNode && pNode->_tag == aTag)
return pNode;
}
if(child && child->_tag == aTag)
return child;
}
return NULL;
return nullptr;
}
/* "add" logic MUST only be on this method
@ -626,7 +613,7 @@ void Node::addChild(Node *child, int zOrder, int tag)
CCASSERT( child != NULL, "Argument must be non-nil");
CCASSERT( child->_parent == NULL, "child already added. It can't be added again");
if( ! _children )
if (_children.empty())
{
this->childrenAlloc();
}
@ -691,12 +678,12 @@ void Node::removeFromParentAndCleanup(bool cleanup)
void Node::removeChild(Node* child, bool cleanup /* = true */)
{
// explicit nil handling
if (_children == NULL)
if (_children.empty())
{
return;
}
long index = _children->getIndexOfObject(child);
long index = _children.getIndex(child);
if( index != CC_INVALID_INDEX )
this->detachChild( child, index, cleanup );
}
@ -725,33 +712,31 @@ void Node::removeAllChildren()
void Node::removeAllChildrenWithCleanup(bool cleanup)
{
// not using detachChild improves speed here
if ( _children && _children->count() > 0 )
if (!_children.empty())
{
Object* child;
CCARRAY_FOREACH(_children, child)
for (auto& child : _children)
{
Node* pNode = static_cast<Node*>(child);
if (pNode)
if (child)
{
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if(_running)
{
pNode->onExitTransitionDidStart();
pNode->onExit();
child->onExitTransitionDidStart();
child->onExit();
}
if (cleanup)
{
pNode->cleanup();
child->cleanup();
}
// set parent nil at the end
pNode->setParent(NULL);
child->setParent(nullptr);
}
}
_children->removeAllObjects();
_children.clear();
}
}
@ -783,9 +768,9 @@ void Node::detachChild(Node *child, long childIndex, bool doCleanup)
}
// set parent nil at the end
child->setParent(NULL);
child->setParent(nullptr);
_children->removeObjectAtIndex(childIndex);
_children.remove(childIndex);
}
@ -793,7 +778,7 @@ void Node::detachChild(Node *child, long childIndex, bool doCleanup)
void Node::insertChild(Node* child, int z)
{
_reorderChildDirty = true;
_children->addObject(child);
_children.pushBack(child);
child->_setZOrder(z);
}
@ -810,24 +795,24 @@ void Node::sortAllChildren()
#if 0
if (_reorderChildDirty)
{
int i,j,length = _children->count();
int i,j,length = _children.size();
// insertion sort
for(i=1; i<length; i++)
{
j = i-1;
auto tempI = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
auto tempI = static_cast<Node*>( _children.at(i) );
auto tempJ = static_cast<Node*>( _children.at(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempI->_ZOrder < tempJ->_ZOrder || ( tempI->_ZOrder == tempJ->_ZOrder && tempI->_orderOfArrival < tempJ->_orderOfArrival ) ) )
{
_children->fastSetObject( tempJ, j+1 );
_children.fastSetObject( tempJ, j+1 );
j = j-1;
if(j>=0)
tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
tempJ = static_cast<Node*>( _children.at(j) );
}
_children->fastSetObject(tempI, j+1);
_children.fastSetObject(tempI, j+1);
}
//don't need to check children recursively, that's done in visit of each child
@ -836,7 +821,7 @@ void Node::sortAllChildren()
}
#else
if( _reorderChildDirty ) {
std::sort( std::begin(*_children), std::end(*_children), nodeComparisonLess );
std::sort( std::begin(_children), std::end(_children), nodeComparisonLess );
_reorderChildDirty = false;
}
#endif
@ -867,15 +852,15 @@ void Node::visit()
}
this->transform();
int i = 0;
long i = 0;
if(_children && _children->count() > 0)
if(!_children.empty())
{
sortAllChildren();
// draw children zOrder < 0
for( ; i < _children->count(); i++ )
for( ; i < _children.size(); i++ )
{
auto node = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto node = _children.at(i);
if ( node && node->_ZOrder < 0 )
node->visit();
@ -885,12 +870,10 @@ void Node::visit()
// self draw
this->draw();
for( ; i < _children->count(); i++ )
{
auto node = static_cast<Node*>( _children->getObjectAtIndex(i) );
if (node)
node->visit();
}
// Uses std::for_each to improve performance.
std::for_each(_children.cbegin()+i, _children.cend(), [](Node* node){
node->visit();
});
}
else
{
@ -955,7 +938,9 @@ void Node::onEnter()
{
_isTransitionFinished = false;
arrayMakeObjectsPerformSelector(_children, onEnter, Node*);
_children.forEach([](Node* child){
child->onEnter();
});
this->resume();
@ -974,8 +959,10 @@ void Node::onEnterTransitionDidFinish()
{
_isTransitionFinished = true;
arrayMakeObjectsPerformSelector(_children, onEnterTransitionDidFinish, Node*);
_children.forEach([](Node* child){
child->onEnterTransitionDidFinish();
});
if (_scriptType != kScriptTypeNone)
{
int action = kNodeOnEnterTransitionDidFinish;
@ -987,7 +974,10 @@ void Node::onEnterTransitionDidFinish()
void Node::onExitTransitionDidStart()
{
arrayMakeObjectsPerformSelector(_children, onExitTransitionDidStart, Node*);
_children.forEach([](Node* child){
child->onExitTransitionDidStart();
});
if (_scriptType != kScriptTypeNone)
{
int action = kNodeOnExitTransitionDidStart;
@ -1010,7 +1000,9 @@ void Node::onExit()
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
}
arrayMakeObjectsPerformSelector(_children, onExit, Node*);
_children.forEach([](Node* child){
child->onExit();
});
}
void Node::setEventDispatcher(EventDispatcher* dispatcher)
@ -1063,7 +1055,7 @@ Action * Node::getActionByTag(int tag)
return _actionManager->getActionByTag(tag, this);
}
unsigned int Node::getNumberOfRunningActions() const
long Node::getNumberOfRunningActions() const
{
return _actionManager->getNumberOfRunningActionsInTarget(this);
}
@ -1358,7 +1350,9 @@ bool Node::updatePhysicsTransform()
void Node::updateTransform()
{
// Recursively iterate over children
arrayMakeObjectsPerformSelector(_children, updateTransform, Node*);
_children.forEach([](Node* child){
child->updateTransform();
});
}
Component* Node::getComponent(const char *pName)
@ -1467,15 +1461,13 @@ void NodeRGBA::updateDisplayedOpacity(GLubyte parentOpacity)
if (_cascadeOpacityEnabled)
{
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
RGBAProtocol* item = dynamic_cast<RGBAProtocol*>(pObj);
_children.forEach([this](Node* child){
RGBAProtocol* item = dynamic_cast<RGBAProtocol*>(child);
if (item)
{
item->updateDisplayedOpacity(_displayedOpacity);
}
}
});
}
}
@ -1524,15 +1516,13 @@ void NodeRGBA::updateDisplayedColor(const Color3B& parentColor)
if (_cascadeColorEnabled)
{
Object *obj = NULL;
CCARRAY_FOREACH(_children, obj)
{
RGBAProtocol *item = dynamic_cast<RGBAProtocol*>(obj);
_children.forEach([this](Node* child){
RGBAProtocol *item = dynamic_cast<RGBAProtocol*>(child);
if (item)
{
item->updateDisplayedColor(_displayedColor);
}
}
});
}
}

View File

@ -38,8 +38,7 @@
#include "CCScriptSupport.h"
#include "CCProtocols.h"
#include "CCEventDispatcher.h"
#include <vector>
#include "CCVector.h"
NS_CC_BEGIN
@ -614,10 +613,10 @@ public:
*
* @return An array of children
*/
virtual Array* getChildren() { return _children; }
virtual const Array *getChildren() const { return _children; }
/**
virtual Vector<Node*>& getChildren() { return _children; }
virtual const Vector<Node*>& getChildren() const { return _children; }
/**
* Get the amount of children.
*
* @return The amount of children.
@ -1043,7 +1042,7 @@ public:
*
* @return The number of actions that are running plus the ones that are schedule to run
*/
unsigned int getNumberOfRunningActions() const;
long getNumberOfRunningActions() const;
/** @deprecated Use getNumberOfRunningActions() instead */
CC_DEPRECATED_ATTRIBUTE unsigned int numberOfRunningActions() const { return getNumberOfRunningActions(); };
@ -1398,7 +1397,7 @@ protected:
/// lazy allocs
void childrenAlloc(void);
/// helper that reorder a child
void insertChild(Node* child, int z);
@ -1440,8 +1439,8 @@ protected:
GridBase *_grid; ///< a grid
int _ZOrder; ///< z-order value that affects the draw order
Array *_children; ///< array of children nodes
Vector<Node*> _children; ///< array of children nodes
Node *_parent; ///< weak reference to parent node
int _tag; ///< a tag. Can be any number you assigned just to identify this node

View File

@ -95,10 +95,8 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity)
_textureAtlas = new TextureAtlas();
_textureAtlas->initWithTexture(tex, capacity);
// no lazy alloc in this node
_children = new Array();
_children->initWithCapacity(capacity);
_children.reserve(capacity);
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
@ -171,7 +169,7 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
CCASSERT( child->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCParticleSystem is not using the same texture id");
// If this is the 1st children, then copy blending function
if( _children->count() == 0 )
if (_children.empty())
{
setBlendFunc(child->getBlendFunc());
}
@ -179,16 +177,15 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
CCASSERT( _blendFunc.src == child->getBlendFunc().src && _blendFunc.dst == child->getBlendFunc().dst, "Can't add a ParticleSystem that uses a different blending function");
//no lazy sorting, so don't call super addChild, call helper instead
unsigned int pos = addChildHelper(child,zOrder,tag);
long pos = addChildHelper(child,zOrder,tag);
//get new atlasIndex
int atlasIndex = 0;
if (pos != 0)
{
ParticleSystem* p = (ParticleSystem*)_children->getObjectAtIndex(pos-1);
ParticleSystem* p = static_cast<ParticleSystem*>(_children.at(pos-1));
atlasIndex = p->getAtlasIndex() + p->getTotalParticles();
}
else
{
@ -205,21 +202,17 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
// XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster
// XXX or possibly using vertexZ for reordering, that would be fastest
// this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting
unsigned int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag)
long ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag)
{
CCASSERT( child != NULL, "Argument must be non-nil");
CCASSERT( child->getParent() == NULL, "child already added. It can't be added again");
if( ! _children )
{
_children = new Array();
_children->initWithCapacity(4);
}
_children.reserve(4);
//don't use a lazy insert
unsigned int pos = searchNewPositionInChildrenForZ(z);
long pos = searchNewPositionInChildrenForZ(z);
_children->insertObject(child, pos);
_children.insert(pos, child);
child->setTag(aTag);
child->_setZOrder(z);
@ -239,7 +232,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
{
CCASSERT( aChild != NULL, "Child must be non-NULL");
CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children");
CCASSERT( _children->containsObject(aChild), "Child doesn't belong to batch" );
CCASSERT( _children.contains(aChild), "Child doesn't belong to batch" );
ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
@ -249,9 +242,9 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
}
// no reordering if only 1 child
if( _children->count() > 1)
if (!_children.empty())
{
unsigned int newIndex = 0, oldIndex = 0;
long newIndex = 0, oldIndex = 0;
getCurrentIndex(&oldIndex, &newIndex, child, zOrder);
@ -260,8 +253,8 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
// reorder _children->array
child->retain();
_children->removeObjectAtIndex(oldIndex);
_children->insertObject(child, newIndex);
_children.remove(oldIndex);
_children.insert(newIndex, child);
child->release();
// save old altasIndex
@ -272,10 +265,10 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
// Find new AtlasIndex
int newAtlasIndex = 0;
for( int i=0;i < _children->count();i++)
for( int i=0;i < _children.size();i++)
{
ParticleSystem* pNode = (ParticleSystem*)_children->getObjectAtIndex(i);
if( pNode == child )
ParticleSystem* node = static_cast<ParticleSystem*>(_children.at(i));
if( node == child )
{
newAtlasIndex = child->getAtlasIndex();
break;
@ -292,17 +285,17 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
child->_setZOrder(zOrder);
}
void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, Node* child, int z)
void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* newIndex, Node* child, int z)
{
bool foundCurrentIdx = false;
bool foundNewIdx = false;
int minusOne = 0;
unsigned int count = _children->count();
long count = _children.size();
for( unsigned int i=0; i < count; i++ )
for( long i=0; i < count; i++ )
{
Node* pNode = (Node *)_children->getObjectAtIndex(i);
Node* pNode = _children.at(i);
// new index
if( pNode->getZOrder() > z && ! foundNewIdx )
@ -343,13 +336,13 @@ void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* ne
*newIndex += minusOne;
}
unsigned int ParticleBatchNode::searchNewPositionInChildrenForZ(int z)
long ParticleBatchNode::searchNewPositionInChildrenForZ(int z)
{
unsigned int count = _children->count();
long count = _children.size();
for( unsigned int i=0; i < count; i++ )
for( long i=0; i < count; i++ )
{
Node *child = (Node *)_children->getObjectAtIndex(i);
Node *child = _children.at(i);
if (child->getZOrder() > z)
{
return i;
@ -366,7 +359,7 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup)
return;
CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children");
CCASSERT(_children->containsObject(aChild), "CCParticleBatchNode doesn't contain the sprite. Can't remove it");
CCASSERT(_children.contains(aChild), "CCParticleBatchNode doesn't contain the sprite. Can't remove it");
ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
Node::removeChild(child, cleanup);
@ -385,12 +378,14 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup)
void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup)
{
removeChild((ParticleSystem *)_children->getObjectAtIndex(index),doCleanup);
removeChild(_children.at(index), doCleanup);
}
void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
{
arrayMakeObjectsPerformSelectorWithObject(_children, setBatchNode, NULL, ParticleSystem*);
_children.forEach([](Node* child){
static_cast<ParticleSystem*>(child)->setBatchNode(nullptr);
});
Node::removeAllChildrenWithCleanup(doCleanup);
@ -417,7 +412,7 @@ void ParticleBatchNode::draw(void)
void ParticleBatchNode::increaseAtlasCapacityTo(unsigned int quantity)
void ParticleBatchNode::increaseAtlasCapacityTo(long quantity)
{
CCLOG("cocos2d: ParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].",
(long)_textureAtlas->getCapacity(),
@ -467,15 +462,13 @@ void ParticleBatchNode::insertChild(ParticleSystem* system, int index)
//rebuild atlas indexes
void ParticleBatchNode::updateAllAtlasIndexes()
{
Object *pObj = NULL;
unsigned int index = 0;
CCARRAY_FOREACH(_children,pObj)
{
ParticleSystem* child = static_cast<ParticleSystem*>(pObj);
child->setAtlasIndex(index);
index += child->getTotalParticles();
}
_children.forEach([&index](Node* child){
ParticleSystem* partiSys = static_cast<ParticleSystem*>(child);
partiSys->setAtlasIndex(index);
index += partiSys->getTotalParticles();
});
}
// ParticleBatchNode - CocosNodeTexture protocol

View File

@ -129,10 +129,10 @@ public:
private:
void updateAllAtlasIndexes();
void increaseAtlasCapacityTo(unsigned int quantity);
unsigned int searchNewPositionInChildrenForZ(int z);
void getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, Node* child, int z);
unsigned int addChildHelper(ParticleSystem* child, int z, int aTag);
void increaseAtlasCapacityTo(long quantity);
long searchNewPositionInChildrenForZ(int z);
void getCurrentIndex(long* oldIndex, long* newIndex, Node* child, int z);
long addChildHelper(ParticleSystem* child, int z, int aTag);
void updateBlendFunc(void);
/** the texture atlas used for drawing the quads */
TextureAtlas* _textureAtlas;

View File

@ -169,9 +169,9 @@ bool ParticleSystem::initWithFile(const std::string& plistFile)
{
bool bRet = false;
_plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile);
Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(_plistFile.c_str());
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(_plistFile.c_str());
CCASSERT( dict != NULL, "Particles: file not found");
CCASSERT( !dict.empty(), "Particles: file not found");
// XXX compute path from a path, should define a function somewhere to do it
string listFilePath = plistFile;
@ -185,113 +185,110 @@ bool ParticleSystem::initWithFile(const std::string& plistFile)
bRet = this->initWithDictionary(dict, "");
}
dict->release();
return bRet;
}
bool ParticleSystem::initWithDictionary(Dictionary *dictionary)
bool ParticleSystem::initWithDictionary(ValueMap& dictionary)
{
return initWithDictionary(dictionary, "");
}
bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::string& dirname)
bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname)
{
bool bRet = false;
unsigned char *buffer = NULL;
unsigned char *deflated = NULL;
Image *image = NULL;
unsigned char *buffer = nullptr;
unsigned char *deflated = nullptr;
Image *image = nullptr;
do
{
int maxParticles = dictionary->valueForKey("maxParticles")->intValue();
int maxParticles = dictionary["maxParticles"].asInt();
// self, not super
if(this->initWithTotalParticles(maxParticles))
{
// Emitter name in particle designer 2.0
const String * configNameConstStr = dictionary->valueForKey("configName");
_configName = configNameConstStr->getCString();
_configName = dictionary["configName"].asString();
// angle
_angle = dictionary->valueForKey("angle")->floatValue();
_angleVar = dictionary->valueForKey("angleVariance")->floatValue();
_angle = dictionary["angle"].asFloat();
_angleVar = dictionary["angleVariance"].asFloat();
// duration
_duration = dictionary->valueForKey("duration")->floatValue();
_duration = dictionary["duration"].asFloat();
// blend function
if (_configName.length()>0)
{
_blendFunc.src = dictionary->valueForKey("blendFuncSource")->floatValue();
_blendFunc.src = dictionary["blendFuncSource"].asFloat();
}
else
{
_blendFunc.src = dictionary->valueForKey("blendFuncSource")->intValue();
_blendFunc.src = dictionary["blendFuncSource"].asInt();
}
_blendFunc.dst = dictionary->valueForKey("blendFuncDestination")->intValue();
_blendFunc.dst = dictionary["blendFuncDestination"].asInt();
// color
_startColor.r = dictionary->valueForKey("startColorRed")->floatValue();
_startColor.g = dictionary->valueForKey("startColorGreen")->floatValue();
_startColor.b = dictionary->valueForKey("startColorBlue")->floatValue();
_startColor.a = dictionary->valueForKey("startColorAlpha")->floatValue();
_startColor.r = dictionary["startColorRed"].asFloat();
_startColor.g = dictionary["startColorGreen"].asFloat();
_startColor.b = dictionary["startColorBlue"].asFloat();
_startColor.a = dictionary["startColorAlpha"].asFloat();
_startColorVar.r = dictionary->valueForKey("startColorVarianceRed")->floatValue();
_startColorVar.g = dictionary->valueForKey("startColorVarianceGreen")->floatValue();
_startColorVar.b = dictionary->valueForKey("startColorVarianceBlue")->floatValue();
_startColorVar.a = dictionary->valueForKey("startColorVarianceAlpha")->floatValue();
_startColorVar.r = dictionary["startColorVarianceRed"].asFloat();
_startColorVar.g = dictionary["startColorVarianceGreen"].asFloat();
_startColorVar.b = dictionary["startColorVarianceBlue"].asFloat();
_startColorVar.a = dictionary["startColorVarianceAlpha"].asFloat();
_endColor.r = dictionary->valueForKey("finishColorRed")->floatValue();
_endColor.g = dictionary->valueForKey("finishColorGreen")->floatValue();
_endColor.b = dictionary->valueForKey("finishColorBlue")->floatValue();
_endColor.a = dictionary->valueForKey("finishColorAlpha")->floatValue();
_endColor.r = dictionary["finishColorRed"].asFloat();
_endColor.g = dictionary["finishColorGreen"].asFloat();
_endColor.b = dictionary["finishColorBlue"].asFloat();
_endColor.a = dictionary["finishColorAlpha"].asFloat();
_endColorVar.r = dictionary->valueForKey("finishColorVarianceRed")->floatValue();
_endColorVar.g = dictionary->valueForKey("finishColorVarianceGreen")->floatValue();
_endColorVar.b = dictionary->valueForKey("finishColorVarianceBlue")->floatValue();
_endColorVar.a = dictionary->valueForKey("finishColorVarianceAlpha")->floatValue();
_endColorVar.r = dictionary["finishColorVarianceRed"].asFloat();
_endColorVar.g = dictionary["finishColorVarianceGreen"].asFloat();
_endColorVar.b = dictionary["finishColorVarianceBlue"].asFloat();
_endColorVar.a = dictionary["finishColorVarianceAlpha"].asFloat();
// particle size
_startSize = dictionary->valueForKey("startParticleSize")->floatValue();
_startSizeVar = dictionary->valueForKey("startParticleSizeVariance")->floatValue();
_endSize = dictionary->valueForKey("finishParticleSize")->floatValue();
_endSizeVar = dictionary->valueForKey("finishParticleSizeVariance")->floatValue();
_startSize = dictionary["startParticleSize"].asFloat();
_startSizeVar = dictionary["startParticleSizeVariance"].asFloat();
_endSize = dictionary["finishParticleSize"].asFloat();
_endSizeVar = dictionary["finishParticleSizeVariance"].asFloat();
// position
float x = dictionary->valueForKey("sourcePositionx")->floatValue();
float y = dictionary->valueForKey("sourcePositiony")->floatValue();
float x = dictionary["sourcePositionx"].asFloat();
float y = dictionary["sourcePositiony"].asFloat();
this->setPosition( Point(x,y) );
_posVar.x = dictionary->valueForKey("sourcePositionVariancex")->floatValue();
_posVar.y = dictionary->valueForKey("sourcePositionVariancey")->floatValue();
_posVar.x = dictionary["sourcePositionVariancex"].asFloat();
_posVar.y = dictionary["sourcePositionVariancey"].asFloat();
// Spinning
_startSpin = dictionary->valueForKey("rotationStart")->floatValue();
_startSpinVar = dictionary->valueForKey("rotationStartVariance")->floatValue();
_endSpin= dictionary->valueForKey("rotationEnd")->floatValue();
_endSpinVar= dictionary->valueForKey("rotationEndVariance")->floatValue();
_startSpin = dictionary["rotationStart"].asFloat();
_startSpinVar = dictionary["rotationStartVariance"].asFloat();
_endSpin= dictionary["rotationEnd"].asFloat();
_endSpinVar= dictionary["rotationEndVariance"].asFloat();
_emitterMode = (Mode) dictionary->valueForKey("emitterType")->intValue();
_emitterMode = (Mode) dictionary["emitterType"].asInt();
// Mode A: Gravity + tangential accel + radial accel
if (_emitterMode == Mode::GRAVITY)
{
// gravity
modeA.gravity.x = dictionary->valueForKey("gravityx")->floatValue();
modeA.gravity.y = dictionary->valueForKey("gravityy")->floatValue();
modeA.gravity.x = dictionary["gravityx"].asFloat();
modeA.gravity.y = dictionary["gravityy"].asFloat();
// speed
modeA.speed = dictionary->valueForKey("speed")->floatValue();
modeA.speedVar = dictionary->valueForKey("speedVariance")->floatValue();
modeA.speed = dictionary["speed"].asFloat();
modeA.speedVar = dictionary["speedVariance"].asFloat();
// radial acceleration
modeA.radialAccel = dictionary->valueForKey("radialAcceleration")->floatValue();
modeA.radialAccelVar = dictionary->valueForKey("radialAccelVariance")->floatValue();
modeA.radialAccel = dictionary["radialAcceleration"].asFloat();
modeA.radialAccelVar = dictionary["radialAccelVariance"].asFloat();
// tangential acceleration
modeA.tangentialAccel = dictionary->valueForKey("tangentialAcceleration")->floatValue();
modeA.tangentialAccelVar = dictionary->valueForKey("tangentialAccelVariance")->floatValue();
modeA.tangentialAccel = dictionary["tangentialAcceleration"].asFloat();
modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].asFloat();
// rotation is dir
modeA.rotationIsDir = dictionary->valueForKey("rotationIsDir")->boolValue();
modeA.rotationIsDir = dictionary["rotationIsDir"].asBool();
}
// or Mode B: radius movement
@ -299,31 +296,31 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
{
if (_configName.length()>0)
{
modeB.startRadius = dictionary->valueForKey("maxRadius")->intValue();
modeB.startRadius = dictionary["maxRadius"].asInt();
}
else
{
modeB.startRadius = dictionary->valueForKey("maxRadius")->floatValue();
modeB.startRadius = dictionary["maxRadius"].asFloat();
}
modeB.startRadiusVar = dictionary->valueForKey("maxRadiusVariance")->floatValue();
modeB.startRadiusVar = dictionary["maxRadiusVariance"].asFloat();
if (_configName.length()>0)
{
modeB.endRadius = dictionary->valueForKey("minRadius")->intValue();
modeB.endRadius = dictionary["minRadius"].asInt();
}
else
{
modeB.endRadius = dictionary->valueForKey("minRadius")->floatValue();
modeB.endRadius = dictionary["minRadius"].asFloat();
}
modeB.endRadiusVar = 0.0f;
if (_configName.length()>0)
{
modeB.rotatePerSecond = dictionary->valueForKey("rotatePerSecond")->intValue();
modeB.rotatePerSecond = dictionary["rotatePerSecond"].asInt();
}
else
{
modeB.rotatePerSecond = dictionary->valueForKey("rotatePerSecond")->floatValue();
modeB.rotatePerSecond = dictionary["rotatePerSecond"].asFloat();
}
modeB.rotatePerSecondVar = dictionary->valueForKey("rotatePerSecondVariance")->floatValue();
modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].asFloat();
} else {
CCASSERT( false, "Invalid emitterType in config file");
@ -331,8 +328,8 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
}
// life span
_life = dictionary->valueForKey("particleLifespan")->floatValue();
_lifeVar = dictionary->valueForKey("particleLifespanVariance")->floatValue();
_life = dictionary["particleLifespan"].asFloat();
_lifeVar = dictionary["particleLifespanVariance"].asFloat();
// emission Rate
_emissionRate = _totalParticles / _life;
@ -345,7 +342,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
// texture
// Try to get the texture from the cache
std::string textureName = dictionary->valueForKey("textureFileName")->getCString();
std::string textureName = dictionary["textureFileName"].asString();
size_t rPos = textureName.rfind('/');
@ -385,19 +382,19 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
}
else
{
const char *textureData = dictionary->valueForKey("textureImageData")->getCString();
CCASSERT(textureData, "");
std::string textureData = dictionary["textureImageData"].asString();
CCASSERT(!textureData.empty(), "");
long dataLen = strlen(textureData);
if(dataLen != 0)
long dataLen = textureData.size();
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");
int decodeLen = base64Decode((unsigned char*)textureData.c_str(), (unsigned int)dataLen, &buffer);
CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData");
CC_BREAK_IF(!buffer);
int deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated);
CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData");
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()
@ -413,7 +410,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
}
if (_configName.length()>0)
{
_yCoordFlipped = dictionary->valueForKey("yCoordFlipped")->intValue();
_yCoordFlipped = dictionary["yCoordFlipped"].asInt();
}
CCASSERT( this->_texture != NULL, "CCParticleSystem: error loading the texture");
}

View File

@ -28,7 +28,7 @@ THE SOFTWARE.
#include "CCProtocols.h"
#include "CCNode.h"
#include "CCDictionary.h"
#include "CCValue.h"
#include "CCString.h"
NS_CC_BEGIN
@ -386,12 +386,12 @@ protected:
/** initializes a QuadParticleSystem from a Dictionary.
@since v0.99.3
*/
bool initWithDictionary(Dictionary *dictionary);
bool initWithDictionary(ValueMap& dictionary);
/** initializes a particle system from a NSDictionary and the path from where to load the png
@since v2.1
*/
bool initWithDictionary(Dictionary *dictionary, const std::string& dirname);
bool initWithDictionary(ValueMap& dictionary, const std::string& dirname);
//! Initializes a system with a fixed number of particles
virtual bool initWithTotalParticles(int numberOfParticles);

View File

@ -528,16 +528,12 @@ void RenderTexture::draw()
//! make sure all children are drawn
sortAllChildren();
Object *pElement;
CCARRAY_FOREACH(_children, pElement)
{
Node *child = static_cast<Node*>(pElement);
_children.forEach([this](Node* child){
if (child != _sprite)
{
child->visit();
}
}
});
end();
}

View File

@ -132,25 +132,17 @@ void Scene::addChildToPhysicsWorld(Node* child)
{
if (_physicsWorld)
{
std::function<void(Object*)> addToPhysicsWorldFunc = nullptr;
addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void
std::function<void(Node*)> addToPhysicsWorldFunc = nullptr;
addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Node* node) -> void
{
if (dynamic_cast<Node*>(obj) != nullptr)
if (node->getPhysicsBody())
{
Node* node = dynamic_cast<Node*>(obj);
if (node->getPhysicsBody())
{
_physicsWorld->addBody(node->getPhysicsBody());
}
Object* subChild = nullptr;
CCARRAY_FOREACH(node->getChildren(), subChild)
{
addToPhysicsWorldFunc(subChild);
}
_physicsWorld->addBody(node->getPhysicsBody());
}
node->getChildren().forEach([addToPhysicsWorldFunc](Node* n){
addToPhysicsWorldFunc(n);
});
};
addToPhysicsWorldFunc(child);

View File

@ -696,7 +696,7 @@ void Sprite::addChild(Node *child, int zOrder, int tag)
void Sprite::reorderChild(Node *child, int zOrder)
{
CCASSERT(child != NULL, "");
CCASSERT(_children->containsObject(child), "");
CCASSERT(_children.contains(child), "");
if (zOrder == child->getZOrder())
{
@ -726,15 +726,13 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup)
{
if (_batchNode)
{
Object* object = NULL;
CCARRAY_FOREACH(_children, object)
{
Sprite* child = dynamic_cast<Sprite*>(object);
if (child)
_children.forEach([this](Node* child){
Sprite* sprite = dynamic_cast<Sprite*>(child);
if (sprite)
{
_batchNode->removeSpriteFromAtlas(child);
_batchNode->removeSpriteFromAtlas(sprite);
}
}
});
}
Node::removeAllChildrenWithCleanup(cleanup);
@ -769,12 +767,14 @@ void Sprite::sortAllChildren()
_children->fastSetObject(tempI, j+1);
}
#else
std::sort(std::begin(*_children), std::end(*_children), nodeComparisonLess);
std::sort(std::begin(_children), std::end(_children), nodeComparisonLess);
#endif
if ( _batchNode)
{
arrayMakeObjectsPerformSelector(_children, sortAllChildren, Sprite*);
_children.forEach([](Node* child){
child->sortAllChildren();
});
}
_reorderChildDirty = false;
@ -809,15 +809,13 @@ void Sprite::setDirtyRecursively(bool bValue)
// recursively set dirty
if (_hasChildren)
{
Object* object = NULL;
CCARRAY_FOREACH(_children, object)
{
Sprite* child = dynamic_cast<Sprite*>(object);
if (child)
_children.forEach([](Node* child){
Sprite* sp = dynamic_cast<Sprite*>(child);
if (sp)
{
child->setDirtyRecursively(true);
sp->setDirtyRecursively(true);
}
}
});
}
}
@ -1062,7 +1060,7 @@ void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName,
CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found");
AnimationFrame* frame = static_cast<AnimationFrame*>( a->getFrames()->getObjectAtIndex(frameIndex) );
AnimationFrame* frame = a->getFrames().at(frameIndex);
CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame");

View File

@ -92,9 +92,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity)
updateBlendFunc();
// no lazy alloc in this node
_children = new Array();
_children->initWithCapacity(capacity);
_children.reserve(capacity);
_descendants.reserve(capacity);
@ -187,7 +185,7 @@ void SpriteBatchNode::addChild(Node *child, int zOrder, int tag)
void SpriteBatchNode::reorderChild(Node *child, int zOrder)
{
CCASSERT(child != NULL, "the child should not be null");
CCASSERT(_children->containsObject(child), "Child doesn't belong to Sprite");
CCASSERT(_children.contains(child), "Child doesn't belong to Sprite");
if (zOrder == child->getZOrder())
{
@ -209,7 +207,7 @@ void SpriteBatchNode::removeChild(Node *child, bool cleanup)
return;
}
CCASSERT(_children->containsObject(sprite), "sprite batch node should contain the child");
CCASSERT(_children.contains(sprite), "sprite batch node should contain the child");
// cleanup before removing
removeSpriteFromAtlas(sprite);
@ -219,8 +217,8 @@ void SpriteBatchNode::removeChild(Node *child, bool cleanup)
void SpriteBatchNode::removeChildAtIndex(int index, bool doCleanup)
{
CCASSERT(index>=0 && index < _children->count(), "Invalid index");
removeChild( static_cast<Sprite*>(_children->getObjectAtIndex(index)), doCleanup);
CCASSERT(index>=0 && index < _children.size(), "Invalid index");
removeChild(_children.at(index), doCleanup);
}
void SpriteBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
@ -265,25 +263,25 @@ void SpriteBatchNode::sortAllChildren()
_children->fastSetObject(tempI, j+1);
}
#else
std::sort(std::begin(*_children), std::end(*_children), nodeComparisonLess);
std::sort(std::begin(_children), std::end(_children), nodeComparisonLess);
#endif
//sorted now check all children
if (_children->count() > 0)
if (!_children.empty())
{
//first sort all children recursively based on zOrder
arrayMakeObjectsPerformSelector(_children, sortAllChildren, Sprite*);
_children.forEach([](Node* child){
child->sortAllChildren();
});
int index=0;
Object* obj = NULL;
//fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact)
// and at the same time reorder descendants and the quads to the right index
CCARRAY_FOREACH(_children, obj)
{
Sprite* child = static_cast<Sprite*>(obj);
updateAtlasIndex(child, &index);
}
_children.forEach([this, &index](Node* child){
Sprite* sp = static_cast<Sprite*>(child);
updateAtlasIndex(sp, &index);
});
}
_reorderChildDirty=false;
@ -292,12 +290,8 @@ void SpriteBatchNode::sortAllChildren()
void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
{
int count = 0;
Array* array = sprite->getChildren();
if (array != NULL)
{
count = array->count();
}
auto& array = sprite->getChildren();
long count = array.size();
int oldIndex = 0;
@ -315,7 +309,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
{
bool needNewIndex=true;
if (static_cast<Sprite*>(array->getObjectAtIndex(0) )->getZOrder() >= 0)
if (array.at(0)->getZOrder() >= 0)
{
//all children are in front of the parent
oldIndex = sprite->getAtlasIndex();
@ -330,11 +324,9 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
needNewIndex = false;
}
Object* obj = NULL;
CCARRAY_FOREACH(array,obj)
{
Sprite* child = static_cast<Sprite*>(obj);
if (needNewIndex && child->getZOrder() >= 0)
array.forEach([&](Node* child){
Sprite* sp = static_cast<Sprite*>(child);
if (needNewIndex && sp->getZOrder() >= 0)
{
oldIndex = sprite->getAtlasIndex();
sprite->setAtlasIndex(*curIndex);
@ -344,11 +336,10 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
}
(*curIndex)++;
needNewIndex = false;
}
updateAtlasIndex(child, curIndex);
}
updateAtlasIndex(sp, curIndex);
});
if (needNewIndex)
{//all children have a zOrder < 0)
@ -399,7 +390,9 @@ void SpriteBatchNode::draw(void)
CC_NODE_DRAW_SETUP();
arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*);
_children.forEach([](Node* child){
child->updateTransform();
});
GL::blendFunc( _blendFunc.src, _blendFunc.dst );
@ -413,11 +406,11 @@ void SpriteBatchNode::increaseAtlasCapacity(void)
// if we're going beyond the current TextureAtlas's capacity,
// all the previously initialized sprites will need to redo their texture coords
// this is likely computationally expensive
int quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3;
long quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3;
CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].",
(long)_textureAtlas->getCapacity(),
(long)quantity);
_textureAtlas->getCapacity(),
quantity);
if (! _textureAtlas->resizeCapacity(quantity))
{
@ -429,22 +422,17 @@ void SpriteBatchNode::increaseAtlasCapacity(void)
int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index)
{
CCASSERT(index>=0 && index < _children->count(), "Invalid index");
CCASSERT(index>=0 && index < _children.size(), "Invalid index");
Array *children = parent->getChildren();
auto& children = parent->getChildren();
if (children && children->count() > 0)
{
Object* object = NULL;
CCARRAY_FOREACH(children, object)
children.forEach([this, &index](Node* child){
Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() < 0))
{
Sprite* child = static_cast<Sprite*>(object);
if (child && (child->getZOrder() < 0))
{
index = rebuildIndexInOrder(child, index);
}
index = rebuildIndexInOrder(sp, index);
}
}
});
// ignore self (batch node)
if (! parent->isEqual(this))
@ -453,61 +441,56 @@ int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index)
index++;
}
if (children && children->count() > 0)
{
Object* object = NULL;
CCARRAY_FOREACH(children, object)
children.forEach([this, &index](Node* child){
Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() >= 0))
{
Sprite* child = static_cast<Sprite*>(object);
if (child && (child->getZOrder() >= 0))
{
index = rebuildIndexInOrder(child, index);
}
index = rebuildIndexInOrder(sp, index);
}
}
});
return index;
}
int SpriteBatchNode::highestAtlasIndexInChild(Sprite *sprite)
{
Array *children = sprite->getChildren();
auto& children = sprite->getChildren();
if (! children || children->count() == 0)
if (children.size() == 0)
{
return sprite->getAtlasIndex();
}
else
{
return highestAtlasIndexInChild( static_cast<Sprite*>(children->getLastObject()));
return highestAtlasIndexInChild( static_cast<Sprite*>(children.back()));
}
}
int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite)
{
Array *children = sprite->getChildren();
auto& children = sprite->getChildren();
if (! children || children->count() == 0)
if (children.size() == 0)
{
return sprite->getAtlasIndex();
}
else
{
return lowestAtlasIndexInChild(static_cast<Sprite*>(children->getObjectAtIndex(0)));
return lowestAtlasIndexInChild(static_cast<Sprite*>(children.at(0)));
}
}
int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ)
{
Array *siblings = sprite->getParent()->getChildren();
int childIndex = siblings->getIndexOfObject(sprite);
auto& siblings = sprite->getParent()->getChildren();
long childIndex = siblings.getIndex(sprite);
// ignore parent Z if parent is spriteSheet
bool ignoreParent = (SpriteBatchNode*)(sprite->getParent()) == this;
Sprite *prev = NULL;
if (childIndex > 0 && childIndex != -1)
{
prev = static_cast<Sprite*>(siblings->getObjectAtIndex(childIndex - 1));
prev = static_cast<Sprite*>(siblings.at(childIndex - 1));
}
// first child of the sprite sheet
@ -568,7 +551,7 @@ void SpriteBatchNode::appendChild(Sprite* sprite)
}
_descendants.push_back(sprite);
int index = _descendants.size()-1;
long index = _descendants.size()-1;
sprite->setAtlasIndex(index);
@ -576,13 +559,9 @@ void SpriteBatchNode::appendChild(Sprite* sprite)
_textureAtlas->insertQuad(&quad, index);
// add children recursively
Object* obj = nullptr;
CCARRAY_FOREACH(sprite->getChildren(), obj)
{
Sprite* child = static_cast<Sprite*>(obj);
appendChild(child);
}
sprite->getChildren().forEach([this](Node* child){
appendChild(static_cast<Sprite*>(child));
});
}
void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
@ -606,19 +585,14 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
}
// remove children recursively
Array *children = sprite->getChildren();
if (children && children->count() > 0)
{
Object* object = NULL;
CCARRAY_FOREACH(children, object)
auto& children = sprite->getChildren();
children.forEach([this](Node* obj){
Sprite* child = static_cast<Sprite*>(obj);
if (child)
{
Sprite* child = static_cast<Sprite*>(object);
if (child)
{
removeSpriteFromAtlas(child);
}
removeSpriteFromAtlas(child);
}
}
});
}
void SpriteBatchNode::updateBlendFunc(void)

View File

@ -64,22 +64,18 @@ void SpriteFrameCache::destroyInstance()
bool SpriteFrameCache::init(void)
{
_spriteFrames= new Dictionary();
_spriteFrames->init();
_spriteFramesAliases = new Dictionary();
_spriteFramesAliases->init();
_spriteFrames.reserve(20);
_spriteFramesAliases.reserve(20);
_loadedFileNames = new std::set<std::string>();
return true;
}
SpriteFrameCache::~SpriteFrameCache(void)
{
CC_SAFE_RELEASE(_spriteFrames);
CC_SAFE_RELEASE(_spriteFramesAliases);
CC_SAFE_DELETE(_loadedFileNames);
}
void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Texture2D *pobTexture)
void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture)
{
/*
Supported Zwoptex Formats:
@ -90,25 +86,24 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
*/
Dictionary *metadataDict = (Dictionary*)dictionary->objectForKey("metadata");
Dictionary *framesDict = (Dictionary*)dictionary->objectForKey("frames");
ValueMap& metadataDict = dictionary["metadata"].asValueMap();
ValueMap& framesDict = dictionary["frames"].asValueMap();
int format = 0;
// get the format
if(metadataDict != NULL)
if (!metadataDict.empty())
{
format = metadataDict->valueForKey("format")->intValue();
format = metadataDict["format"].asInt();
}
// check the format
CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
DictElement* element = NULL;
CCDICT_FOREACH(framesDict, element)
for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter)
{
Dictionary* frameDict = static_cast<Dictionary*>(element->getObject());
std::string spriteFrameName = element->getStrKey();
SpriteFrame* spriteFrame = static_cast<SpriteFrame*>(_spriteFrames->objectForKey(spriteFrameName));
ValueMap& frameDict = iter->second.asValueMap();
std::string spriteFrameName = iter->first;
SpriteFrame* spriteFrame = _spriteFrames.at(spriteFrameName);
if (spriteFrame)
{
continue;
@ -116,14 +111,14 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
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();
float x = frameDict["x"].asFloat();
float y = frameDict["y"].asFloat();
float w = frameDict["width"].asFloat();
float h = frameDict["height"].asFloat();
float ox = frameDict["offsetX"].asFloat();
float oy = frameDict["offsetY"].asFloat();
int ow = frameDict["originalWidth"].asInt();
int oh = frameDict["originalHeight"].asInt();
// check ow/oh
if(!ow || !oh)
{
@ -134,7 +129,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
oh = abs(oh);
// create frame
spriteFrame = new SpriteFrame();
spriteFrame->initWithTexture(pobTexture,
spriteFrame->initWithTexture(texture,
Rect(x, y, w, h),
false,
Point(ox, oy),
@ -143,21 +138,21 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
}
else if(format == 1 || format == 2)
{
Rect frame = RectFromString(frameDict->valueForKey("frame")->getCString());
Rect frame = RectFromString(frameDict["frame"].asString());
bool rotated = false;
// rotation
if (format == 2)
{
rotated = frameDict->valueForKey("rotated")->boolValue();
rotated = frameDict["rotated"].asBool();
}
Point offset = PointFromString(frameDict->valueForKey("offset")->getCString());
Size sourceSize = SizeFromString(frameDict->valueForKey("sourceSize")->getCString());
Point offset = PointFromString(frameDict["offset"].asString());
Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());
// create frame
spriteFrame = new SpriteFrame();
spriteFrame->initWithTexture(pobTexture,
spriteFrame->initWithTexture(texture,
frame,
rotated,
offset,
@ -167,31 +162,28 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
else if (format == 3)
{
// get values
Size spriteSize = SizeFromString(frameDict->valueForKey("spriteSize")->getCString());
Point spriteOffset = PointFromString(frameDict->valueForKey("spriteOffset")->getCString());
Size spriteSourceSize = SizeFromString(frameDict->valueForKey("spriteSourceSize")->getCString());
Rect textureRect = RectFromString(frameDict->valueForKey("textureRect")->getCString());
bool textureRotated = frameDict->valueForKey("textureRotated")->boolValue();
Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
Point spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
Rect textureRect = RectFromString(frameDict["textureRect"].asString());
bool textureRotated = frameDict["textureRotated"].asBool();
// get aliases
Array* aliases = (Array*) (frameDict->objectForKey("aliases"));
String * frameKey = new String(spriteFrameName);
ValueVector& aliases = frameDict["aliases"].asValueVector();
Object* pObj = NULL;
CCARRAY_FOREACH(aliases, pObj)
{
std::string oneAlias = static_cast<String*>(pObj)->getCString();
if (_spriteFramesAliases->objectForKey(oneAlias.c_str()))
std::for_each(aliases.cbegin(), aliases.cend(), [this, &spriteFrameName](const Value& value){
std::string oneAlias = value.asString();
if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
{
CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
}
_spriteFramesAliases->setObject(frameKey, oneAlias.c_str());
}
frameKey->release();
_spriteFramesAliases[oneAlias] = Value(spriteFrameName);
});
// create frame
spriteFrame = new SpriteFrame();
spriteFrame->initWithTexture(pobTexture,
spriteFrame->initWithTexture(texture,
Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
textureRotated,
spriteOffset,
@ -199,7 +191,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
}
// add sprite frame
_spriteFrames->setObject(spriteFrame, spriteFrameName);
_spriteFrames.insert(spriteFrameName, spriteFrame);
spriteFrame->release();
}
}
@ -207,10 +199,9 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex
void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist);
Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
addSpriteFramesWithDictionary(dict, pobTexture);
dict->release();
}
void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName)
@ -235,18 +226,18 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist)
if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end())
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist);
Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
string texturePath("");
Dictionary* metadataDict = static_cast<Dictionary*>( dict->objectForKey("metadata") );
if (metadataDict)
ValueMap& metadataDict = dict["metadata"].asValueMap();
if (!metadataDict.empty())
{
// try to read texture file name from meta data
texturePath = metadataDict->valueForKey("textureFileName")->getCString();
texturePath = metadataDict["textureFileName"].asString();
}
if (! texturePath.empty())
if (!texturePath.empty())
{
// build texture path relative to plist file
texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath.c_str(), pszPlist);
@ -277,37 +268,39 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist)
{
CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
}
dict->release();
}
}
void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const std::string& pszFrameName)
void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName)
{
_spriteFrames->setObject(pobFrame, pszFrameName);
_spriteFrames.insert(frameName, frame);
}
void SpriteFrameCache::removeSpriteFrames(void)
void SpriteFrameCache::removeSpriteFrames()
{
_spriteFrames->removeAllObjects();
_spriteFramesAliases->removeAllObjects();
_spriteFrames.clear();
_spriteFramesAliases.clear();
_loadedFileNames->clear();
}
void SpriteFrameCache::removeUnusedSpriteFrames(void)
void SpriteFrameCache::removeUnusedSpriteFrames()
{
bool bRemoved = false;
DictElement* element = NULL;
CCDICT_FOREACH(_spriteFrames, element)
std::vector<std::string> toRemoveFrames;
for (auto iter = _spriteFrames.begin(); iter != _spriteFrames.end(); ++iter)
{
SpriteFrame* spriteFrame = static_cast<SpriteFrame*>(element->getObject());
SpriteFrame* spriteFrame = iter->second;
if( spriteFrame->retainCount() == 1 )
{
CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", element->getStrKey());
_spriteFrames->removeObjectForElememt(element);
toRemoveFrames.push_back(iter->first);
CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter->first.c_str());
bRemoved = true;
}
}
_spriteFrames.remove(toRemoveFrames);
// XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
if( bRemoved )
{
@ -323,16 +316,16 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
return;
// Is this an alias ?
String* key = (String*)_spriteFramesAliases->objectForKey(name);
std::string key = _spriteFramesAliases[name].asString();
if (key)
if (!key.empty())
{
_spriteFrames->removeObjectForKey(key->getCString());
_spriteFramesAliases->removeObjectForKey(key->getCString());
_spriteFrames.remove(key);
_spriteFramesAliases.erase(key);
}
else
{
_spriteFrames->removeObjectForKey(name);
_spriteFrames.remove(name);
}
// XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
@ -342,13 +335,13 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist)
{
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
if (dict == nullptr)
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
if (dict.empty())
{
CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str());
return;
}
removeSpriteFramesFromDictionary((Dictionary*)dict);
removeSpriteFramesFromDictionary(dict);
// remove it from the cache
set<string>::iterator ret = _loadedFileNames->find(plist);
@ -356,55 +349,52 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist)
{
_loadedFileNames->erase(ret);
}
dict->release();
}
void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary)
void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueMap& dictionary)
{
Dictionary* framesDict = static_cast<Dictionary*>(dictionary->objectForKey("frames"));
Array* keysToRemove = Array::create();
ValueMap framesDict = dictionary["frames"].asValueMap();
std::vector<std::string> keysToRemove;
DictElement* element = NULL;
CCDICT_FOREACH(framesDict, element)
for (auto iter = framesDict.cbegin(); iter != framesDict.cend(); ++iter)
{
if (_spriteFrames->objectForKey(element->getStrKey()))
if (_spriteFrames.at(iter->first))
{
keysToRemove->addObject(String::create(element->getStrKey()));
keysToRemove.push_back(iter->first);
}
}
_spriteFrames->removeObjectsForKeys(keysToRemove);
_spriteFrames.remove(keysToRemove);
}
void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture)
{
Array* keysToRemove = Array::create();
std::vector<std::string> keysToRemove;
DictElement* element = NULL;
CCDICT_FOREACH(_spriteFrames, element)
for (auto iter = _spriteFrames.cbegin(); iter != _spriteFrames.cend(); ++iter)
{
string key = element->getStrKey();
SpriteFrame* frame = static_cast<SpriteFrame*>(_spriteFrames->objectForKey(key.c_str()));
std::string key = iter->first;
SpriteFrame* frame = _spriteFrames.at(key);
if (frame && (frame->getTexture() == texture))
{
keysToRemove->addObject(String::create(element->getStrKey()));
keysToRemove.push_back(key);
}
}
_spriteFrames->removeObjectsForKeys(keysToRemove);
_spriteFrames.remove(keysToRemove);
}
SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name)
{
SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(name);
SpriteFrame* frame = _spriteFrames.at(name);
if (!frame)
{
// try alias dictionary
String *key = (String*)_spriteFramesAliases->objectForKey(name);
if (key)
std::string key = _spriteFramesAliases[name].asString();
if (!key.empty())
{
frame = (SpriteFrame*)_spriteFrames->objectForKey(key->getCString());
if (! frame)
frame = _spriteFrames.at(key);
if (!frame)
{
CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str());
}
@ -414,3 +404,4 @@ SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name)
}
NS_CC_END

View File

@ -37,13 +37,13 @@ THE SOFTWARE.
#include "CCSpriteFrame.h"
#include "CCTexture2D.h"
#include "CCObject.h"
#include "CCValue.h"
#include "CCMap.h"
#include <set>
#include <string>
NS_CC_BEGIN
class Dictionary;
class Array;
class Sprite;
/**
@ -72,7 +72,7 @@ public:
protected:
// MARMALADE: Made this protected not private, as deriving from this class is pretty useful
SpriteFrameCache() : _spriteFrames(NULL), _spriteFramesAliases(NULL){}
SpriteFrameCache(){}
public:
/**
@ -115,13 +115,13 @@ public:
* In the medium term: it will allocate more resources.
* In the long term: it will be the same.
*/
void removeSpriteFrames(void);
void removeSpriteFrames();
/** Removes unused sprite frames.
* Sprite Frames that have a retain count of 1 will be deleted.
* It is convenient to call this method after when starting a new Scene.
*/
void removeUnusedSpriteFrames(void);
void removeUnusedSpriteFrames();
/** Deletes an sprite frame from the sprite frame cache. */
void removeSpriteFrameByName(const std::string& name);
@ -153,16 +153,16 @@ public:
private:
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/
void addSpriteFramesWithDictionary(Dictionary* dictionary, Texture2D *texture);
void addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D *texture);
/** Removes multiple Sprite Frames from Dictionary.
* @since v0.99.5
*/
void removeSpriteFramesFromDictionary(Dictionary* dictionary);
void removeSpriteFramesFromDictionary(ValueMap& dictionary);
protected:
Dictionary* _spriteFrames;
Dictionary* _spriteFramesAliases;
Map<std::string, SpriteFrame*> _spriteFrames;
ValueMap _spriteFramesAliases;
std::set<std::string>* _loadedFileNames;
};

View File

@ -70,7 +70,7 @@ bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *la
_minGID = layerInfo->_minGID;
_maxGID = layerInfo->_maxGID;
_opacity = layerInfo->_opacity;
setProperties(Dictionary::createWithDictionary(layerInfo->getProperties()));
setProperties(layerInfo->getProperties());
_contentScaleFactor = Director::getInstance()->getContentScaleFactor();
// tilesetInfo
@ -112,14 +112,12 @@ TMXLayer::TMXLayer()
,_tiles(NULL)
,_tileSet(NULL)
,_layerOrientation(TMXOrientationOrtho)
,_properties(NULL)
{}
TMXLayer::~TMXLayer()
{
CC_SAFE_RELEASE(_tileSet);
CC_SAFE_RELEASE(_reusedTile);
CC_SAFE_RELEASE(_properties);
if (_atlasIndexArray)
{
@ -193,28 +191,28 @@ void TMXLayer::setupTiles()
}
// TMXLayer - Properties
String* TMXLayer::getProperty(const char *propertyName) const
Value TMXLayer::getProperty(const std::string& propertyName) const
{
return static_cast<String*>(_properties->objectForKey(propertyName));
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
void TMXLayer::parseInternalProperties()
{
// if cc_vertex=automatic, then tiles will be rendered using vertexz
String *vertexz = getProperty("cc_vertexz");
if (vertexz)
auto vertexz = getProperty("cc_vertexz");
if (!vertexz.isNull())
{
std::string vertexZStr = vertexz.asString();
// If "automatic" is on, then parse the "cc_alpha_func" too
if (vertexz->_string == "automatic")
if (vertexZStr == "automatic")
{
_useAutomaticVertexZ = true;
String *alphaFuncVal = getProperty("cc_alpha_func");
float alphaFuncValue = 0.0f;
if (alphaFuncVal != NULL)
{
alphaFuncValue = alphaFuncVal->floatValue();
}
auto alphaFuncVal = getProperty("cc_alpha_func");
float alphaFuncValue = alphaFuncVal.asFloat();
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
GLint alphaValueLocation = glGetUniformLocation(getShaderProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
@ -228,7 +226,7 @@ void TMXLayer::parseInternalProperties()
}
else
{
_vertexZvalue = vertexz->intValue();
_vertexZvalue = vertexz.asInt();
}
}
}
@ -390,25 +388,23 @@ Sprite * TMXLayer::insertTileForGID(unsigned int gid, const Point& pos)
ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
// update possible children
if (_children && _children->count()>0)
{
Object* pObject = nullptr;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&indexForZ](Node* child){
Sprite* sp = static_cast<Sprite*>(child);
if (child)
{
Sprite* child = static_cast<Sprite*>(pObject);
if (child)
int ai = sp->getAtlasIndex();
if ( ai >= indexForZ )
{
unsigned int ai = child->getAtlasIndex();
if ( ai >= indexForZ )
{
child->setAtlasIndex(ai+1);
}
sp->setAtlasIndex(ai+1);
}
}
}
});
_tiles[z] = gid;
return tile;
}
Sprite * TMXLayer::updateTileForGID(unsigned int gid, const Point& pos)
{
Rect rect = _tileSet->rectForGID(gid);
@ -461,6 +457,7 @@ static inline int compareInts(const void * a, const void * b)
{
return ((*(int*)a) - (*(int*)b));
}
unsigned int TMXLayer::atlasIndexForExistantZ(unsigned int z)
{
int key=z;
@ -471,6 +468,7 @@ unsigned int TMXLayer::atlasIndexForExistantZ(unsigned int z)
int index = ((size_t)item - (size_t)_atlasIndexArray->arr) / sizeof(void*);
return index;
}
unsigned int TMXLayer::atlasIndexForNewZ(int z)
{
// XXX: This can be improved with a sort of binary search
@ -558,7 +556,7 @@ void TMXLayer::removeChild(Node* node, bool cleanup)
return;
}
CCASSERT(_children->containsObject(sprite), "Tile does not belong to TMXLayer");
CCASSERT(_children.contains(sprite), "Tile does not belong to TMXLayer");
unsigned int atlasIndex = sprite->getAtlasIndex();
unsigned int zz = (size_t)_atlasIndexArray->arr[atlasIndex];
@ -596,22 +594,17 @@ void TMXLayer::removeTileAt(const Point& pos)
_textureAtlas->removeQuadAtIndex(atlasIndex);
// update possible children
if (_children && _children->count()>0)
{
Object* pObject = nullptr;
CCARRAY_FOREACH(_children, pObject)
_children.forEach([&atlasIndex](Node* obj){
Sprite* child = static_cast<Sprite*>(obj);
if (child)
{
Sprite* child = static_cast<Sprite*>(pObject);
if (child)
unsigned int ai = child->getAtlasIndex();
if ( ai >= atlasIndex )
{
unsigned int ai = child->getAtlasIndex();
if ( ai >= atlasIndex )
{
child->setAtlasIndex(ai-1);
}
child->setAtlasIndex(ai-1);
}
}
}
});
}
}
}

View File

@ -137,8 +137,8 @@ public:
CC_DEPRECATED_ATTRIBUTE Point positionAt(const Point& tileCoordinate) { return getPositionAt(tileCoordinate); };
/** return the value for the specific property name */
String* getProperty(const char *propertyName) const;
CC_DEPRECATED_ATTRIBUTE String* propertyNamed(const char *propertyName) const { return getProperty(propertyName); };
Value getProperty(const std::string& propertyName) const;
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const std::string& propertyName) const { return getProperty(propertyName); };
/** Creates the tiles */
void setupTiles();
@ -174,10 +174,9 @@ public:
inline void setLayerOrientation(unsigned int orientation) { _layerOrientation = orientation; };
/** properties from the layer. They can be added using Tiled */
inline Dictionary* getProperties() const { return _properties; };
inline void setProperties(Dictionary* properties) {
CC_SAFE_RETAIN(properties);
CC_SAFE_RELEASE(_properties);
inline const ValueMap& getProperties() const { return _properties; };
inline ValueMap& getProperties() { return _properties; };
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
//
@ -244,7 +243,7 @@ protected:
/** Layer orientation, which is the same as the map orientation */
unsigned int _layerOrientation;
/** properties from the layer. They can be added using Tiled */
Dictionary* _properties;
ValueMap _properties;
};
// end of tilemap_parallax_nodes group

View File

@ -35,41 +35,37 @@ TMXObjectGroup::TMXObjectGroup()
: _groupName("")
, _positionOffset(Point::ZERO)
{
_objects = Array::create();
_objects->retain();
_properties = new Dictionary();
_properties->init();
}
TMXObjectGroup::~TMXObjectGroup()
{
CCLOGINFO("deallocing TMXObjectGroup: %p", this);
CC_SAFE_RELEASE(_objects);
CC_SAFE_RELEASE(_properties);
}
Dictionary* TMXObjectGroup::getObject(const char *objectName) const
ValueMap TMXObjectGroup::getObject(const std::string& objectName) const
{
if (_objects && _objects->count() > 0)
if (_objects.size() > 0)
{
Object* pObj = nullptr;
CCARRAY_FOREACH(_objects, pObj)
for (auto& v : _objects)
{
Dictionary* pDict = static_cast<Dictionary*>(pObj);
String *name = static_cast<String*>(pDict->objectForKey("name"));
if (name && name->_string == objectName)
ValueMap dict = v.asValueMap();
if (dict["name"].asString() == objectName)
{
return pDict;
return dict;
}
}
}
// object not found
return NULL;
return ValueMap();
}
String* TMXObjectGroup::getProperty(const char* propertyName) const
Value TMXObjectGroup::getProperty(const std::string& propertyName) const
{
return static_cast<String*>(_properties->objectForKey(propertyName));
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
NS_CC_END

View File

@ -30,7 +30,7 @@ THE SOFTWARE.
#include "CCGeometry.h"
#include "CCString.h"
#include "CCArray.h"
#include "CCDictionary.h"
#include "CCValue.h"
NS_CC_BEGIN
@ -55,20 +55,20 @@ public:
*/
virtual ~TMXObjectGroup();
inline const char* getGroupName(){ return _groupName.c_str(); }
inline void setGroupName(const char *groupName){ _groupName = groupName; }
inline const std::string& getGroupName(){ return _groupName; }
inline void setGroupName(const std::string& groupName){ _groupName = groupName; }
/** return the value for the specific property name */
String* getProperty(const char* propertyName) const;
Value getProperty(const std::string& propertyName) const;
CC_DEPRECATED_ATTRIBUTE String *propertyNamed(const char* propertyName) const { return getProperty(propertyName); };
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const std::string& propertyName) const { return getProperty(propertyName); };
/** return the dictionary for the specific object name.
It will return the 1st object found on the array for the given name.
*/
Dictionary* getObject(const char *objectName) const;
ValueMap getObject(const std::string& objectName) const;
CC_DEPRECATED_ATTRIBUTE Dictionary* objectNamed(const char *objectName) const { return getObject(objectName); };
CC_DEPRECATED_ATTRIBUTE ValueMap objectNamed(const std::string& objectName) const { return getObject(objectName); };
/** Gets the offset position of child objects */
inline const Point& getPositionOffset() const { return _positionOffset; };
@ -77,22 +77,20 @@ public:
inline void setPositionOffset(const Point& offset) { _positionOffset = offset; };
/** Gets the list of properties stored in a dictionary */
inline Dictionary* getProperties() const { return _properties; };
inline const ValueMap& getProperties() const { return _properties; };
inline ValueMap& getProperties() { return _properties; };
/** Sets the list of properties */
inline void setProperties(Dictionary* properties) {
CC_SAFE_RETAIN(properties);
CC_SAFE_RELEASE(_properties);
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
/** Gets the array of the objects */
inline Array* getObjects() const { return _objects; };
inline const ValueVector& getObjects() const { return _objects; };
inline ValueVector& getObjects() { return _objects; };
/** Sets the array of the objects */
inline void setObjects(Array* objects) {
CC_SAFE_RETAIN(objects);
CC_SAFE_RELEASE(_objects);
inline void setObjects(const ValueVector& objects) {
_objects = objects;
};
@ -102,9 +100,9 @@ protected:
/** offset position of child objects */
Point _positionOffset;
/** list of properties stored in a dictionary */
Dictionary* _properties;
ValueMap _properties;
/** array of the objects */
Array* _objects;
ValueVector _objects;
};
// end of tilemap_parallax_nodes group

View File

@ -42,7 +42,7 @@ TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile)
return ret;
}
CC_SAFE_DELETE(ret);
return NULL;
return nullptr;
}
TMXTiledMap* TMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath)
@ -54,7 +54,7 @@ TMXTiledMap* TMXTiledMap::createWithXML(const std::string& tmxString, const std:
return ret;
}
CC_SAFE_DELETE(ret);
return NULL;
return nullptr;
}
bool TMXTiledMap::initWithTMXFile(const std::string& tmxFile)
@ -69,7 +69,7 @@ bool TMXTiledMap::initWithTMXFile(const std::string& tmxFile)
{
return false;
}
CCASSERT( mapInfo->getTilesets()->count() != 0, "TMXTiledMap: Map not found. Please check the filename.");
CCASSERT( !mapInfo->getTilesets().empty(), "TMXTiledMap: Map not found. Please check the filename.");
buildWithMapInfo(mapInfo);
return true;
@ -81,7 +81,7 @@ bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& r
TMXMapInfo *mapInfo = TMXMapInfo::createWithXML(tmxString, resourcePath);
CCASSERT( mapInfo->getTilesets()->count() != 0, "TMXTiledMap: Map not found. Please check the filename.");
CCASSERT( !mapInfo->getTilesets().empty(), "TMXTiledMap: Map not found. Please check the filename.");
buildWithMapInfo(mapInfo);
return true;
@ -90,16 +90,11 @@ bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& r
TMXTiledMap::TMXTiledMap()
:_mapSize(Size::ZERO)
,_tileSize(Size::ZERO)
,_objectGroups(NULL)
,_properties(NULL)
,_tileProperties(NULL)
{
}
TMXTiledMap::~TMXTiledMap()
{
CC_SAFE_RELEASE(_properties);
CC_SAFE_RELEASE(_objectGroups);
CC_SAFE_RELEASE(_tileProperties);
}
// private
@ -118,14 +113,13 @@ TMXLayer * TMXTiledMap::parseLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
TMXTilesetInfo * TMXTiledMap::tilesetForLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
Size size = layerInfo->_layerSize;
Array* tilesets = mapInfo->getTilesets();
if (tilesets && tilesets->count()>0)
auto& tilesets = mapInfo->getTilesets();
if (tilesets.size()>0)
{
TMXTilesetInfo* tileset = NULL;
Object* pObj = NULL;
CCARRAY_FOREACH_REVERSE(tilesets, pObj)
TMXTilesetInfo* tileset = nullptr;
for (auto iter = tilesets.crbegin(); iter != tilesets.crend(); ++iter)
{
tileset = static_cast<TMXTilesetInfo*>(pObj);
tileset = *iter;
if (tileset)
{
for( unsigned int y=0; y < size.height; y++ )
@ -157,7 +151,7 @@ TMXTilesetInfo * TMXTiledMap::tilesetForLayer(TMXLayerInfo *layerInfo, TMXMapInf
// If all the tiles are 0, return empty tileset
CCLOG("cocos2d: Warning: TMX Layer '%s' has no tiles", layerInfo->_name.c_str());
return NULL;
return nullptr;
}
void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
@ -166,54 +160,40 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
_tileSize = mapInfo->getTileSize();
_mapOrientation = mapInfo->getOrientation();
CC_SAFE_RELEASE(_objectGroups);
_objectGroups = mapInfo->getObjectGroups();
CC_SAFE_RETAIN(_objectGroups);
CC_SAFE_RELEASE(_properties);
_properties = mapInfo->getProperties();
CC_SAFE_RETAIN(_properties);
CC_SAFE_RELEASE(_tileProperties);
_tileProperties = mapInfo->getTileProperties();
CC_SAFE_RETAIN(_tileProperties);
int idx=0;
Array* layers = mapInfo->getLayers();
if (layers && layers->count()>0)
{
TMXLayerInfo* layerInfo = NULL;
Object* pObj = NULL;
CCARRAY_FOREACH(layers, pObj)
mapInfo->getLayers().forEach([&idx, this, &mapInfo](TMXLayerInfo* layerInfo){
if (layerInfo && layerInfo->_visible)
{
layerInfo = static_cast<TMXLayerInfo*>(pObj);
if (layerInfo && layerInfo->_visible)
{
TMXLayer *child = parseLayer(layerInfo, mapInfo);
addChild((Node*)child, idx, idx);
// update content size with the max size
const Size& childSize = child->getContentSize();
Size currentSize = this->getContentSize();
currentSize.width = std::max( currentSize.width, childSize.width );
currentSize.height = std::max( currentSize.height, childSize.height );
this->setContentSize(currentSize);
idx++;
}
TMXLayer *child = parseLayer(layerInfo, mapInfo);
addChild((Node*)child, idx, idx);
// update content size with the max size
const Size& childSize = child->getContentSize();
Size currentSize = this->getContentSize();
currentSize.width = std::max( currentSize.width, childSize.width );
currentSize.height = std::max( currentSize.height, childSize.height );
this->setContentSize(currentSize);
idx++;
}
}
});
}
// public
TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const
{
CCASSERT(layerName.size() > 0, "Invalid layer name!");
Object* pObj = NULL;
CCARRAY_FOREACH(_children, pObj)
for (auto& child : _children)
{
TMXLayer* layer = dynamic_cast<TMXLayer*>(pObj);
TMXLayer* layer = dynamic_cast<TMXLayer*>(child);
if(layer)
{
if(layerName.compare( layer->getLayerName()) == 0)
@ -224,20 +204,19 @@ TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const
}
// layer not found
return NULL;
return nullptr;
}
TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const
{
CCASSERT(groupName.size() > 0, "Invalid group name!");
if (_objectGroups && _objectGroups->count()>0)
if (_objectGroups.size()>0)
{
TMXObjectGroup* objectGroup = NULL;
Object* pObj = NULL;
CCARRAY_FOREACH(_objectGroups, pObj)
TMXObjectGroup* objectGroup = nullptr;
for (auto iter = _objectGroups.cbegin(); iter != _objectGroups.cend(); ++iter)
{
objectGroup = static_cast<TMXObjectGroup*>(pObj);
objectGroup = *iter;
if (objectGroup && objectGroup->getGroupName() == groupName)
{
return objectGroup;
@ -246,17 +225,23 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const
}
// objectGroup not found
return NULL;
return nullptr;
}
String* TMXTiledMap::getProperty(const std::string& propertyName) const
Value TMXTiledMap::getProperty(const std::string& propertyName) const
{
return static_cast<String*>(_properties->objectForKey(propertyName));
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
Dictionary* TMXTiledMap::getPropertiesForGID(int GID) const
Value TMXTiledMap::getPropertiesForGID(int GID) const
{
return static_cast<Dictionary*>(_tileProperties->objectForKey(GID));
if (_tileProperties.find(GID) != _tileProperties.end())
return _tileProperties.at(GID);
return Value();
}

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "CCNode.h"
#include "CCTMXObjectGroup.h"
#include "CCValue.h"
NS_CC_BEGIN
@ -132,16 +133,16 @@ public:
CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const char *groupName) const { return getObjectGroup(groupName); };
/** return the value for the specific property name */
String *getProperty(const std::string& propertyName) const;
Value getProperty(const std::string& propertyName) const;
/**
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE String *propertyNamed(const char *propertyName) const { return getProperty(propertyName); };
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const char *propertyName) const { return getProperty(propertyName); };
/** return properties dictionary for tile GID */
Dictionary* getPropertiesForGID(int GID) const;
CC_DEPRECATED_ATTRIBUTE Dictionary* propertiesForGID(int GID) const { return getPropertiesForGID(GID); };
Value getPropertiesForGID(int GID) const;
CC_DEPRECATED_ATTRIBUTE Value propertiesForGID(int GID) const { return getPropertiesForGID(GID); };
/** the map's size property measured in tiles */
inline const Size& getMapSize() const { return _mapSize; };
@ -156,18 +157,15 @@ public:
inline void setMapOrientation(int mapOrientation) { _mapOrientation = mapOrientation; };
/** object groups */
inline Array* getObjectGroups() const { return _objectGroups; };
inline void setObjectGroups(Array* groups) {
CC_SAFE_RETAIN(groups);
CC_SAFE_RELEASE(_objectGroups);
inline const Vector<TMXObjectGroup*>& getObjectGroups() const { return _objectGroups; };
inline Vector<TMXObjectGroup*>& getObjectGroups() { return _objectGroups; };
inline void setObjectGroups(const Vector<TMXObjectGroup*>& groups) {
_objectGroups = groups;
};
/** properties */
inline Dictionary* getProperties() const { return _properties; };
inline void setProperties(Dictionary* properties) {
CC_SAFE_RETAIN(properties);
CC_SAFE_RELEASE(_properties);
inline ValueMap& getProperties() { return _properties; };
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
@ -199,12 +197,12 @@ protected:
/** map orientation */
int _mapOrientation;
/** object groups */
Array* _objectGroups;
Vector<TMXObjectGroup*> _objectGroups;
/** properties */
Dictionary* _properties;
ValueMap _properties;
//! tile properties
Dictionary* _tileProperties;
IntValueMap _tileProperties;
private:
CC_DISALLOW_COPY_AND_ASSIGN(TMXTiledMap);

View File

@ -38,47 +38,33 @@ using namespace std;
NS_CC_BEGIN
static const char* valueForKey(const char *key, std::unordered_map<std::string, std::string>* dict)
{
if (dict)
{
std::unordered_map<std::string, std::string>::iterator it = dict->find(key);
return it!=dict->end() ? it->second.c_str() : "";
}
return "";
}
// implementation TMXLayerInfo
TMXLayerInfo::TMXLayerInfo()
: _name("")
, _tiles(NULL)
, _tiles(nullptr)
, _ownTiles(true)
, _minGID(100000)
, _maxGID(0)
, _offset(Point::ZERO)
{
_properties = new Dictionary();
_properties->init();
}
TMXLayerInfo::~TMXLayerInfo()
{
CCLOGINFO("deallocing TMXLayerInfo: %p", this);
CC_SAFE_RELEASE(_properties);
if( _ownTiles && _tiles )
{
free(_tiles);
_tiles = NULL;
_tiles = nullptr;
}
}
Dictionary * TMXLayerInfo::getProperties()
ValueMap TMXLayerInfo::getProperties()
{
return _properties;
}
void TMXLayerInfo::setProperties(Dictionary* var)
void TMXLayerInfo::setProperties(ValueMap var)
{
CC_SAFE_RETAIN(var);
CC_SAFE_RELEASE(_properties);
_properties = var;
}
@ -121,7 +107,7 @@ TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile)
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
return nullptr;
}
TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath)
@ -133,17 +119,11 @@ TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
return nullptr;
}
void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath)
{
_tilesets = Array::create();
_tilesets->retain();
_layers = Array::create();
_layers->retain();
if (tmxFileName.size() > 0)
{
_TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName);
@ -154,13 +134,7 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string&
_resources = resourcePath;
}
_objectGroups = Array::createWithCapacity(4);
_objectGroups->retain();
_properties = new Dictionary();
_properties->init();
_tileProperties = new Dictionary();
_tileProperties->init();
_objectGroups.reserve(4);
// tmp vars
_currentString = "";
@ -184,13 +158,8 @@ bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile)
TMXMapInfo::TMXMapInfo()
: _mapSize(Size::ZERO)
, _tileSize(Size::ZERO)
, _layers(NULL)
, _tilesets(NULL)
, _objectGroups(NULL)
, _layerAttribs(0)
, _storingCharacters(false)
, _properties(NULL)
, _tileProperties(NULL)
, _currentFirstGID(0)
{
}
@ -198,16 +167,11 @@ TMXMapInfo::TMXMapInfo()
TMXMapInfo::~TMXMapInfo()
{
CCLOGINFO("deallocing TMXMapInfo: %p", this);
CC_SAFE_RELEASE(_tilesets);
CC_SAFE_RELEASE(_layers);
CC_SAFE_RELEASE(_properties);
CC_SAFE_RELEASE(_tileProperties);
CC_SAFE_RELEASE(_objectGroups);
}
bool TMXMapInfo::parseXMLString(const std::string& xmlString)
{
int len = xmlString.size();
size_t len = xmlString.size();
if (len <= 0)
return false;
@ -244,24 +208,24 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
CC_UNUSED_PARAM(ctx);
TMXMapInfo *pTMXMapInfo = this;
std::string elementName = (char*)name;
std::unordered_map<std::string, std::string> *attributeDict = new std::unordered_map<std::string, std::string>();
ValueMap attributeDict;
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));
attributeDict.insert(std::make_pair(key, Value(value)));
}
}
if (elementName == "map")
{
std::string version = valueForKey("version", attributeDict);
std::string version = attributeDict["version"].asString();
if ( version != "1.0")
{
CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str());
}
std::string orientationStr = valueForKey("orientation", attributeDict);
std::string orientationStr = attributeDict["orientation"].asString();
if (orientationStr == "orthogonal")
pTMXMapInfo->setOrientation(TMXOrientationOrtho);
else if (orientationStr == "isometric")
@ -272,12 +236,12 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", pTMXMapInfo->getOrientation());
Size s;
s.width = (float)atof(valueForKey("width", attributeDict));
s.height = (float)atof(valueForKey("height", attributeDict));
s.width = attributeDict["width"].asFloat();
s.height = attributeDict["height"].asFloat();
pTMXMapInfo->setMapSize(s);
s.width = (float)atof(valueForKey("tilewidth", attributeDict));
s.height = (float)atof(valueForKey("tileheight", attributeDict));
s.width = attributeDict["tilewidth"].asFloat();
s.height = attributeDict["tileheight"].asFloat();
pTMXMapInfo->setTileSize(s);
// The parent element is now "map"
@ -286,7 +250,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
else if (elementName == "tileset")
{
// If this is an external tileset then start parsing that
std::string externalTilesetFilename = valueForKey("source", attributeDict);
std::string externalTilesetFilename = attributeDict["source"].asString();
if (externalTilesetFilename != "")
{
// Tileset file will be relative to the map file. So we need to convert it to an absolute path
@ -301,31 +265,31 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
externalTilesetFilename = FileUtils::getInstance()->fullPathForFilename(externalTilesetFilename.c_str());
_currentFirstGID = (unsigned int)atoi(valueForKey("firstgid", attributeDict));
_currentFirstGID = (unsigned int)attributeDict["firstgid"].asInt();
pTMXMapInfo->parseXMLFile(externalTilesetFilename.c_str());
}
else
{
TMXTilesetInfo *tileset = new TMXTilesetInfo();
tileset->_name = valueForKey("name", attributeDict);
tileset->_name = attributeDict["name"].asString();
if (_currentFirstGID == 0)
{
tileset->_firstGid = (unsigned int)atoi(valueForKey("firstgid", attributeDict));
tileset->_firstGid = (unsigned int)attributeDict["firstgid"].asInt();
}
else
{
tileset->_firstGid = _currentFirstGID;
_currentFirstGID = 0;
}
tileset->_spacing = (unsigned int)atoi(valueForKey("spacing", attributeDict));
tileset->_margin = (unsigned int)atoi(valueForKey("margin", attributeDict));
tileset->_spacing = (unsigned int)attributeDict["spacing"].asInt();
tileset->_margin = (unsigned int)attributeDict["margin"].asInt();
Size s;
s.width = (float)atof(valueForKey("tilewidth", attributeDict));
s.height = (float)atof(valueForKey("tileheight", attributeDict));
s.width = attributeDict["tilewidth"].asFloat();
s.height = attributeDict["tileheight"].asFloat();
tileset->_tileSize = s;
pTMXMapInfo->getTilesets()->addObject(tileset);
pTMXMapInfo->getTilesets().pushBack(tileset);
tileset->release();
}
}
@ -333,9 +297,9 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
{
if (pTMXMapInfo->getParentElement() == TMXPropertyLayer)
{
TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject();
TMXLayerInfo* layer = pTMXMapInfo->getLayers().back();
Size layerSize = layer->_layerSize;
unsigned int gid = (unsigned int)atoi(valueForKey("gid", attributeDict));
unsigned int gid = (unsigned int)attributeDict["gid"].asInt();
int tilesAmount = layerSize.width*layerSize.height;
do
@ -367,44 +331,41 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
else
{
TMXTilesetInfo* info = (TMXTilesetInfo*)pTMXMapInfo->getTilesets()->getLastObject();
Dictionary *dict = new Dictionary();
dict->init();
pTMXMapInfo->setParentGID(info->_firstGid + atoi(valueForKey("id", attributeDict)));
pTMXMapInfo->getTileProperties()->setObject(dict, pTMXMapInfo->getParentGID());
CC_SAFE_RELEASE(dict);
TMXTilesetInfo* info = pTMXMapInfo->getTilesets().back();
pTMXMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt());
//FIXME:XXX Why insert an empty dict?
pTMXMapInfo->getTileProperties()[pTMXMapInfo->getParentGID()] = Value(ValueMap());
pTMXMapInfo->setParentElement(TMXPropertyTile);
}
}
else if (elementName == "layer")
{
TMXLayerInfo *layer = new TMXLayerInfo();
layer->_name = valueForKey("name", attributeDict);
layer->_name = attributeDict["name"].asString();
Size s;
s.width = (float)atof(valueForKey("width", attributeDict));
s.height = (float)atof(valueForKey("height", attributeDict));
s.width = attributeDict["width"].asFloat();
s.height = attributeDict["height"].asFloat();
layer->_layerSize = s;
std::string visible = valueForKey("visible", attributeDict);
layer->_visible = !(visible == "0");
layer->_visible = attributeDict["visible"].asBool();
std::string opacity = valueForKey("opacity", attributeDict);
if( opacity != "" )
Value& opacityValue = attributeDict["opacity"];
if( !opacityValue.isNull() )
{
layer->_opacity = (unsigned char)(255 * atof(opacity.c_str()));
layer->_opacity = (unsigned char)(255.0f * opacityValue.asFloat());
}
else
{
layer->_opacity = 255;
}
float x = (float)atof(valueForKey("x", attributeDict));
float y = (float)atof(valueForKey("y", attributeDict));
float x = attributeDict["x"].asFloat();
float y = attributeDict["y"].asFloat();
layer->_offset = Point(x,y);
pTMXMapInfo->getLayers()->addObject(layer);
pTMXMapInfo->getLayers().pushBack(layer);
layer->release();
// The parent element is now "layer"
@ -414,13 +375,13 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
else if (elementName == "objectgroup")
{
TMXObjectGroup *objectGroup = new TMXObjectGroup();
objectGroup->setGroupName(valueForKey("name", attributeDict));
objectGroup->setGroupName(attributeDict["name"].asString());
Point positionOffset;
positionOffset.x = (float)atof(valueForKey("x", attributeDict)) * pTMXMapInfo->getTileSize().width;
positionOffset.y = (float)atof(valueForKey("y", attributeDict)) * pTMXMapInfo->getTileSize().height;
positionOffset.x = attributeDict["x"].asFloat() * pTMXMapInfo->getTileSize().width;
positionOffset.y = attributeDict["y"].asFloat() * pTMXMapInfo->getTileSize().height;
objectGroup->setPositionOffset(positionOffset);
pTMXMapInfo->getObjectGroups()->addObject(objectGroup);
pTMXMapInfo->getObjectGroups().pushBack(objectGroup);
objectGroup->release();
// The parent element is now "objectgroup"
@ -429,10 +390,10 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
else if (elementName == "image")
{
TMXTilesetInfo* tileset = (TMXTilesetInfo*)pTMXMapInfo->getTilesets()->getLastObject();
TMXTilesetInfo* tileset = pTMXMapInfo->getTilesets().back();
// build full path
std::string imagename = valueForKey("source", attributeDict);
std::string imagename = attributeDict["source"].asString();
if (_TMXFileName.find_last_of("/") != string::npos)
{
@ -446,14 +407,14 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
else if (elementName == "data")
{
std::string encoding = valueForKey("encoding", attributeDict);
std::string compression = valueForKey("compression", attributeDict);
std::string encoding = attributeDict["encoding"].asString();
std::string compression = attributeDict["compression"].asString();
if (encoding == "")
{
pTMXMapInfo->setLayerAttribs(pTMXMapInfo->getLayerAttribs() | TMXLayerAttribNone);
TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject();
TMXLayerInfo* layer = pTMXMapInfo->getLayers().back();
Size layerSize = layer->_layerSize;
int tilesAmount = layerSize.width*layerSize.height;
@ -498,56 +459,36 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
else if (elementName == "object")
{
char buffer[32] = {0};
TMXObjectGroup* objectGroup = (TMXObjectGroup*)pTMXMapInfo->getObjectGroups()->getLastObject();
TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().back();
// The value for "type" was blank or not a valid class name
// Create an instance of TMXObjectInfo to store the object and its properties
Dictionary *dict = new Dictionary();
dict->init();
ValueMap dict;
// 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];
String* obj = new String(valueForKey(key, attributeDict));
if( obj )
{
obj->autorelease();
dict->setObject(obj, key);
}
Value value = attributeDict[key];
dict[key] = value;
}
// 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);
String* pStr = new String(buffer);
pStr->autorelease();
dict->setObject(pStr, "x");
}
int x = attributeDict["x"].asInt() + (int)objectGroup->getPositionOffset().x;
dict["x"] = Value(x);
// Y
value = valueForKey("y", attributeDict);
if (value) {
int y = atoi(value) + (int)objectGroup->getPositionOffset().y;
int y = attributeDict["y"].asInt() + (int)objectGroup->getPositionOffset().y;
// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
y = (int)(_mapSize.height * _tileSize.height) - y - atoi(valueForKey("height", attributeDict));
sprintf(buffer, "%d", y);
String* pStr = new String(buffer);
pStr->autorelease();
dict->setObject(pStr, "y");
}
// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
y = (int)(_mapSize.height * _tileSize.height) - y - attributeDict["height"].asInt();
dict["y"] = Value(y);
// Add the object to the objectGroup
objectGroup->getObjects()->addObject(dict);
dict->release();
objectGroup->getObjects().push_back(Value(dict));
// The parent element is now "object"
pTMXMapInfo->setParentElement(TMXPropertyObject);
@ -558,70 +499,61 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
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) );
attributeDict["name"].asString().c_str(), attributeDict["value"].asString().c_str() );
}
else if ( pTMXMapInfo->getParentElement() == TMXPropertyMap )
{
// The parent element is the map
String *value = new String(valueForKey("value", attributeDict));
std::string key = valueForKey("name", attributeDict);
pTMXMapInfo->getProperties()->setObject(value, key.c_str());
value->release();
}
Value value = attributeDict["value"];
std::string key = attributeDict["name"].asString();
pTMXMapInfo->getProperties().insert(std::make_pair(key, value));
}
else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer )
{
// The parent element is the last layer
TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject();
String *value = new String(valueForKey("value", attributeDict));
std::string key = valueForKey("name", attributeDict);
TMXLayerInfo* layer = pTMXMapInfo->getLayers().back();
Value value = attributeDict["value"];
std::string key = attributeDict["name"].asString();
// Add the property to the layer
layer->getProperties()->setObject(value, key.c_str());
value->release();
}
layer->getProperties().insert(std::make_pair(key, value));
}
else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup )
{
// The parent element is the last object group
TMXObjectGroup* objectGroup = (TMXObjectGroup*)pTMXMapInfo->getObjectGroups()->getLastObject();
String *value = new String(valueForKey("value", attributeDict));
const char* key = valueForKey("name", attributeDict);
objectGroup->getProperties()->setObject(value, key);
value->release();
}
TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().back();
Value value = attributeDict["value"];
std::string key = attributeDict["name"].asString();
objectGroup->getProperties().insert(std::make_pair(key, value));
}
else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject )
{
// The parent element is the last object
TMXObjectGroup* objectGroup = (TMXObjectGroup*)pTMXMapInfo->getObjectGroups()->getLastObject();
Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject();
TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().back();
ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
const char* propertyName = valueForKey("name", attributeDict);
String *propertyValue = new String(valueForKey("value", attributeDict));
dict->setObject(propertyValue, propertyName);
propertyValue->release();
}
std::string propertyName = attributeDict["name"].asString();
dict[propertyName] = attributeDict["value"];
}
else if ( pTMXMapInfo->getParentElement() == TMXPropertyTile )
{
Dictionary* dict = (Dictionary*)pTMXMapInfo->getTileProperties()->objectForKey(pTMXMapInfo->getParentGID());
IntValueMap& dict = pTMXMapInfo->getTileProperties().at(pTMXMapInfo->getParentGID()).asIntKeyMap();
const char* propertyName = valueForKey("name", attributeDict);
String *propertyValue = new String(valueForKey("value", attributeDict));
dict->setObject(propertyValue, propertyName);
propertyValue->release();
int propertyName = attributeDict["name"].asInt();
dict[propertyName] = attributeDict["value"];
}
}
else if (elementName == "polygon")
{
// find parent object's dict and add polygon-points to it
TMXObjectGroup* objectGroup = (TMXObjectGroup*)_objectGroups->getLastObject();
Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject();
TMXObjectGroup* objectGroup = _objectGroups.back();
ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
// get points value string
const char* value = valueForKey("points", attributeDict);
if(value)
std::string value = attributeDict["points"].asString();
if (!value.empty())
{
Array* pointsArray = Array::createWithCapacity(10);
ValueVector pointsArray;
pointsArray.reserve(10);
// parse points string into a space-separated set of points
stringstream pointsStream(value);
@ -631,50 +563,42 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
// parse each point combo into a comma-separated x,y point
stringstream pointStream(pointPair);
string xStr,yStr;
char buffer[32] = {0};
Dictionary* pointDict = new Dictionary;
pointDict->init();
ValueMap pointDict;
// set x
if(std::getline(pointStream, xStr, ','))
{
int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
sprintf(buffer, "%d", x);
String* pStr = new String(buffer);
pStr->autorelease();
pointDict->setObject(pStr, "x");
pointDict["x"] = Value(x);
}
// set y
if(std::getline(pointStream, yStr, ','))
{
int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
sprintf(buffer, "%d", y);
String* pStr = new String(buffer);
pStr->autorelease();
pointDict->setObject(pStr, "y");
pointDict["y"] = Value(y);
}
// add to points array
pointsArray->addObject(pointDict);
pointDict->release();
pointsArray.push_back(Value(pointDict));
}
dict->setObject(pointsArray, "points");
dict["points"] = Value(pointsArray);
}
}
else if (elementName == "polyline")
{
// find parent object's dict and add polyline-points to it
TMXObjectGroup* objectGroup = (TMXObjectGroup*)_objectGroups->getLastObject();
Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject();
TMXObjectGroup* objectGroup = _objectGroups.back();
ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
// get points value string
const char* value = valueForKey("points", attributeDict);
if(value)
std::string value = attributeDict["points"].asString();
if (!value.empty())
{
Array* pointsArray = Array::createWithCapacity(10);
ValueVector pointsArray;
pointsArray.reserve(10);
// parse points string into a space-separated set of points
stringstream pointsStream(value);
@ -684,45 +608,30 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
// parse each point combo into a comma-separated x,y point
stringstream pointStream(pointPair);
string xStr,yStr;
char buffer[32] = {0};
Dictionary* pointDict = new Dictionary;
pointDict->init();
ValueMap pointDict;
// set x
if(std::getline(pointStream, xStr, ','))
{
int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
sprintf(buffer, "%d", x);
String* pStr = new String(buffer);
pStr->autorelease();
pointDict->setObject(pStr, "x");
pointDict["x"] = Value(x);
}
// set y
if(std::getline(pointStream, yStr, ','))
{
int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
sprintf(buffer, "%d", y);
String* pStr = new String(buffer);
pStr->autorelease();
pointDict->setObject(pStr, "y");
pointDict["y"] = Value(y);
}
// add to points array
pointsArray->addObject(pointDict);
pointDict->release();
pointsArray.push_back(Value(pointDict));
}
dict->setObject(pointsArray, "polylinePoints");
dict["polylinePoints"] = Value(pointsArray);
}
}
if (attributeDict)
{
attributeDict->clear();
delete attributeDict;
}
}
void TMXMapInfo::endElement(void *ctx, const char *name)
@ -739,7 +648,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name)
{
pTMXMapInfo->setStoringCharacters(false);
TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject();
TMXLayerInfo* layer = pTMXMapInfo->getLayers().back();
std::string currentString = pTMXMapInfo->getCurrentString();
unsigned char *buffer;
@ -752,18 +661,16 @@ void TMXMapInfo::endElement(void *ctx, const char *name)
if( pTMXMapInfo->getLayerAttribs() & (TMXLayerAttribGzip | TMXLayerAttribZlib) )
{
unsigned char *deflated;
unsigned char *deflated = nullptr;
Size s = layer->_layerSize;
// int sizeHint = s.width * s.height * sizeof(uint32_t);
int sizeHint = (int)(s.width * s.height * sizeof(unsigned int));
int inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
int CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
CCASSERT(inflatedLen == sizeHint, "");
inflatedLen = (size_t)&inflatedLen; // XXX: to avoid warnings in compiler
free(buffer);
buffer = NULL;
buffer = nullptr;
if( ! deflated )
{
@ -782,7 +689,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name)
}
else if (pTMXMapInfo->getLayerAttribs() & TMXLayerAttribNone)
{
TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject();
TMXLayerInfo* layer = pTMXMapInfo->getLayers().back();
Size layerSize = layer->_layerSize;
int tilesAmount = layerSize.width * layerSize.height;

View File

@ -29,15 +29,17 @@ THE SOFTWARE.
#define __CC_TM_XML_PARSER__
#include "CCArray.h"
#include "CCDictionary.h"
#include "CCGeometry.h"
#include "platform/CCSAXParser.h"
#include "CCVector.h"
#include "CCValue.h"
#include <string>
NS_CC_BEGIN
class TMXLayerInfo;
class TMXObjectGroup;
class TMXTilesetInfo;
/** @file
* Internal TMX parser
@ -99,10 +101,10 @@ public:
*/
virtual ~TMXLayerInfo();
void setProperties(Dictionary *properties);
Dictionary* getProperties();
void setProperties(ValueMap properties);
ValueMap getProperties();
Dictionary *_properties;
ValueMap _properties;
std::string _name;
Size _layerSize;
unsigned int *_tiles;
@ -193,10 +195,8 @@ public:
/* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */
bool parseXMLString(const std::string& xmlString);
Dictionary* getTileProperties() { return _tileProperties; };
void setTileProperties(Dictionary* tileProperties) {
CC_SAFE_RETAIN(tileProperties);
CC_SAFE_RELEASE(_tileProperties);
IntValueMap& getTileProperties() { return _tileProperties; };
void setTileProperties(const IntValueMap& tileProperties) {
_tileProperties = tileProperties;
};
@ -213,26 +213,23 @@ public:
inline void setTileSize(const Size& tileSize) { _tileSize = tileSize; };
/// Layers
inline Array* getLayers() const { return _layers; };
inline void setLayers(Array* layers) {
CC_SAFE_RETAIN(layers);
CC_SAFE_RELEASE(_layers);
inline const Vector<TMXLayerInfo*>& getLayers() const { return _layers; };
inline Vector<TMXLayerInfo*>& getLayers() { return _layers; };
inline void setLayers(const Vector<TMXLayerInfo*>& layers) {
_layers = layers;
};
/// tilesets
inline Array* getTilesets() const { return _tilesets; };
inline void setTilesets(Array* tilesets) {
CC_SAFE_RETAIN(tilesets);
CC_SAFE_RELEASE(_tilesets);
inline const Vector<TMXTilesetInfo*>& getTilesets() const { return _tilesets; };
inline Vector<TMXTilesetInfo*>& getTilesets() { return _tilesets; };
inline void setTilesets(const Vector<TMXTilesetInfo*>& tilesets) {
_tilesets = tilesets;
};
/// ObjectGroups
inline Array* getObjectGroups() const { return _objectGroups; };
inline void setObjectGroups(Array* groups) {
CC_SAFE_RETAIN(groups);
CC_SAFE_RELEASE(_objectGroups);
inline const Vector<TMXObjectGroup*>& getObjectGroups() const { return _objectGroups; };
inline Vector<TMXObjectGroup*>& getObjectGroups() { return _objectGroups; };
inline void setObjectGroups(const Vector<TMXObjectGroup*>& groups) {
_objectGroups = groups;
};
@ -254,10 +251,8 @@ public:
inline void setStoringCharacters(bool storingCharacters) { _storingCharacters = storingCharacters; };
/// properties
inline Dictionary* getProperties() const { return _properties; };
inline void setProperties(Dictionary* properties) {
CC_SAFE_RETAIN(properties);
CC_SAFE_RELEASE(_properties);
inline ValueMap getProperties() const { return _properties; };
inline void setProperties(ValueMap properties) {
_properties = properties;
};
@ -293,11 +288,11 @@ protected:
/// tiles width & height
Size _tileSize;
/// Layers
Array* _layers;
Vector<TMXLayerInfo*> _layers;
/// tilesets
Array* _tilesets;
Vector<TMXTilesetInfo*> _tilesets;
/// ObjectGroups
Array* _objectGroups;
Vector<TMXObjectGroup*> _objectGroups;
/// parent element
int _parentElement;
/// parent GID
@ -307,7 +302,7 @@ protected:
/// is storing characters?
bool _storingCharacters;
/// properties
Dictionary* _properties;
ValueMap _properties;
//! tmx filename
std::string _TMXFileName;
@ -316,7 +311,7 @@ protected:
//! current string
std::string _currentString;
//! tile properties
Dictionary* _tileProperties;
IntValueMap _tileProperties;
unsigned int _currentFirstGID;
};

View File

@ -338,7 +338,7 @@ void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index)
CCASSERT( _totalQuads <= _capacity, "invalid totalQuads");
// issue #575. index can be > totalQuads
unsigned int remaining = (_totalQuads-1) - index;
long remaining = (_totalQuads-1) - index;
// last object doesn't need to be moved
if( remaining > 0)

View File

@ -266,4 +266,9 @@ To enable set it to a value different than 0. Disabled by default.
#define CC_LUA_ENGINE_DEBUG 0
#endif
/** Use physics integration API */
#ifndef CC_USE_PHYSICS
#define CC_USE_PHYSICS
#endif
#endif // __CCCONFIG_H__

View File

@ -60,6 +60,8 @@ THE SOFTWARE.
#include "CCDictionary.h"
#include "CCObject.h"
#include "CCArray.h"
#include "CCVector.h"
#include "CCMap.h"
#include "CCGeometry.h"
#include "CCSet.h"
#include "CCAutoreleasePool.h"
@ -70,6 +72,7 @@ THE SOFTWARE.
#include "CCString.h"
#include "CCNS.h"
#include "CCData.h"
#include "CCValue.h"
// draw nodes
#include "CCDrawingPrimitives.h"

View File

@ -74,7 +74,7 @@
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
@ -121,7 +121,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
</PreBuildEvent>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>

View File

@ -23,9 +23,8 @@ THE SOFTWARE.
****************************************************************************/
#include "CCFileUtils.h"
#include "ccMacros.h"
#include "CCDirector.h"
#include "CCDictionary.h"
#include "CCString.h"
#include "CCSAXParser.h"
#include "tinyxml2.h"
#include "unzip.h"
@ -59,26 +58,23 @@ class DictMaker : public SAXDelegator
{
public:
SAXResult _resultType;
Array* _rootArray;
Dictionary *_rootDict;
Dictionary *_curDict;
std::stack<Dictionary*> _dictStack;
ValueMap _rootDict;
ValueVector _rootArray;
std::string _curKey; ///< parsed key
std::string _curValue; // parsed value
SAXState _state;
Array* _array;
std::stack<Array*> _arrayStack;
ValueMap* _curDict;
ValueVector* _curArray;
std::stack<ValueMap*> _dictStack;
std::stack<ValueVector*> _arrayStack;
std::stack<SAXState> _stateStack;
public:
DictMaker()
: _resultType(SAX_RESULT_NONE),
_rootArray(NULL),
_rootDict(NULL),
_curDict(NULL),
_state(SAX_NONE),
_array(NULL)
: _resultType(SAX_RESULT_NONE)
{
}
@ -86,50 +82,42 @@ public:
{
}
Dictionary* dictionaryWithContentsOfFile(const char *pFileName)
ValueMap dictionaryWithContentsOfFile(const char *pFileName)
{
_resultType = SAX_RESULT_DICT;
SAXParser parser;
if (false == parser.init("UTF-8"))
{
return NULL;
}
CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
parser.setDelegator(this);
parser.parse(pFileName);
return _rootDict;
return std::move(_rootDict);
}
Array* arrayWithContentsOfFile(const char* pFileName)
ValueVector arrayWithContentsOfFile(const char* pFileName)
{
_resultType = SAX_RESULT_ARRAY;
SAXParser parser;
if (false == parser.init("UTF-8"))
{
return NULL;
}
CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
parser.setDelegator(this);
parser.parse(pFileName);
return _array;
return std::move(_rootArray);
}
void startElement(void *ctx, const char *name, const char **atts)
{
CC_UNUSED_PARAM(ctx);
CC_UNUSED_PARAM(atts);
std::string sName((char*)name);
std::string sName(name);
if( sName == "dict" )
{
_curDict = new Dictionary();
if(_resultType == SAX_RESULT_DICT && _rootDict == NULL)
if(_resultType == SAX_RESULT_DICT && _rootDict.empty())
{
// Because it will call _curDict->release() later, so retain here.
_rootDict = _curDict;
_rootDict->retain();
_curDict = &_rootDict;
}
_state = SAX_DICT;
SAXState preState = SAX_NONE;
@ -140,19 +128,19 @@ public:
if (SAX_ARRAY == preState)
{
// add the dictionary into the array
_array->addObject(_curDict);
// add a new dictionary into the array
_curArray->push_back(Value(ValueMap()));
_curDict = &(_curArray->rbegin())->asValueMap();
}
else if (SAX_DICT == preState)
{
// add the dictionary into the pre dictionary
// add a new dictionary into the pre dictionary
CCASSERT(! _dictStack.empty(), "The state is wrong!");
Dictionary* pPreDict = _dictStack.top();
pPreDict->setObject(_curDict, _curKey.c_str());
ValueMap* preDict = _dictStack.top();
(*preDict)[_curKey] = Value(ValueMap());
_curDict = &(*preDict)[_curKey].asValueMap();
}
_curDict->release();
// record the dict state
_stateStack.push(_state);
_dictStack.push(_curDict);
@ -176,12 +164,10 @@ public:
else if (sName == "array")
{
_state = SAX_ARRAY;
_array = new Array();
_array->init();
if (_resultType == SAX_RESULT_ARRAY && _rootArray == NULL)
if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty())
{
_rootArray = _array;
_rootArray->retain();
_curArray = &_rootArray;
}
SAXState preState = SAX_NONE;
if (! _stateStack.empty())
@ -191,18 +177,19 @@ public:
if (preState == SAX_DICT)
{
_curDict->setObject(_array, _curKey.c_str());
(*_curDict)[_curKey] = Value(ValueVector());
_curArray = &(*_curDict)[_curKey].asValueVector();
}
else if (preState == SAX_ARRAY)
{
CCASSERT(! _arrayStack.empty(), "The state is wrong!");
Array* pPreArray = _arrayStack.top();
pPreArray->addObject(_array);
ValueVector* preArray = _arrayStack.top();
preArray->push_back(Value(ValueVector()));
_curArray = &(_curArray->rbegin())->asValueVector();
}
_array->release();
// record the array state
_stateStack.push(_state);
_arrayStack.push(_array);
_arrayStack.push(_curArray);
}
else
{
@ -230,49 +217,52 @@ public:
_arrayStack.pop();
if (! _arrayStack.empty())
{
_array = _arrayStack.top();
_curArray = _arrayStack.top();
}
}
else if (sName == "true")
{
String *str = new String("1");
if (SAX_ARRAY == curState)
{
_array->addObject(str);
_curArray->push_back(Value(true));
}
else if (SAX_DICT == curState)
{
_curDict->setObject(str, _curKey.c_str());
(*_curDict)[_curKey] = Value(true);
}
str->release();
}
else if (sName == "false")
{
String *str = new String("0");
if (SAX_ARRAY == curState)
{
_array->addObject(str);
_curArray->push_back(Value(false));
}
else if (SAX_DICT == curState)
{
_curDict->setObject(str, _curKey.c_str());
(*_curDict)[_curKey] = Value(false);
}
str->release();
}
else if (sName == "string" || sName == "integer" || sName == "real")
{
String* pStrValue = new String(_curValue);
if (SAX_ARRAY == curState)
{
_array->addObject(pStrValue);
if (sName == "string")
_curArray->push_back(Value(_curValue));
else if (sName == "integer")
_curArray->push_back(Value(atoi(_curValue.c_str())));
else
_curArray->push_back(Value(atof(_curValue.c_str())));
}
else if (SAX_DICT == curState)
{
_curDict->setObject(pStrValue, _curKey.c_str());
if (sName == "string")
(*_curDict)[_curKey] = Value(_curValue);
else if (sName == "integer")
(*_curDict)[_curKey] = Value(atoi(_curValue.c_str()));
else
(*_curDict)[_curKey] = Value(atof(_curValue.c_str()));
}
pStrValue->release();
_curValue.clear();
}
@ -288,12 +278,12 @@ public:
}
SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
String *pText = new String(std::string((char*)ch,0,len));
std::string text = std::string((char*)ch,0,len);
switch(_state)
{
case SAX_KEY:
_curKey = pText->getCString();
_curKey = text;
break;
case SAX_INT:
case SAX_REAL:
@ -304,49 +294,48 @@ public:
CCASSERT(!_curKey.empty(), "key not found : <integer/real>");
}
_curValue.append(pText->getCString());
_curValue.append(text);
}
break;
default:
break;
}
pText->release();
}
};
Dictionary* FileUtils::createDictionaryWithContentsOfFile(const std::string& filename)
ValueMap FileUtils::getValueMapFromFile(const std::string& filename)
{
std::string fullPath = fullPathForFilename(filename.c_str());
DictMaker tMaker;
return tMaker.dictionaryWithContentsOfFile(fullPath.c_str());
return std::move(tMaker.dictionaryWithContentsOfFile(fullPath.c_str()));
}
Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename)
ValueVector FileUtils::getValueVectorFromFile(const std::string& filename)
{
std::string fullPath = fullPathForFilename(filename.c_str());
DictMaker tMaker;
return tMaker.arrayWithContentsOfFile(fullPath.c_str());
return std::move(tMaker.arrayWithContentsOfFile(fullPath.c_str()));
}
/*
* forward statement
*/
static tinyxml2::XMLElement* generateElementForArray(cocos2d::Array *array, tinyxml2::XMLDocument *pDoc);
static tinyxml2::XMLElement* generateElementForDict(cocos2d::Dictionary *dict, tinyxml2::XMLDocument *pDoc);
static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *pDoc);
static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *pDoc);
/*
* Use tinyxml2 to write plist files
*/
bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath)
bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath)
{
//CCLOG("tinyxml2 Dictionary %d writeToFile %s", dict->_ID, fullPath.c_str());
tinyxml2::XMLDocument *pDoc = new tinyxml2::XMLDocument();
if (NULL == pDoc)
if (nullptr == pDoc)
return false;
tinyxml2::XMLDeclaration *pDeclaration = pDoc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
if (NULL == pDeclaration)
if (nullptr == pDeclaration)
{
delete pDoc;
return false;
@ -358,7 +347,7 @@ bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPa
tinyxml2::XMLElement *pRootEle = pDoc->NewElement("plist");
pRootEle->SetAttribute("version", "1.0");
if (NULL == pRootEle)
if (nullptr == pRootEle)
{
delete pDoc;
return false;
@ -366,7 +355,7 @@ bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPa
pDoc->LinkEndChild(pRootEle);
tinyxml2::XMLElement *innerDict = generateElementForDict(dict, pDoc);
if (NULL == innerDict )
if (nullptr == innerDict )
{
delete pDoc;
return false;
@ -382,46 +371,64 @@ bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPa
/*
* Generate tinyxml2::XMLElement for Object through a tinyxml2::XMLDocument
*/
static tinyxml2::XMLElement* generateElementForObject(cocos2d::Object *object, tinyxml2::XMLDocument *pDoc)
static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XMLDocument *pDoc)
{
// object is String
if (String *str = dynamic_cast<String *>(object))
if (value.getType() == Value::Type::STRING)
{
tinyxml2::XMLElement* node = pDoc->NewElement("string");
tinyxml2::XMLText* content = pDoc->NewText(str->getCString());
tinyxml2::XMLText* content = pDoc->NewText(value.asString().c_str());
node->LinkEndChild(content);
return node;
}
// object is integer
if (value.getType() == Value::Type::INTEGER)
{
tinyxml2::XMLElement* node = pDoc->NewElement("integer");
tinyxml2::XMLText* content = pDoc->NewText(value.asString().c_str());
node->LinkEndChild(content);
return node;
}
// object is real
if (value.getType() == Value::Type::FLOAT || value.getType() == Value::Type::DOUBLE)
{
tinyxml2::XMLElement* node = pDoc->NewElement("real");
tinyxml2::XMLText* content = pDoc->NewText(value.asString().c_str());
node->LinkEndChild(content);
return node;
}
//FIXME:XXX How to deal with Boolean ??
// object is Array
if (Array *array = dynamic_cast<Array *>(object))
return generateElementForArray(array, pDoc);
if (value.getType() == Value::Type::VECTOR)
return generateElementForArray(value.asValueVector(), pDoc);
// object is Dictionary
if (Dictionary *innerDict = dynamic_cast<Dictionary *>(object))
return generateElementForDict(innerDict, pDoc);
if (value.getType() == Value::Type::MAP)
return generateElementForDict(value.asValueMap(), pDoc);
CCLOG("This type cannot appear in property list");
return NULL;
return nullptr;
}
/*
* Generate tinyxml2::XMLElement for Dictionary through a tinyxml2::XMLDocument
*/
static tinyxml2::XMLElement* generateElementForDict(cocos2d::Dictionary *dict, tinyxml2::XMLDocument *pDoc)
static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *pDoc)
{
tinyxml2::XMLElement* rootNode = pDoc->NewElement("dict");
DictElement *dictElement = NULL;
CCDICT_FOREACH(dict, dictElement)
for (auto iter = dict.begin(); iter != dict.end(); ++iter)
{
tinyxml2::XMLElement* tmpNode = pDoc->NewElement("key");
rootNode->LinkEndChild(tmpNode);
tinyxml2::XMLText* content = pDoc->NewText(dictElement->getStrKey());
tinyxml2::XMLText* content = pDoc->NewText(iter->first.c_str());
tmpNode->LinkEndChild(content);
Object *object = dictElement->getObject();
tinyxml2::XMLElement *element = generateElementForObject(object, pDoc);
tinyxml2::XMLElement *element = generateElementForObject(iter->second, pDoc);
if (element)
rootNode->LinkEndChild(element);
}
@ -431,17 +438,16 @@ static tinyxml2::XMLElement* generateElementForDict(cocos2d::Dictionary *dict, t
/*
* Generate tinyxml2::XMLElement for Array through a tinyxml2::XMLDocument
*/
static tinyxml2::XMLElement* generateElementForArray(cocos2d::Array *array, tinyxml2::XMLDocument *pDoc)
static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *pDoc)
{
tinyxml2::XMLElement* rootNode = pDoc->NewElement("array");
Object *object = NULL;
CCARRAY_FOREACH(array, object)
{
tinyxml2::XMLElement *element = generateElementForObject(object, pDoc);
std::for_each(array.begin(), array.end(), [=](Value& value){
tinyxml2::XMLElement *element = generateElementForObject(value, pDoc);
if (element)
rootNode->LinkEndChild(element);
}
});
return rootNode;
}
@ -450,14 +456,14 @@ static tinyxml2::XMLElement* generateElementForArray(cocos2d::Array *array, tiny
NS_CC_BEGIN
/* The subclass FileUtilsApple should override these two method. */
Dictionary* FileUtils::createDictionaryWithContentsOfFile(const std::string& filename) {return NULL;}
bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return false;}
Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename) {return NULL;}
ValueMap FileUtils::getValueMapFromFile(const std::string& filename) {return ValueMap();}
ValueVector FileUtils::getValueVectorFromFile(const std::string& filename) {return ValueVector();}
bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath) {return false;}
#endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */
FileUtils* FileUtils::s_sharedFileUtils = NULL;
FileUtils* FileUtils::s_sharedFileUtils = nullptr;
void FileUtils::destroyInstance()
@ -466,13 +472,11 @@ void FileUtils::destroyInstance()
}
FileUtils::FileUtils()
: _filenameLookupDict(NULL)
{
}
FileUtils::~FileUtils()
{
CC_SAFE_RELEASE(_filenameLookupDict);
}
@ -490,8 +494,8 @@ void FileUtils::purgeCachedEntries()
unsigned char* FileUtils::getFileData(const char* filename, const char* mode, long *size)
{
unsigned char * buffer = NULL;
CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters.");
unsigned char * buffer = nullptr;
CCASSERT(filename != nullptr && size != nullptr && mode != nullptr, "Invalid parameters.");
*size = 0;
do
{
@ -520,8 +524,8 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, lo
unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, long *size)
{
unsigned char * buffer = NULL;
unzFile pFile = NULL;
unsigned char * buffer = nullptr;
unzFile pFile = nullptr;
*size = 0;
do
@ -537,7 +541,7 @@ unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char
char szFilePathA[260];
unz_file_info FileInfo;
nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0);
nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), nullptr, 0, nullptr, 0);
CC_BREAK_IF(UNZ_OK != nRet);
nRet = unzOpenCurrentFile(pFile);
@ -564,12 +568,15 @@ std::string FileUtils::getNewFilename(const std::string &filename)
std::string newFileName;
// in Lookup Filename dictionary ?
String* fileNameFound = _filenameLookupDict ? (String*)_filenameLookupDict->objectForKey(filename) : NULL;
if( NULL == fileNameFound || fileNameFound->length() == 0) {
auto iter = _filenameLookupDict.find(filename);
if (iter == _filenameLookupDict.end())
{
newFileName = filename;
}
else {
newFileName = fileNameFound->getCString();
else
{
newFileName = iter->second.asString();
}
return newFileName;
}
@ -731,12 +738,10 @@ void FileUtils::addSearchPath(const std::string &searchpath)
_searchPathArray.push_back(path);
}
void FileUtils::setFilenameLookupDictionary(Dictionary* pFilenameLookupDict)
void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict)
{
_fullPathCache.clear();
CC_SAFE_RELEASE(_filenameLookupDict);
_filenameLookupDict = pFilenameLookupDict;
CC_SAFE_RETAIN(_filenameLookupDict);
_filenameLookupDict = filenameLookupDict;
}
void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename)
@ -744,17 +749,17 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename
std::string fullPath = fullPathForFilename(filename);
if (fullPath.length() > 0)
{
Dictionary* dict = Dictionary::createWithContentsOfFile(fullPath.c_str());
if (dict)
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
if (!dict.empty())
{
Dictionary* metadata = static_cast<Dictionary*>( dict->objectForKey("metadata") );
int version = static_cast<String*>( metadata->objectForKey("version"))->intValue();
ValueMap& metadata = dict["metadata"].asValueMap();
int version = metadata["version"].asInt();
if (version != 1)
{
CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename.c_str());
return;
}
setFilenameLookupDictionary( static_cast<Dictionary*>( dict->objectForKey("filenames")) );
setFilenameLookupDictionary( dict["filenames"].asValueMap());
}
}
}

View File

@ -29,11 +29,10 @@ THE SOFTWARE.
#include <unordered_map>
#include "CCPlatformMacros.h"
#include "ccTypes.h"
#include "CCValue.h"
NS_CC_BEGIN
class Dictionary;
class Array;
/**
* @addtogroup platform
* @{
@ -42,10 +41,7 @@ class Array;
//! @brief Helper class to handle file operations
class CC_DLL FileUtils
{
friend class Array;
friend class Dictionary;
public:
/**
* Gets the instance of FileUtils.
*/
@ -189,7 +185,7 @@ public:
* @param pFilenameLookupDict The dictionary for replacing filename.
* @since v2.1
*/
virtual void setFilenameLookupDictionary(Dictionary* filenameLookupDict);
virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);
/**
* Gets full path from a file name and the path of the reletive file.
@ -300,6 +296,24 @@ public:
virtual void setPopupNotify(bool notify);
virtual bool isPopupNotify();
/**
* Converts the contents of a file to a ValueMap.
* @note This method is used internally.
*/
virtual ValueMap getValueMapFromFile(const std::string& filename);
/**
* Write a ValueMap to a plist file.
* @note This method is used internally.
*/
virtual bool writeToFile(ValueMap& dict, const std::string& fullPath);
/**
* Converts the contents of a file to a ValueVector.
* @note This method is used internally.
*/
virtual ValueVector getValueVectorFromFile(const std::string& filename);
protected:
/**
* The default constructor.
@ -347,23 +361,6 @@ protected:
*/
virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename);
/**
* Creates a dictionary by the contents of a file.
* @note This method is used internally.
*/
virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename);
/**
* Write a dictionary to a plist file.
* @note This method is used internally.
*/
virtual bool writeToFile(Dictionary *dict, const std::string& fullPath);
/**
* Creates an array by the contents of a file.
* @note This method is used internally.
*/
virtual Array* createArrayWithContentsOfFile(const std::string& filename);
/** Dictionary used to lookup filenames based on a key.
* It is used internally by the following methods:
@ -372,7 +369,7 @@ protected:
*
* @since v2.1
*/
Dictionary* _filenameLookupDict;
ValueMap _filenameLookupDict;
/**
* The vector contains resolution folders.

View File

@ -1548,7 +1548,7 @@ bool Image::initWithTGAData(tImageTGA* tgaData)
const unsigned char tgaSuffix[] = ".tga";
for(int i = 0; i < 4; ++i)
{
if (std::tolower(_filePath[_filePath.length() - i - 1]) != tgaSuffix[3 - i])
if (tolower(_filePath[_filePath.length() - i - 1]) != tgaSuffix[3 - i])
{
CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str());
break;

View File

@ -23,7 +23,6 @@
****************************************************************************/
#include "CCSAXParser.h"
#include "CCDictionary.h"
#include "CCFileUtils.h"
#include "tinyxml2.h"
@ -102,7 +101,7 @@ bool SAXParser::init(const char *pszEncoding)
return true;
}
bool SAXParser::parse(const char* pXMLData, unsigned int uDataLength)
bool SAXParser::parse(const char* pXMLData, size_t uDataLength)
{
tinyxml2::XMLDocument tinyDoc;
tinyDoc.Parse(pXMLData, uDataLength);

View File

@ -26,6 +26,7 @@
#include "CCPlatformConfig.h"
#include "platform/CCCommon.h"
#include "string.h" // for size_t
NS_CC_BEGIN
@ -81,7 +82,7 @@ public:
* @js NA
* @lua NA
*/
bool parse(const char* pXMLData, unsigned int uDataLength);
bool parse(const char* pXMLData, size_t uDataLength);
/**
* @js NA
* @lua NA

View File

@ -46,10 +46,10 @@ public:
virtual bool isFileExist(const std::string& strFilePath) const override;
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) override;
virtual Dictionary* createDictionaryWithContentsOfFile(const std::string& filename) override;
virtual bool writeToFile(Dictionary *dict, const std::string& fullPath) override;
virtual ValueMap getValueMapFromFile(const std::string& filename) override;
virtual bool writeToFile(ValueMap& dict, const std::string& fullPath) override;
virtual Array* createArrayWithContentsOfFile(const std::string& filename) override;
virtual ValueVector getValueVectorFromFile(const std::string& filename) override;
};
// end of platform group

View File

@ -37,152 +37,152 @@ THE SOFTWARE.
NS_CC_BEGIN
static void addValueToDict(id key, id value, Dictionary* pDict);
static void addObjectToNSDict(const char*key, Object* object, NSMutableDictionary *dict);
static void addValueToDict(id nsKey, id nsValue, ValueMap& dict);
static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict);
static void addItemToArray(id item, Array *pArray)
static void addItemToArray(id item, ValueVector& array)
{
// add string value into array
if ([item isKindOfClass:[NSString class]]) {
String* pValue = new String([item UTF8String]);
pArray->addObject(pValue);
pValue->release();
if ([item isKindOfClass:[NSString class]])
{
array.push_back(Value([item UTF8String]));
return;
}
// add number value into array(such as int, float, bool and so on)
if ([item isKindOfClass:[NSNumber class]]) {
NSString* pStr = [item stringValue];
String* pValue = new String([pStr UTF8String]);
pArray->addObject(pValue);
pValue->release();
if ([item isKindOfClass:[NSNumber class]])
{
array.push_back(Value([item doubleValue]));
return;
}
// add dictionary value into array
if ([item isKindOfClass:[NSDictionary class]]) {
Dictionary* pDictItem = new Dictionary();
pDictItem->init();
for (id subKey in [item allKeys]) {
if ([item isKindOfClass:[NSDictionary class]])
{
ValueMap dict;
for (id subKey in [item allKeys])
{
id subValue = [item objectForKey:subKey];
addValueToDict(subKey, subValue, pDictItem);
addValueToDict(subKey, subValue, dict);
}
pArray->addObject(pDictItem);
pDictItem->release();
array.push_back(Value(dict));
return;
}
// add array value into array
if ([item isKindOfClass:[NSArray class]]) {
Array *pArrayItem = new Array();
pArrayItem->init();
for (id subItem in item) {
addItemToArray(subItem, pArrayItem);
if ([item isKindOfClass:[NSArray class]])
{
ValueVector subArray;
for (id subItem in item)
{
addItemToArray(subItem, subArray);
}
pArray->addObject(pArrayItem);
pArrayItem->release();
array.push_back(Value(subArray));
return;
}
}
static void addObjectToNSArray(Object *object, NSMutableArray *array)
static void addObjectToNSArray(Value& value, NSMutableArray *array)
{
// add string into array
if (String *ccString = dynamic_cast<String *>(object)) {
NSString *strElement = [NSString stringWithCString:ccString->getCString() encoding:NSUTF8StringEncoding];
if (value.getType() == Value::Type::STRING)
{
NSString *strElement = [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding];
[array addObject:strElement];
return;
}
// add array into array
if (Array *ccArray = dynamic_cast<Array *>(object)) {
if (value.getType() == Value::Type::VECTOR)
{
NSMutableArray *arrElement = [NSMutableArray array];
Object *element = NULL;
CCARRAY_FOREACH(ccArray, element)
{
addObjectToNSArray(element, arrElement);
}
ValueVector valueArray = value.asValueVector();
std::for_each(valueArray.begin(), valueArray.end(), [=](Value& e){
addObjectToNSArray(e, arrElement);
});
[array addObject:arrElement];
return;
}
// add dictionary value into array
if (Dictionary *ccDict = dynamic_cast<Dictionary *>(object)) {
if (value.getType() == Value::Type::MAP)
{
NSMutableDictionary *dictElement = [NSMutableDictionary dictionary];
DictElement *element = NULL;
CCDICT_FOREACH(ccDict, element)
auto valueDict = value.asValueMap();
for (auto iter = valueDict.begin(); iter != valueDict.end(); ++iter)
{
addObjectToNSDict(element->getStrKey(), element->getObject(), dictElement);
addObjectToNSDict(iter->first, iter->second, dictElement);
}
[array addObject:dictElement];
}
}
static void addValueToDict(id key, id value, Dictionary* pDict)
static void addValueToDict(id nsKey, id nsValue, ValueMap& dict)
{
// the key must be a string
CCASSERT([key isKindOfClass:[NSString class]], "The key should be a string!");
std::string pKey = [key UTF8String];
// the value is a new dictionary
if ([value isKindOfClass:[NSDictionary class]]) {
Dictionary* pSubDict = new Dictionary();
pSubDict->init();
for (id subKey in [value allKeys]) {
id subValue = [value objectForKey:subKey];
addValueToDict(subKey, subValue, pSubDict);
}
pDict->setObject(pSubDict, pKey.c_str());
pSubDict->release();
return;
}
CCASSERT([nsKey isKindOfClass:[NSString class]], "The key should be a string!");
std::string key = [nsKey UTF8String];
// the value is a string
if ([value isKindOfClass:[NSString class]]) {
String* pValue = new String([value UTF8String]);
pDict->setObject(pValue, pKey.c_str());
pValue->release();
if ([nsValue isKindOfClass:[NSString class]])
{
dict[key] = Value([nsValue UTF8String]);
return;
}
// the value is a number
if ([value isKindOfClass:[NSNumber class]]) {
NSString* pStr = [value stringValue];
String* pValue = new String([pStr UTF8String]);
if ([nsValue isKindOfClass:[NSNumber class]])
{
dict[key] = Value([nsValue doubleValue]);
return;
}
// the value is a new dictionary
if ([nsValue isKindOfClass:[NSDictionary class]])
{
ValueMap subDict;
pDict->setObject(pValue, pKey.c_str());
pValue->release();
for (id subKey in [nsValue allKeys])
{
id subValue = [nsValue objectForKey:subKey];
addValueToDict(subKey, subValue, subDict);
}
dict[key] = Value(subDict);
return;
}
// the value is a array
if ([value isKindOfClass:[NSArray class]]) {
Array *pArray = new Array();
pArray->init();
for (id item in value) {
addItemToArray(item, pArray);
if ([nsValue isKindOfClass:[NSArray class]])
{
ValueVector valueArray;
for (id item in nsValue)
{
addItemToArray(item, valueArray);
}
pDict->setObject(pArray, pKey.c_str());
pArray->release();
dict[key] = Value(valueArray);
return;
}
}
static void addObjectToNSDict(const char * key, Object* object, NSMutableDictionary *dict)
static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict)
{
NSString *NSkey = [NSString stringWithCString:key encoding:NSUTF8StringEncoding];
NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding];
// the object is a Dictionary
if (Dictionary *ccDict = dynamic_cast<Dictionary *>(object)) {
if (value.getType() == Value::Type::MAP)
{
NSMutableDictionary *dictElement = [NSMutableDictionary dictionary];
DictElement *element = NULL;
CCDICT_FOREACH(ccDict, element)
ValueMap subDict = value.asValueMap();
for (auto iter = subDict.begin(); iter != subDict.end(); ++iter)
{
addObjectToNSDict(element->getStrKey(), element->getObject(), dictElement);
addObjectToNSDict(iter->first, iter->second, dictElement);
}
[dict setObject:dictElement forKey:NSkey];
@ -190,20 +190,24 @@ static void addObjectToNSDict(const char * key, Object* object, NSMutableDiction
}
// the object is a String
if (String *element = dynamic_cast<String *>(object)) {
NSString *strElement = [NSString stringWithCString:element->getCString() encoding:NSUTF8StringEncoding];
if (value.getType() == Value::Type::STRING)
{
NSString *strElement = [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding];
[dict setObject:strElement forKey:NSkey];
return;
}
// the object is a Array
if (Array *ccArray = dynamic_cast<Array *>(object)) {
if (value.getType() == Value::Type::VECTOR)
{
NSMutableArray *arrElement = [NSMutableArray array];
Object *element = NULL;
CCARRAY_FOREACH(ccArray, element)
{
addObjectToNSArray(element, arrElement);
}
ValueVector array = value.asValueVector();
std::for_each(array.begin(), array.end(), [=](Value& v){
addObjectToNSArray(v, arrElement);
});
[dict setObject:arrElement forKey:NSkey];
return;
}
@ -304,39 +308,33 @@ std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string
return "";
}
Dictionary* FileUtilsApple::createDictionaryWithContentsOfFile(const std::string& filename)
ValueMap FileUtilsApple::getValueMapFromFile(const std::string& filename)
{
std::string fullPath = fullPathForFilename(filename);
NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:path];
ValueMap ret;
if (dict != nil)
{
auto ret = new Dictionary();
ret->init();
for (id key in [dict allKeys]) {
for (id key in [dict allKeys])
{
id value = [dict objectForKey:key];
addValueToDict(key, value, ret);
}
return ret;
}
else
{
return NULL;
}
return ret;
}
bool FileUtilsApple::writeToFile(Dictionary *dict, const std::string &fullPath)
bool FileUtilsApple::writeToFile(ValueMap& dict, const std::string &fullPath)
{
//CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
DictElement *element = NULL;
CCDICT_FOREACH(dict, element)
for (auto iter = dict.begin(); iter != dict.end(); ++iter)
{
addObjectToNSDict(element->getStrKey(), element->getObject(), nsDict);
addObjectToNSDict(iter->first, iter->second, nsDict);
}
NSString *file = [NSString stringWithUTF8String:fullPath.c_str()];
@ -346,7 +344,7 @@ bool FileUtilsApple::writeToFile(Dictionary *dict, const std::string &fullPath)
return true;
}
Array* FileUtilsApple::createArrayWithContentsOfFile(const std::string& filename)
ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename)
{
// NSString* pPath = [NSString stringWithUTF8String:pFileName];
// NSString* pathExtension= [pPath pathExtension];
@ -357,8 +355,7 @@ Array* FileUtilsApple::createArrayWithContentsOfFile(const std::string& filename
NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
NSArray* array = [NSArray arrayWithContentsOfFile:path];
Array* ret = new Array();
ret->init();
ValueVector ret;
for (id value in array)
{

View File

@ -26,10 +26,10 @@ THE SOFTWARE.
#include "CCArray.h"
#include "CCString.h"
#include "platform/CCFileUtils.h"
#include <algorithm> // std::for_each
NS_CC_BEGIN
#if CC_USE_ARRAY_VECTOR
// ----------------------------------------------------------------------------------
@ -478,7 +478,15 @@ Array* Array::createWithContentsOfFile(const char* fileName)
Array* Array::createWithContentsOfFileThreadSafe(const char* fileName)
{
return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName);
ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName);
Array* ret = Array::createWithCapacity(arr.size());
std::for_each(arr.cbegin(), arr.cend(), [&ret](const Value& value){
ret->addObject(String::create(value.asString()));
});
return ret;
}
bool Array::init()

View File

@ -26,6 +26,7 @@
#include "CCString.h"
#include "CCInteger.h"
#include "platform/CCFileUtils.h"
#include <algorithm> // std::for_each
using namespace std;
@ -377,9 +378,73 @@ Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict)
return srcDict->clone();
}
static Array* visitArray(const ValueVector& array);
static Dictionary* visitDict(const ValueMap& dict)
{
Dictionary* ret = new Dictionary();
ret->init();
for (auto iter = dict.begin(); iter != dict.end(); ++iter)
{
if (iter->second.getType() == Value::Type::MAP)
{
const ValueMap& subDict = iter->second.asValueMap();
auto sub = visitDict(subDict);
ret->setObject(sub, iter->first);
sub->release();
}
else if (iter->second.getType() == Value::Type::VECTOR)
{
const ValueVector& arr = iter->second.asValueVector();
auto sub = visitArray(arr);
ret->setObject(sub, iter->first);
sub->release();
}
else
{
auto str = new String(iter->second.asString());
ret->setObject(str, iter->first);
str->release();
}
}
return ret;
}
static Array* visitArray(const ValueVector& array)
{
Array* ret = new Array();
ret->init();
std::for_each(array.begin(), array.end(), [&ret](const Value& value){
if (value.getType() == Value::Type::MAP)
{
const ValueMap& subDict = value.asValueMap();
auto sub = visitDict(subDict);
ret->addObject(sub);
sub->release();
}
else if (value.getType() == Value::Type::VECTOR)
{
const ValueVector& arr = value.asValueVector();
auto sub = visitArray(arr);
ret->addObject(sub);
sub->release();
}
else
{
auto str = new String(value.asString());
ret->addObject(str);
str->release();
}
});
return ret;
}
Dictionary* Dictionary::createWithContentsOfFileThreadSafe(const char *pFileName)
{
return FileUtils::getInstance()->createDictionaryWithContentsOfFile(pFileName);
return visitDict(FileUtils::getInstance()->getValueMapFromFile(pFileName));
}
void Dictionary::acceptVisitor(DataVisitor &visitor)
@ -399,7 +464,14 @@ Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName)
bool Dictionary::writeToFile(const char *fullPath)
{
return FileUtils::getInstance()->writeToFile(this, fullPath);
ValueMap dict;
DictElement* element = nullptr;
CCDICT_FOREACH(this, element)
{
dict[element->getStrKey()] = Value(static_cast<String*>(element->getObject())->getCString());
}
return FileUtils::getInstance()->writeToFile(dict, fullPath);
}
Dictionary* Dictionary::clone() const

254
cocos/base/CCMap.h Normal file
View File

@ -0,0 +1,254 @@
/****************************************************************************
Copyright (c) 2012 - 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCMAP_H__
#define __CCMAP_H__
#include <vector>
#include <unordered_map>
#include <algorithm> // std::for_each
NS_CC_BEGIN
/**
* @addtogroup data_structures
* @{
*/
template <class K, class V>
class CC_DLL Map
{
public:
Map<K, V>()
: _data()
{
CCLOGINFO("In the default constructor of Map!");
}
explicit Map<K, V>(long capacity)
: _data()
{
CCLOGINFO("In the constructor with capacity of Map!");
_data.reserve(capacity);
}
Map<K, V>(const Map<K, V>& other)
{
CCLOGINFO("In the copy constructor of Map!");
_data = other;
addRefForAllObjects();
}
Map<K, V>(Map<K, V>&& other)
{
CCLOGINFO("In the move constructor of Map!");
_data = other;
}
~Map<K, V>()
{
CCLOGINFO("In the destructor of Map!");
clear();
}
/** Sets capacity of current array */
void reserve(long capacity)
{
_data.reserve(capacity);
}
/** Returns capacity of the array */
size_t capacity() const
{
return _data.capacity();
}
size_t size() const
{
return _data.size();
}
bool empty() const
{
return _data.empty();
}
std::vector<K> keys() const
{
std::vector<K> keys;
if (!_data.empty())
{
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{
keys.push_back(iter->first);
}
}
return std::move(keys);
}
std::vector<K> keys(V object) const
{
std::vector<K> keys;
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{
if (iter->second == object)
{
keys.push_back(iter->first);
}
}
return std::move(keys);
}
V at(const K& key) const
{
auto iter = _data.find(key);
if (iter != _data.end())
return iter->second;
return nullptr;
}
void insert(const K& key, V object)
{
CCASSERT(object != nullptr, "Object is nullptr!");
remove(key);
_data.insert(std::make_pair(key, object));
object->retain();
}
void remove(const K& key)
{
auto iter = _data.find(key);
if (iter != _data.end())
{
iter->second->release();
_data.erase(iter);
}
}
void remove(const std::vector<K>& keys)
{
std::for_each(keys.cbegin(), keys.cend(), [this](const K& key){
this->remove(key);
});
}
void clear()
{
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{
iter->second->release();
}
_data.clear();
}
V getRandomObject() const
{
if (!_data.empty())
{
int randIdx = rand() % _data.size();
return (_data.begin() + randIdx)->second;
}
return nullptr;
}
// ------------------------------------------
// Iterators
// ------------------------------------------
typedef std::unordered_map<K, V> RefMap;
typedef typename RefMap::iterator iterator;
typedef typename RefMap::const_iterator const_iterator;
iterator begin() { return _data.begin(); }
const_iterator begin() const { return _data.begin(); }
iterator end() { return _data.end(); }
const_iterator end() const { return _data.end(); }
const_iterator cbegin() const { return _data.cbegin(); }
const_iterator cend() const { return _data.cend(); }
// Don't uses operator since we could not decide whether it needs 'retain'/'release'.
// V& operator[] ( const K& key )
// {
// CCLOG("copy: [] ref");
// return _data[key];
// }
//
// V& operator[] ( K&& key )
// {
// CCLOG("move [] ref");
// return _data[key];
// }
// const V& operator[] ( const K& key ) const
// {
// CCLOG("const copy []");
// return _data.at(key);
// }
//
// const V& operator[] ( K&& key ) const
// {
// CCLOG("const move []");
// return _data.at(key);
// }
Map<K, V>& operator= ( const Map<K, V>& other )
{
CCLOG("In the copy assignment operator of Map!");
clear();
_data = other._data;
addRefForAllObjects();
}
Map<K, V>& operator= ( Map<K, V>&& other )
{
CCLOG("In the move assignment operator of Map!");
_data = std::move(other._data);
}
protected:
void addRefForAllObjects()
{
for (auto iter = _data.begin(); iter != _data.end(); ++iter)
{
_data->second->retain();
}
}
RefMap _data;
};
// end of data_structure group
/// @}
NS_CC_END
#endif /* __CCMAP_H__ */

View File

@ -53,16 +53,16 @@ static inline void split(std::string src, const char* token, strArray& vect)
// if the form is right,the string will be split into the parameter strs;
// or the parameter strs will be empty.
// if the form is right return true,else return false.
static bool splitWithForm(const char* pStr, strArray& strs)
static bool splitWithForm(const std::string& str, strArray& strs)
{
bool bRet = false;
do
{
CC_BREAK_IF(!pStr);
CC_BREAK_IF(str.empty());
// string is empty
std::string content = pStr;
std::string content = str;
CC_BREAK_IF(content.length() == 0);
int nPosLeft = content.find('{');
@ -97,14 +97,14 @@ static bool splitWithForm(const char* pStr, strArray& strs)
// implement the functions
Rect RectFromString(const char* pszContent)
Rect RectFromString(const std::string& str)
{
Rect result = Rect::ZERO;
do
{
CC_BREAK_IF(!pszContent);
std::string content = pszContent;
CC_BREAK_IF(str.empty());
std::string content = str;
// find the first '{' and the third '}'
int nPosLeft = content.find('{');
@ -146,14 +146,14 @@ Rect RectFromString(const char* pszContent)
return result;
}
Point PointFromString(const char* pszContent)
Point PointFromString(const std::string& str)
{
Point ret = Point::ZERO;
do
{
strArray strs;
CC_BREAK_IF(!splitWithForm(pszContent, strs));
CC_BREAK_IF(!splitWithForm(str, strs));
float x = (float) atof(strs[0].c_str());
float y = (float) atof(strs[1].c_str());
@ -164,7 +164,7 @@ Point PointFromString(const char* pszContent)
return ret;
}
Size SizeFromString(const char* pszContent)
Size SizeFromString(const std::string& pszContent)
{
Size ret = Size::ZERO;

View File

@ -44,7 +44,7 @@ NS_CC_BEGIN
@return A Core Graphics structure that represents a rectangle.
If the string is not well-formed, the function returns Rect::ZERO.
*/
Rect CC_DLL RectFromString(const char* pszContent);
Rect CC_DLL RectFromString(const std::string& str);
/**
@brief Returns a Core Graphics point structure corresponding to the data in a given string.
@ -56,7 +56,7 @@ Rect CC_DLL RectFromString(const char* pszContent);
@return A Core Graphics structure that represents a point.
If the string is not well-formed, the function returns Point::ZERO.
*/
Point CC_DLL PointFromString(const char* pszContent);
Point CC_DLL PointFromString(const std::string& str);
/**
@brief Returns a Core Graphics size structure corresponding to the data in a given string.
@ -68,7 +68,7 @@ Point CC_DLL PointFromString(const char* pszContent);
@return A Core Graphics structure that represents a size.
If the string is not well-formed, the function returns Size::ZERO.
*/
Size CC_DLL SizeFromString(const char* pszContent);
Size CC_DLL SizeFromString(const std::string& str);
// end of data_structure group
/// @}

407
cocos/base/CCValue.cpp Normal file
View File

@ -0,0 +1,407 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCValue.h"
#include <sstream>
NS_CC_BEGIN
Value::Value()
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::NONE)
{
}
Value::Value(int v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::INTEGER)
{
_baseData.intVal = v;
}
Value::Value(float v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::FLOAT)
{
_baseData.floatVal = v;
}
Value::Value(double v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::DOUBLE)
{
_baseData.doubleVal = v;
}
Value::Value(bool v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::BOOLEAN)
{
_baseData.boolVal = v;
}
Value::Value(const char* v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::STRING)
{
_strData = v;
}
Value::Value(const std::string& v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::STRING)
{
_strData = v;
}
Value::Value(const ValueVector& v)
: _vectorData(new ValueVector())
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::VECTOR)
{
*_vectorData = v;
}
Value::Value(ValueVector&& v)
: _vectorData(new ValueVector())
, _mapData(nullptr)
, _intKeyMapData(nullptr)
, _type(Type::VECTOR)
{
*_vectorData = std::move(v);
}
Value::Value(const ValueMap& v)
: _vectorData(nullptr)
, _mapData(new ValueMap())
, _intKeyMapData(nullptr)
, _type(Type::MAP)
{
*_mapData = v;
}
Value::Value(ValueMap&& v)
: _vectorData(nullptr)
, _mapData(new ValueMap())
, _intKeyMapData(nullptr)
, _type(Type::MAP)
{
*_mapData = std::move(v);
}
Value::Value(const IntValueMap& v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(new IntValueMap())
, _type(Type::INT_KEY_MAP)
{
*_intKeyMapData = v;
}
Value::Value(IntValueMap&& v)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(new IntValueMap())
, _type(Type::INT_KEY_MAP)
{
*_intKeyMapData = std::move(v);
}
Value::Value(const Value& other)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
{
*this = other;
}
Value::Value(Value&& other)
: _vectorData(nullptr)
, _mapData(nullptr)
, _intKeyMapData(nullptr)
{
*this = std::move(other);
}
Value::~Value()
{
CC_SAFE_DELETE(_vectorData);
CC_SAFE_DELETE(_mapData);
CC_SAFE_DELETE(_intKeyMapData);
}
Value& Value::operator= (const Value& other)
{
switch (other._type) {
case Type::INTEGER:
_baseData.intVal = other._baseData.intVal;
break;
case Type::FLOAT:
_baseData.floatVal = other._baseData.floatVal;
break;
case Type::DOUBLE:
_baseData.doubleVal = other._baseData.doubleVal;
break;
case Type::BOOLEAN:
_baseData.boolVal = other._baseData.boolVal;
break;
case Type::STRING:
_strData = other._strData;
break;
case Type::VECTOR:
if (_vectorData == nullptr)
_vectorData = new ValueVector();
*_vectorData = *other._vectorData;
break;
case Type::MAP:
if (_mapData == nullptr)
_mapData = new ValueMap();
*_mapData = *other._mapData;
break;
case Type::INT_KEY_MAP:
if (_intKeyMapData == nullptr)
_intKeyMapData = new IntValueMap();
*_intKeyMapData = *other._intKeyMapData;
break;
default:
break;
}
_type = other._type;
return *this;
}
Value& Value::operator= (Value&& other)
{
switch (other._type) {
case Type::INTEGER:
_baseData.intVal = other._baseData.intVal;
break;
case Type::FLOAT:
_baseData.floatVal = other._baseData.floatVal;
break;
case Type::DOUBLE:
_baseData.doubleVal = other._baseData.doubleVal;
break;
case Type::BOOLEAN:
_baseData.boolVal = other._baseData.boolVal;
break;
case Type::STRING:
_strData = other._strData;
break;
case Type::VECTOR:
CC_SAFE_DELETE(_vectorData);
_vectorData = other._vectorData;
break;
case Type::MAP:
CC_SAFE_DELETE(_mapData);
_mapData = other._mapData;
break;
case Type::INT_KEY_MAP:
CC_SAFE_DELETE(_intKeyMapData);
_intKeyMapData = other._intKeyMapData;
break;
default:
break;
}
_type = other._type;
other._vectorData = nullptr;
other._mapData = nullptr;
other._intKeyMapData = nullptr;
other._type = Type::NONE;
return *this;
}
int Value::asInt() const
{
CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");
if (_type == Type::INTEGER)
{
return _baseData.intVal;
}
if (_type == Type::STRING)
{
return atoi(_strData.c_str());
}
if (_type == Type::FLOAT)
{
return _baseData.floatVal;
}
if (_type == Type::DOUBLE)
{
return _baseData.doubleVal;
}
if (_type == Type::BOOLEAN)
{
return _baseData.boolVal;
}
return 0;
}
float Value::asFloat() const
{
CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");
if (_type == Type::FLOAT)
{
return _baseData.floatVal;
}
if (_type == Type::STRING)
{
return atof(_strData.c_str());
}
if (_type == Type::INTEGER)
{
return _baseData.intVal;
}
if (_type == Type::DOUBLE)
{
return _baseData.doubleVal;
}
if (_type == Type::BOOLEAN)
{
return _baseData.boolVal;
}
return 0.0f;
}
double Value::asDouble() const
{
CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");
if (_type == Type::DOUBLE)
{
return _baseData.doubleVal;
}
if (_type == Type::STRING)
{
return (float)atof(_strData.c_str());
}
if (_type == Type::INTEGER)
{
return _baseData.intVal;
}
if (_type == Type::FLOAT)
{
return _baseData.floatVal;
}
if (_type == Type::BOOLEAN)
{
return _baseData.boolVal;
}
return 0.0;
}
bool Value::asBool() const
{
CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");
if (_type == Type::BOOLEAN)
{
return _baseData.boolVal;
}
if (_type == Type::STRING)
{
return (_strData == "0" || _strData == "false") ? false : true;
}
if (_type == Type::INTEGER)
{
return _baseData.intVal == 0 ? false : true;
}
if (_type == Type::FLOAT)
{
return _baseData.floatVal == 0.0f ? false : true;
}
if (_type == Type::DOUBLE)
{
return _baseData.doubleVal == 0.0 ? false : true;
}
return true;
}
std::string Value::asString() const
{
CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");
if (_type == Type::STRING)
{
return _strData;
}
std::stringstream ret;
switch (_type) {
case Type::INTEGER:
ret << _baseData.intVal;
break;
case Type::FLOAT:
ret << _baseData.floatVal;
break;
case Type::DOUBLE:
ret << _baseData.doubleVal;
break;
case Type::BOOLEAN:
ret << _baseData.boolVal;
break;
default:
break;
}
return ret.str();
}
NS_CC_END

121
cocos/base/CCValue.h Normal file
View File

@ -0,0 +1,121 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCValue__
#define __cocos2d_libs__CCValue__
#include "CCPlatformMacros.h"
#include "ccMacros.h"
#include <string>
#include <vector>
#include <unordered_map>
NS_CC_BEGIN
class Value;
typedef std::vector<Value> ValueVector;
typedef std::unordered_map<std::string, Value> ValueMap;
typedef std::unordered_map<int, Value> IntValueMap;
class Value
{
public:
Value();
explicit Value(int v);
explicit Value(float v);
explicit Value(double v);
explicit Value(bool v);
explicit Value(const char* v);
explicit Value(const std::string& v);
explicit Value(const ValueVector& v);
explicit Value(ValueVector&& v);
explicit Value(const ValueMap& v);
explicit Value(ValueMap&& v);
explicit Value(const IntValueMap& v);
explicit Value(IntValueMap&& v);
Value(const Value& other);
Value(Value&& other);
~Value();
Value& operator= (const Value& other);
Value& operator= (Value&& other);
int asInt() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
std::string asString() const;
inline ValueVector& asValueVector() { return *_vectorData; }
inline const ValueVector& asValueVector() const { return *_vectorData; }
inline ValueMap& asValueMap() { return *_mapData; }
inline const ValueMap& asValueMap() const { return *_mapData; }
inline IntValueMap& asIntKeyMap() { return *_intKeyMapData; }
inline const IntValueMap& asIntKeyMap() const { return *_intKeyMapData; }
inline bool isNull() const { return _type == Type::NONE; }
enum class Type
{
NONE,
INTEGER,
FLOAT,
DOUBLE,
BOOLEAN,
STRING,
VECTOR,
MAP,
INT_KEY_MAP
};
inline Type getType() const { return _type; };
private:
union
{
int intVal;
float floatVal;
double doubleVal;
bool boolVal;
}_baseData;
std::string _strData;
ValueVector* _vectorData;
ValueMap* _mapData;
IntValueMap* _intKeyMapData;
Type _type;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCValue__) */

366
cocos/base/CCVector.h Normal file
View File

@ -0,0 +1,366 @@
/****************************************************************************
Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCVECTOR_H__
#define __CCVECTOR_H__
#include <vector>
#include <algorithm> // std::for_each
#include "ccMacros.h"
NS_CC_BEGIN
template<class T>
class CC_DLL Vector
{
public:
Vector<T>()
: _data()
{
}
/** creates an emptry Vector */
explicit Vector<T>(long capacity)
: _data()
{
CCLOGINFO("In the default constructor with capacity of Vector.");
reserve(capacity);
}
virtual ~Vector<T>()
{
CCLOGINFO("In the destructor of Vector.");
clear();
}
Vector<T>(const Vector<T>& other)
{
CCLOGINFO("In the copy constructor!");
_data = other._data;
addRefForAllObjects();
}
/** Move constructor */
Vector<T>(Vector<T>&& other)
{
CCLOGINFO("In the move constructor of Vector!");
_data = other._data;
}
Vector<T>& operator=(const Vector<T>& other)
{
CCLOGINFO("In the copy assignment operator!");
clear();
_data = other._data;
addRefForAllObjects();
return *this;
}
Vector<T>& operator=(Vector<T>&& other)
{
CCLOGINFO("In the move assignment operator!");
_data = other._data;
return *this;
}
// Don't uses operator since we could not decide whether it needs 'retain'/'release'.
// T& operator[](long index)
// {
// return _data[index];
// }
//
// const T& operator[](long index) const
// {
// return _data[index];
// }
/** Sets capacity of current array */
void reserve(long capacity)
{
_data.reserve(capacity);
}
/** Returns capacity of the array */
long capacity() const
{
return _data.capacity();
}
// Querying an Array
/** Returns element count of the array */
size_t size() const
{
return _data.size();
}
bool empty() const
{
return _data.empty();
}
/** Returns index of a certain object, return UINT_MAX if doesn't contain the object */
long getIndex(T object) const
{
long i = 0;
for (auto it = _data.begin(); it != _data.end(); ++it, ++i)
{
if (*it == object)
{
return i;
}
}
return -1;
}
/** Returns an element with a certain index */
T at(long index) const
{
CCASSERT( index >= 0 && index < size(), "index out of range in getObjectAtIndex()");
return _data[index];
}
T front() const
{
return _data.front();
}
/** Returns the last element of the array */
T back() const
{
return _data.back();
}
/** Returns a random element */
T getRandomObject() const
{
if (!_data.empty())
{
int randIdx = rand() % _data.size();
return *(_data.begin() + randIdx);
}
return nullptr;
}
/** Returns a Boolean value that indicates whether object is present in array. */
bool contains(T object) const
{
return( std::find(_data.begin(), _data.end(), object) != _data.end() );
}
/** returns true if the the arrays are equal */
bool equals(const Vector<T> &other)
{
size_t s = this->size();
if (s != other.size())
return false;
for (long i = 0; i < s; i++)
{
if (!this->at(i)->isEqual(other.at(i)))
{
return false;
}
}
return true;
}
// Adding Objects
/** Add a certain object */
void pushBack(T object)
{
CCASSERT(object != nullptr, "The object should not be nullptr");
_data.push_back( object );
object->retain();
}
/** Add all elements of an existing array */
void insert(const Vector<T>& other)
{
for( auto it = other.begin(); it != other.end(); ++it ) {
_data.push_back( *it );
(*it)->retain();
}
}
/** Insert a certain object at a certain index */
void insert(long index, T object)
{
CCASSERT(index >= 0 && index <= size(), "Invalid index!");
CCASSERT(object != nullptr, "The object should not be nullptr");
_data.insert((std::begin(_data) + index), object);
object->retain();
}
// Removing Objects
/** Remove last object */
void popBack()
{
CCASSERT(!_data.empty(), "no objects added");
auto last = _data.back();
_data.pop_back();
last->release();
}
/** Remove a certain object */
void removeObject(T object)
{
CCASSERT(object != nullptr, "The object should not be nullptr");
auto iter = std::find(_data.begin(), _data.end(), object);
if (iter != _data.end())
_data.erase(iter);
object->release();
}
/** Removes an element with a certain index */
void remove(long index)
{
CCASSERT(!_data.empty() && index >=0 && index < size(), "Invalid index!");
auto it = std::next( begin(), index );
(*it)->release();
_data.erase(it);
}
/** Removes all objects */
void clear()
{
for( auto it = std::begin(_data); it != std::end(_data); ++it ) {
(*it)->release();
}
_data.clear();
}
// Rearranging Content
/** Swap two elements */
void swap(T object1, T object2)
{
long idx1 = getIndex(object1);
long idx2 = getIndex(object2);
CCASSERT(idx1>=0 && idx2>=0, "invalid object index");
std::swap( _data[idx1], _data[idx2] );
}
/** Swap two elements with certain indexes */
void swap(long index1, long index2)
{
CCASSERT(index1 >=0 && index1 < size() && index2 >= 0 && index2 < size(), "Invalid indices");
std::swap( _data[index1], _data[index2] );
}
/** Replace object at index with another object. */
void replace(long index, T object)
{
CCASSERT(index >= 0 && index < size(), "Invalid index!");
CCASSERT(object != nullptr, "The object should not be nullptr");
_data[index]->release();
_data[index] = object;
object->retain();
}
/** reverses the array */
void reverse()
{
std::reverse( std::begin(_data), std::end(_data) );
}
/** Shrinks the array so the memory footprint corresponds with the number of items */
void shrinkToFit()
{
_data.shrink_to_fit();
}
void forEach(std::function<void(T)> callback)
{
if (size() <= 0)
return;
std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){
callback(obj);
});
}
void forEachReverse(std::function<void(T)> callback)
{
if (size() <= 0)
return;
std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){
callback(obj);
});
}
// ------------------------------------------
// Iterators
// ------------------------------------------
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::const_iterator const_iterator;
typedef typename std::vector<T>::reverse_iterator reverse_iterator;
typedef typename std::vector<T>::const_reverse_iterator const_reverse_iterator;
iterator begin() { return _data.begin(); }
const_iterator begin() const { return _data.begin(); }
iterator end() { return _data.end(); }
const_iterator end() const { return _data.end(); }
const_iterator cbegin() const { return _data.cbegin(); }
const_iterator cend() const { return _data.cend(); }
reverse_iterator rbegin() { return _data.rbegin(); }
const_reverse_iterator rbegin() const { return _data.rbegin(); }
reverse_iterator rend() { return _data.rend(); }
const_reverse_iterator rend() const { return _data.rend(); }
const_reverse_iterator crbegin() const { return _data.crbegin(); }
const_reverse_iterator crend() const { return _data.crend(); }
protected:
void addRefForAllObjects()
{
std::for_each(_data.begin(), _data.end(), [](T obj){
obj->retain();
});
}
std::vector<T> _data;
};
// end of data_structure group
/// @}
NS_CC_END
#endif // __CCVECTOR_H__

View File

@ -10,6 +10,7 @@ set(COCOS_BASE_SRC
CCString.cpp
CCDataVisitor.cpp
CCData.cpp
CCValue.cpp
etc1.cpp
s3tc.cpp
atitc.cpp

View File

@ -620,7 +620,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann
float lastKeyframeTime = 0;
Array *actions = Array::create();
Vector<FiniteTimeAction*> actions;
Array *keyframes = channel->getKeyframes();
long numKeyframes = keyframes->count();
@ -631,7 +631,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann
float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime;
lastKeyframeTime = keyframe->getTime();
if(timeSinceLastKeyframe > 0) {
actions->addObject(DelayTime::create(timeSinceLastKeyframe));
actions.pushBack(DelayTime::create(timeSinceLastKeyframe));
}
Array* keyVal = static_cast<Array *>(keyframe->getValue());
@ -646,7 +646,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann
CallFunc *callbackClone = (static_cast<CallFunc*>(callback))->clone();
if(callbackClone != NULL) {
actions->addObject(callbackClone);
actions.pushBack(callbackClone);
}
}
}
@ -680,7 +680,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann
{
// XXX: how to fix this warning?
CallFuncN *callback = CallFuncN::create(target, selCallFunc);
actions->addObject(callback);
actions.pushBack(callback);
}
}
else
@ -690,7 +690,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann
}
}
}
if(actions->count() < 1) return NULL;
if(actions.size() < 1) return NULL;
return (Object *) Sequence::create(actions);
}
@ -699,9 +699,9 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel)
float lastKeyframeTime = 0;
Array *actions = Array::create();
Vector<FiniteTimeAction*> actions;
Array *keyframes = channel->getKeyframes();
int numKeyframes = keyframes->count();
long numKeyframes = keyframes->count();
for (int i = 0; i < numKeyframes; ++i) {
@ -709,7 +709,7 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel)
float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime;
lastKeyframeTime = keyframe->getTime();
if(timeSinceLastKeyframe > 0) {
actions->addObject(DelayTime::create(timeSinceLastKeyframe));
actions.pushBack(DelayTime::create(timeSinceLastKeyframe));
}
stringstream ss (stringstream::in | stringstream::out);
@ -729,12 +729,12 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel)
ss >> gain;
ss.flush();
actions->addObject(CCBSoundEffect::actionWithSoundFile(soundFile, pitch, pan, gain));
actions.pushBack(CCBSoundEffect::actionWithSoundFile(soundFile, pitch, pan, gain));
}
if(actions->count() < 1) return NULL;
if(actions.size() < 1) return NULL;
return (Object *) Sequence::create(actions);
return Sequence::create(actions);
}
@ -742,19 +742,19 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel)
void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration)
{
Array *keyframes = pSeqProp->getKeyframes();
int numKeyframes = keyframes->count();
long numKeyframes = keyframes->count();
if (numKeyframes > 1)
{
// Make an animation!
Array *actions = Array::create();
Vector<FiniteTimeAction*> actions;
CCBKeyframe *keyframeFirst = (CCBKeyframe*)keyframes->getObjectAtIndex(0);
float timeFirst = keyframeFirst->getTime() + fTweenDuration;
if (timeFirst > 0)
{
actions->addObject(DelayTime::create(timeFirst));
actions.pushBack(DelayTime::create(timeFirst));
}
for (int i = 0; i < numKeyframes - 1; ++i)
@ -768,11 +768,11 @@ void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp,
// Apply easing
action = getEaseAction(action, kf0->getEasingType(), kf0->getEasingOpt());
actions->addObject(action);
actions.pushBack(action);
}
}
FiniteTimeAction *seq = Sequence::create(actions);
auto seq = Sequence::create(actions);
pNode->runAction(seq);
}
}

View File

@ -324,15 +324,13 @@ Scene* CCBReader::createSceneWithNodeGraphFromFile(const char *pCCBFileName, Obj
return pScene;
}
void CCBReader::cleanUpNodeGraph(Node *pNode)
void CCBReader::cleanUpNodeGraph(Node *node)
{
pNode->setUserObject(NULL);
node->setUserObject(nullptr);
Object *pChild = NULL;
CCARRAY_FOREACH(pNode->getChildren(), pChild)
{
cleanUpNodeGraph(static_cast<Node*>(pChild));
}
node->getChildren().forEach([this](Node* obj){
cleanUpNodeGraph(obj);
});
}
Node* CCBReader::readFileWithCleanUp(bool bCleanUp, Dictionary* am)

View File

@ -276,7 +276,8 @@ Spawn * ActionNode::refreshActionProperty()
{
return NULL;
}
Array* cSpawnArray = Array::create();
Vector<FiniteTimeAction*> cSpawnArray;
for (int n = 0; n < _frameArrayNum; n++)
{
Array* cArray = (Array*)(_frameArray->getObjectAtIndex(n));
@ -285,8 +286,8 @@ Spawn * ActionNode::refreshActionProperty()
continue;
}
Array* cSequenceArray = Array::create();
int frameCount = cArray->count();
Vector<FiniteTimeAction*> cSequenceArray;
long frameCount = cArray->count();
for (int i = 0; i < frameCount; i++)
{
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i));
@ -298,13 +299,13 @@ Spawn * ActionNode::refreshActionProperty()
ActionFrame* srcFrame = (ActionFrame*)(cArray->getObjectAtIndex(i-1));
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex()) * getUnitTime();
Action* cAction = frame->getAction(duration);
cSequenceArray->addObject(cAction);
cSequenceArray.pushBack(static_cast<FiniteTimeAction*>(cAction));
}
}
Sequence* cSequence = Sequence::create(cSequenceArray);
if (cSequence != NULL)
{
cSpawnArray->addObject(cSequence);
cSpawnArray.pushBack(cSequence);
}
}

View File

@ -312,7 +312,7 @@ void Armature::changeBoneParent(Bone *bone, const char *parentName)
if(bone->getParentBone())
{
bone->getParentBone()->getChildren()->removeObject(bone);
bone->getParentBone()->getChildren().removeObject(bone);
bone->setParentBone(nullptr);
}
@ -467,7 +467,7 @@ void Armature::draw()
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
}
for (auto object : *_children)
for (auto object : _children)
{
if (Bone *bone = dynamic_cast<Bone *>(object))
{
@ -640,7 +640,7 @@ Rect Armature::getBoundingBox() const
Rect boundingBox = Rect(0, 0, 0, 0);
for(auto object : *_children)
for(auto object : _children)
{
if (Bone *bone = dynamic_cast<Bone *>(object))
{
@ -672,12 +672,12 @@ Rect Armature::getBoundingBox() const
Bone *Armature::getBoneAtPoint(float x, float y) const
{
int length = _children->count();
long length = _children.size();
Bone *bs;
for(int i = length - 1; i >= 0; i--)
for(long i = length - 1; i >= 0; i--)
{
bs = static_cast<Bone*>( _children->getObjectAtIndex(i) );
bs = static_cast<Bone*>( _children.at(i) );
if(bs->getDisplayManager()->containPoint(x, y))
{
return bs;
@ -797,7 +797,7 @@ void Armature::setBody(cpBody *body)
_body = body;
_body->data = this;
for(auto object: *_children)
for(auto object: _children)
{
if (Bone *bone = dynamic_cast<Bone *>(object))
{

View File

@ -163,14 +163,14 @@ void BatchNode::visit()
void BatchNode::draw()
{
if (_children == nullptr)
if (_children.empty())
{
return;
}
CC_NODE_DRAW_SETUP();
for(auto object : *_children)
for(auto object : _children)
{
Armature *armature = dynamic_cast<Armature *>(object);
if (armature)

View File

@ -69,7 +69,6 @@ Bone::Bone()
_boneData = nullptr;
_tween = nullptr;
_tween = nullptr;
_children = nullptr;
_displayManager = nullptr;
_ignoreMovementBoneData = false;
_worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0);
@ -85,7 +84,6 @@ Bone::Bone()
Bone::~Bone(void)
{
CC_SAFE_DELETE(_tweenData);
CC_SAFE_DELETE(_children);
CC_SAFE_DELETE(_tween);
CC_SAFE_DELETE(_displayManager);
CC_SAFE_DELETE(_worldInfo);
@ -229,14 +227,10 @@ void Bone::update(float delta)
DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty());
if (_children)
{
for(auto object : *_children)
{
Bone *childBone = (Bone *)object;
childBone->update(delta);
}
}
_children.forEach([&delta](Node* obj){
Bone *childBone = static_cast<Bone*>(obj);
childBone->update(delta);
});
_boneTransformDirty = false;
}
@ -309,30 +303,29 @@ void Bone::addChildBone(Bone *child)
CCASSERT( nullptr != child, "Argument must be non-nil");
CCASSERT( nullptr == child->_parentBone, "child already added. It can't be added again");
if(!_children)
if(_children.empty())
{
_children = Array::createWithCapacity(4);
_children->retain();
_children.reserve(4);
}
if (_children->getIndexOfObject(child) == CC_INVALID_INDEX)
if (_children.getIndex(child) == CC_INVALID_INDEX)
{
_children->addObject(child);
_children.pushBack(child);
child->setParentBone(this);
}
}
void Bone::removeChildBone(Bone *bone, bool recursion)
{
if (_children && _children->getIndexOfObject(bone) != CC_INVALID_INDEX )
if (!_children.empty() && _children.getIndex(bone) != CC_INVALID_INDEX )
{
if(recursion)
{
Array *ccbones = bone->_children;
auto ccbones = bone->_children;
for(auto object : *ccbones)
for(auto& object : ccbones)
{
Bone *ccBone = (Bone *)object;
Bone *ccBone = static_cast<Bone*>(object);
bone->removeChildBone(ccBone, recursion);
}
}
@ -341,7 +334,7 @@ void Bone::removeChildBone(Bone *bone, bool recursion)
bone->getDisplayManager()->setCurrentDecorativeDisplay(nullptr);
_children->removeObject(bone);
_children.removeObject(bone);
}
}

View File

@ -186,7 +186,7 @@ void ColliderDetector::addContourData(ContourData *contourData)
#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX
CCArray *calculatedVertexList = colliderBody->getCalculatedVertexList();
int num = contourData->vertexList.count();
int num = contourData->vertexList.size();
for (int i = 0; i < num; i++)
{
ContourVertex2 *newVertex = new ContourVertex2(0, 0);
@ -410,7 +410,7 @@ void ColliderDetector::setBody(b2Body *pBody)
const Array *array = &contourData->vertexList;
Object *object = nullptr;
b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.count()];
b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.size()];
int i = 0;
for(auto object : *array)
@ -421,7 +421,7 @@ void ColliderDetector::setBody(b2Body *pBody)
}
b2PolygonShape polygon;
polygon.Set(b2bv, contourData->vertexList.count());
polygon.Set(b2bv, contourData->vertexList.size());
CC_SAFE_DELETE(b2bv);

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_BODY_H__
#define __CCPHYSICS_BODY_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "CCObject.h"

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_CONTACT_H__
#define __CCPHYSICS_CONTACT_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "CCObject.h"

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_JOINT_H__
#define __CCPHYSICS_JOINT_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "CCObject.h"

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_SHAPE_H__
#define __CCPHYSICS_SHAPE_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "CCObject.h"

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_WORLD_H__
#define __CCPHYSICS_WORLD_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include <list>

View File

@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
#ifdef CC_USE_PHYSICS
#include "CCPhysicsBodyInfo_chipmunk.h"
#ifdef CC_USE_PHYSICS
NS_CC_BEGIN
PhysicsBodyInfo::PhysicsBodyInfo()

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_BODY_INFO_CHIPMUNK_H__
#define __CCPHYSICS_BODY_INFO_CHIPMUNK_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "chipmunk.h"

View File

@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
#ifdef CC_USE_PHYSICS
#include "CCPhysicsContactInfo_chipmunk.h"
#ifdef CC_USE_PHYSICS
NS_CC_BEGIN
PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact)

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__
#define __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "chipmunk.h"

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_HELPER_CHIPMUNK_H__
#define __CCPHYSICS_HELPER_CHIPMUNK_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "chipmunk.h"

View File

@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
#ifdef CC_USE_PHYSICS
#include "CCPhysicsJointInfo_chipmunk.h"
#ifdef CC_USE_PHYSICS
#include <algorithm>
#include <unordered_map>

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__
#define __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include "chipmunk.h"

View File

@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
#ifdef CC_USE_PHYSICS
#include "CCPhysicsShapeInfo_chipmunk.h"
#ifdef CC_USE_PHYSICS
#include <algorithm>
#include <unordered_map>

View File

@ -25,7 +25,8 @@
#ifndef __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__
#define __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__
#if CC_USE_PHYSICS
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include <vector>
#include <unordered_map>

View File

@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
#ifdef CC_USE_PHYSICS
#include "CCPhysicsWorldInfo_chipmunk.h"
#ifdef CC_USE_PHYSICS
#include "CCPhysicsHelper_chipmunk.h"
#include "CCPhysicsBodyInfo_chipmunk.h"
#include "CCPhysicsShapeInfo_chipmunk.h"

View File

@ -25,6 +25,7 @@
#ifndef __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__
#define __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__
#include "ccConfig.h"
#ifdef CC_USE_PHYSICS
#include <vector>

@ -1 +1 @@
Subproject commit 8b8a8815474b2dcef3de12161bf7c0621f3c3e05
Subproject commit e4ce0d5a6240c303a591a4476564bd7080ab06c2

View File

@ -222,16 +222,14 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti
void Control::setOpacityModifyRGB(bool bOpacityModifyRGB)
{
_isOpacityModifyRGB=bOpacityModifyRGB;
Object* child;
Array* children=getChildren();
CCARRAY_FOREACH(children, child)
{
RGBAProtocol* pNode = dynamic_cast<RGBAProtocol*>(child);
if (pNode)
_children.forEach([&](Node* obj){
RGBAProtocol* rgba = dynamic_cast<RGBAProtocol*>(obj);
if (rgba)
{
pNode->setOpacityModifyRGB(bOpacityModifyRGB);
rgba->setOpacityModifyRGB(bOpacityModifyRGB);
}
}
});
}
bool Control::isOpacityModifyRGB() const

View File

@ -341,7 +341,7 @@ bool Scale9Sprite::updateWithBatchNode(SpriteBatchNode* batchnode, const Rect& o
_scale9Image->addChild(_top, 1, pTop);
// Bottom
_bottom = Sprite::Sprite::createWithTexture(_scale9Image->getTexture(), rotatedcenterbottombounds, true);
_bottom = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedcenterbottombounds, true);
_bottom->retain();
_scale9Image->addChild(_bottom, 1, pBottom);
@ -699,17 +699,16 @@ void Scale9Sprite::setOpacityModifyRGB(bool var)
return;
}
_opacityModifyRGB = var;
Object* child;
Array* children = _scale9Image->getChildren();
CCARRAY_FOREACH(children, child)
{
RGBAProtocol* pNode = dynamic_cast<RGBAProtocol*>(child);
if (pNode)
_scale9Image->getChildren().forEach([this](Node* child){
RGBAProtocol* rgba = dynamic_cast<RGBAProtocol*>(child);
if (rgba)
{
pNode->setOpacityModifyRGB(_opacityModifyRGB);
rgba->setOpacityModifyRGB(_opacityModifyRGB);
}
}
});
}
bool Scale9Sprite::isOpacityModifyRGB() const
{
return _opacityModifyRGB;
@ -789,16 +788,14 @@ void Scale9Sprite::setColor(const Color3B& color)
}
NodeRGBA::setColor(color);
Object* child;
Array* children = _scale9Image->getChildren();
CCARRAY_FOREACH(children, child)
{
RGBAProtocol* pNode = dynamic_cast<RGBAProtocol*>(child);
if (pNode)
_scale9Image->getChildren().forEach([&color](Node* child){
RGBAProtocol* rgba = dynamic_cast<RGBAProtocol*>(child);
if (rgba)
{
pNode->setColor(color);
rgba->setColor(color);
}
}
});
}
const Color3B& Scale9Sprite::getColor() const
@ -813,16 +810,14 @@ void Scale9Sprite::setOpacity(GLubyte opacity)
return;
}
NodeRGBA::setOpacity(opacity);
Object* child;
Array* children = _scale9Image->getChildren();
CCARRAY_FOREACH(children, child)
{
RGBAProtocol* pNode = dynamic_cast<RGBAProtocol*>(child);
if (pNode)
_scale9Image->getChildren().forEach([&opacity](Node* child){
RGBAProtocol* rgba = dynamic_cast<RGBAProtocol*>(child);
if (rgba)
{
pNode->setOpacity(opacity);
rgba->setOpacity(opacity);
}
}
});
}
GLubyte Scale9Sprite::getOpacity() const
@ -837,16 +832,14 @@ void Scale9Sprite::updateDisplayedColor(const cocos2d::Color3B &parentColor)
return;
}
NodeRGBA::updateDisplayedColor(parentColor);
Object* child;
Array* children = _scale9Image->getChildren();
CCARRAY_FOREACH(children, child)
{
RGBAProtocol* pNode = dynamic_cast<RGBAProtocol*>(child);
if (pNode)
_scale9Image->getChildren().forEach([&parentColor](Node* child){
RGBAProtocol* rgba = dynamic_cast<RGBAProtocol*>(child);
if (rgba)
{
pNode->updateDisplayedColor(parentColor);
rgba->updateDisplayedColor(parentColor);
}
}
});
}
void Scale9Sprite::updateDisplayedOpacity(GLubyte parentOpacity)
@ -856,16 +849,14 @@ void Scale9Sprite::updateDisplayedOpacity(GLubyte parentOpacity)
return;
}
NodeRGBA::updateDisplayedOpacity(parentOpacity);
Object* child;
Array* children = _scale9Image->getChildren();
CCARRAY_FOREACH(children, child)
{
RGBAProtocol* pNode = dynamic_cast<RGBAProtocol*>(child);
if (pNode)
_scale9Image->getChildren().forEach([&parentOpacity](Node* child){
RGBAProtocol* rgba = dynamic_cast<RGBAProtocol*>(child);
if (rgba)
{
pNode->updateDisplayedOpacity(parentOpacity);
rgba->updateDisplayedOpacity(parentOpacity);
}
}
});
}
NS_CC_EXT_END

View File

@ -153,26 +153,16 @@ void ScrollView::pause(Object* sender)
{
_container->pause();
Object* pObj = NULL;
Array* pChildren = _container->getChildren();
CCARRAY_FOREACH(pChildren, pObj)
{
Node* pChild = static_cast<Node*>(pObj);
pChild->pause();
}
_container->getChildren().forEach([](Node* child){
child->pause();
});
}
void ScrollView::resume(Object* sender)
{
Object* pObj = NULL;
Array* pChildren = _container->getChildren();
CCARRAY_FOREACH(pChildren, pObj)
{
Node* pChild = static_cast<Node*>(pObj);
pChild->resume();
}
_container->getChildren().forEach([](Node* child){
child->resume();
});
_container->resume();
}
@ -567,14 +557,14 @@ void ScrollView::visit()
this->transform();
this->beforeDraw();
if(_children)
if (!_children.empty())
{
int i=0;
// draw children zOrder < 0
for( ; i < _children->count(); i++ )
for( ; i < _children.size(); i++ )
{
Node *child = static_cast<Node*>( _children->getObjectAtIndex(i) );
Node *child = _children.at(i);
if ( child->getZOrder() < 0 )
{
child->visit();
@ -589,9 +579,9 @@ void ScrollView::visit()
this->draw();
// draw children zOrder >= 0
for( ; i < _children->count(); i++ )
for( ; i < _children.size(); i++ )
{
Node *child = static_cast<Node*>( _children->getObjectAtIndex(i) );
Node *child = _children.at(i);
child->visit();
}

View File

@ -47,15 +47,10 @@ void Bug422Layer::reset()
void Bug422Layer::check(Node* t)
{
auto array = t->getChildren();
Object* pChild = NULL;
CCARRAY_FOREACH(array, pChild)
{
CC_BREAK_IF(! pChild);
auto node = static_cast<Node*>(pChild);
log("%p, rc: %d", node, node->retainCount());
check(node);
}
t->getChildren().forEach([this](Node* child){
log("%p, rc: %d", child, child->retainCount());
check(child);
});
}
void Bug422Layer::menuCallback(Object* sender)

View File

@ -233,13 +233,12 @@ void TestFilenameLookup::onEnter()
auto sharedFileUtils = FileUtils::getInstance();
auto dict = Dictionary::create();
dict->setObject(String::create("Images/grossini.png"), "grossini.bmp");
dict->setObject(String::create("Images/grossini.png"), "grossini.xcf");
ValueMap dict;
dict["grossini.bmp"] = Value("Images/grossini.png");
dict["grossini.xcf"] = Value("Images/grossini.png");
sharedFileUtils->setFilenameLookupDictionary(dict);
// Instead of loading carlitos.xcf, it will load grossini.png
auto sprite = Sprite::create("grossini.xcf");
this->addChild(sprite);
@ -254,7 +253,7 @@ void TestFilenameLookup::onExit()
FileUtils *sharedFileUtils = FileUtils::getInstance();
// reset filename lookup
sharedFileUtils->setFilenameLookupDictionary(Dictionary::create());
sharedFileUtils->setFilenameLookupDictionary(ValueMap());
FileUtilsDemo::onExit();
}
@ -298,7 +297,7 @@ void TestIsFileExist::onExit()
FileUtils *sharedFileUtils = FileUtils::getInstance();
// reset filename lookup
sharedFileUtils->setFilenameLookupDictionary(Dictionary::create());
sharedFileUtils->setFilenameLookupDictionary(ValueMap());
FileUtilsDemo::onExit();
}

View File

@ -119,13 +119,9 @@ static void setEnableRecursiveCascading(Node* node, bool enable)
rgba->setCascadeOpacityEnabled(enable);
}
Object* obj;
auto children = node->getChildren();
CCARRAY_FOREACH(children, obj)
{
auto child = static_cast<Node*>(obj);
node->getChildren().forEach([enable](Node* child){
setEnableRecursiveCascading(child, enable);
}
});
}
// LayerTestCascadingOpacityA

View File

@ -88,27 +88,18 @@ MenuLayerMainMenu::MenuLayerMainMenu()
auto s = Director::getInstance()->getWinSize();
int i=0;
Node* child;
auto pArray = menu->getChildren();
Object* pObject = NULL;
CCARRAY_FOREACH(pArray, pObject)
{
if(pObject == NULL)
break;
child = static_cast<Node*>(pObject);
menu->getChildren().forEach([&i, &s](Node* child){
auto dstPoint = child->getPosition();
int offset = (int) (s.width/2 + 50);
if( i % 2 == 0)
offset = -offset;
child->setPosition( Point( dstPoint.x + offset, dstPoint.y) );
child->runAction(
EaseElasticOut::create(MoveBy::create(2, Point(dstPoint.x - offset,0)), 0.35f)
);
child->runAction(
EaseElasticOut::create(MoveBy::create(2, Point(dstPoint.x - offset,0)), 0.35f)
);
i++;
}
});
_disabledItem = item3; item3->retain();
_disabledItem->setEnabled( false );
@ -406,15 +397,10 @@ MenuLayer4::MenuLayer4()
MenuItemFont::create( "Off" ),
NULL );
//auto more_items = UxArray::arrayWithObjects(
// MenuItemFont::create( "33%" ),
// MenuItemFont::create( "66%" ),
// MenuItemFont::create( "100%" ),
// NULL );
// TIP: you can manipulate the items like any other MutableArray
item4->getSubItems()->addObject( MenuItemFont::create( "33%" ) );
item4->getSubItems()->addObject( MenuItemFont::create( "66%" ) );
item4->getSubItems()->addObject( MenuItemFont::create( "100%" ) );
item4->getSubItems().pushBack( MenuItemFont::create( "33%" ) );
item4->getSubItems().pushBack( MenuItemFont::create( "66%" ) );
item4->getSubItems().pushBack( MenuItemFont::create( "100%" ) );
// you can change the one of the items by doing this
item4->setSelectedIndex( 2 );

View File

@ -1528,17 +1528,16 @@ void MultipleParticleSystems::update(float dt)
{
auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount);
unsigned int count = 0;
Object* pObj = NULL;
CCARRAY_FOREACH(getChildren(), pObj)
{
auto item = dynamic_cast<ParticleSystem*>(pObj);
unsigned int count = 0;
getChildren().forEach([&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child);
if (item != NULL)
{
count += item->getParticleCount();
}
}
});
char str[100] = {0};
sprintf(str, "%4d", count);
atlas->setString(str);
@ -1582,15 +1581,15 @@ void MultipleParticleSystemsBatched::update(float dt)
unsigned count = 0;
auto batchNode = getChildByTag(2);
Object* pObj = NULL;
CCARRAY_FOREACH(batchNode->getChildren(), pObj)
{
auto item = dynamic_cast<ParticleSystem*>(pObj);
batchNode->getChildren().forEach([&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child);
if (item != NULL)
{
count += item->getParticleCount();
}
}
});
char str[50] = {0};
sprintf(str, "%4d", count);
atlas->setString(str);
@ -1643,12 +1642,12 @@ void AddAndDeleteParticleSystems::onEnter()
void AddAndDeleteParticleSystems::removeSystem(float dt)
{
int nChildrenCount = _batchNode->getChildren()->count();
if (nChildrenCount > 0)
int nChildrenCount = _batchNode->getChildren().size();
if (nChildrenCount > 0)
{
CCLOG("remove random system");
unsigned int uRand = rand() % (nChildrenCount - 1);
_batchNode->removeChild((Node*)_batchNode->getChildren()->getObjectAtIndex(uRand), true);
_batchNode->removeChild(_batchNode->getChildren().at(uRand), true);
auto particleSystem = ParticleSystemQuad::create("Particles/Spiral.plist");
//add new
@ -1671,15 +1670,15 @@ void AddAndDeleteParticleSystems::update(float dt)
unsigned int count = 0;
auto batchNode = getChildByTag(2);
Object* pObj = NULL;
CCARRAY_FOREACH(batchNode->getChildren(), pObj)
{
auto item = dynamic_cast<ParticleSystem*>(pObj);
batchNode->getChildren().forEach([&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child);
if (item != NULL)
{
count += item->getParticleCount();
}
}
});
char str[100] = {0};
sprintf(str, "%4d", count);
atlas->setString(str);
@ -1795,27 +1794,26 @@ void ReorderParticleSystems::onEnter()
void ReorderParticleSystems::reorderSystem(float time)
{
auto system = (ParticleSystem*)_batchNode->getChildren()->getObjectAtIndex(1);
_batchNode->reorderChild(system, system->getZOrder() - 1);
auto system = static_cast<ParticleSystem*>(_batchNode->getChildren().at(1));
_batchNode->reorderChild(system, system->getZOrder() - 1);
}
void ReorderParticleSystems::update(float dt)
{
auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount);
auto atlas = static_cast<LabelAtlas*>(getChildByTag(kTagParticleCount));
unsigned int count = 0;
auto batchNode = getChildByTag(2);
Object* pObj = NULL;
CCARRAY_FOREACH(batchNode->getChildren(), pObj)
{
auto item = dynamic_cast<ParticleSystem*>(pObj);
if (item != NULL)
batchNode->getChildren().forEach([&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child);
if (item != nullptr)
{
count += item->getParticleCount();
}
}
});
char str[100] = {0};
sprintf(str, "%4d", count);
atlas->setString(str);

View File

@ -287,7 +287,7 @@ void IterateSpriteSheetForLoop::update(float dt)
CC_PROFILER_START(this->profilerName());
for( const auto &object : *children )
for( const auto &object : children )
{
auto o = static_cast<Object*>(object);
auto sprite = static_cast<Sprite*>(o);
@ -325,11 +325,11 @@ void IterateSpriteSheetCArray::update(float dt)
CC_PROFILER_START(this->profilerName());
CCARRAY_FOREACH(children, object)
{
auto sprite = static_cast<Sprite*>(object);
sprite->setVisible(false);
}
//FIXME: James CCARRAY_FOREACH(children, object)
// {
// auto sprite = static_cast<Sprite*>(object);
// sprite->setVisible(false);
// }
CC_PROFILER_STOP(this->profilerName());
}
@ -362,10 +362,9 @@ void IterateSpriteSheetIterator::update(float dt)
CC_PROFILER_START(this->profilerName());
for( auto it=std::begin(*children); it != std::end(*children); ++it)
for( auto it=std::begin(children); it != std::end(children); ++it)
{
auto obj = static_cast<Object*>(*it);
auto sprite = static_cast<Sprite*>(obj);
auto sprite = static_cast<Sprite*>(*it);
sprite->setVisible(false);
}
@ -396,17 +395,17 @@ const char* IterateSpriteSheetIterator::testName()
void CallFuncsSpriteSheetForEach::update(float dt)
{
// iterate using fast enumeration protocol
auto children = batchNode->getChildren();
auto& children = batchNode->getChildren();
CC_PROFILER_START(this->profilerName());
#if CC_USE_ARRAY_VECTOR
std::for_each(std::begin(*children), std::end(*children), [](const RCPtr<Object>& obj) {
std::for_each(std::begin(children), std::end(children), [](const RCPtr<Object>& obj) {
static_cast<Node*>( static_cast<Object*>(obj) )->getPosition();
});
#else
std::for_each(std::begin(*children), std::end(*children), [](Object* obj) {
static_cast<Node*>(obj)->getPosition();
std::for_each(std::begin(children), std::end(children), [](Node* obj) {
obj->getPosition();
});
#endif
@ -437,11 +436,11 @@ const char* CallFuncsSpriteSheetForEach::testName()
void CallFuncsSpriteSheetCMacro::update(float dt)
{
// iterate using fast enumeration protocol
auto children = batchNode->getChildren();
auto& children = batchNode->getChildren();
CC_PROFILER_START(this->profilerName());
arrayMakeObjectsPerformSelector(children, getPosition, Node*);
//FIXME: James arrayMakeObjectsPerformSelector(children, getPosition, Node*);
CC_PROFILER_STOP(this->profilerName());
}

View File

@ -672,9 +672,9 @@ void SchedulerUpdate::onEnter()
void SchedulerUpdate::removeUpdates(float dt)
{
auto children = getChildren();
auto& children = getChildren();
for (auto c : *children)
for (auto& c : children)
{
auto obj = static_cast<Object*>(c);
auto node = static_cast<Node*>(obj);

View File

@ -678,22 +678,17 @@ void ShaderRetroEffect::update(float dt)
{
_accum += dt;
auto pArray = _label->getChildren();
int i=0;
Object* pObj = NULL;
CCARRAY_FOREACH(pArray, pObj)
{
auto sprite = static_cast<Sprite*>(pObj);
_label->getChildren().forEach([&i, this](Node* sprite){
i++;
auto oldPosition = sprite->getPosition();
sprite->setPosition(Point( oldPosition.x, sinf( _accum * 2 + i/2.0) * 20 ));
// add fabs() to prevent negative scaling
float scaleY = ( sinf( _accum * 2 + i/2.0 + 0.707) );
sprite->setScaleY(scaleY);
}
});
}
std::string ShaderRetroEffect::title()

View File

@ -1 +1 @@
d88c60ebf07ab1a9b0db9d032354310878f868a3
e4cdac1cca25440803dbf150fc336b61c44edb93

View File

@ -164,13 +164,13 @@ void KeyboardNotificationLayer::keyboardWillShow(IMEKeyboardNotificationInfo& in
CCLOG("TextInputTest:needAdjustVerticalPosition(%f)", adjustVert);
// move all the children node of KeyboardNotificationLayer
auto children = getChildren();
auto& children = getChildren();
Node * node = 0;
int count = children->count();
int count = children.size();
Point pos;
for (int i = 0; i < count; ++i)
{
node = (Node*)children->getObjectAtIndex(i);
node = children.at(i);
pos = node->getPosition();
pos.y += adjustVert;
node->setPosition(pos);

View File

@ -128,18 +128,12 @@ TMXOrthoTest::TMXOrthoTest()
Size CC_UNUSED s = map->getContentSize();
CCLOG("ContentSize: %f, %f", s.width,s.height);
auto pChildrenArray = map->getChildren();
SpriteBatchNode* child = NULL;
Object* pObject = NULL;
CCARRAY_FOREACH(pChildrenArray, pObject)
{
child = static_cast<SpriteBatchNode*>(pObject);
if(!child)
break;
auto& pChildrenArray = map->getChildren();
pChildrenArray.forEach([](Node* obj){
auto child = static_cast<SpriteBatchNode*>(obj);
child->getTexture()->setAntiAliasTexParameters();
}
});
float x, y, z;
map->getCamera()->getEye(&x, &y, &z);
@ -177,18 +171,13 @@ TMXOrthoTest2::TMXOrthoTest2()
Size CC_UNUSED s = map->getContentSize();
CCLOG("ContentSize: %f, %f", s.width,s.height);
auto pChildrenArray = map->getChildren();
auto& pChildrenArray = map->getChildren();
SpriteBatchNode* child = NULL;
Object* pObject = NULL;
CCARRAY_FOREACH(pChildrenArray, pObject)
{
child = static_cast<SpriteBatchNode*>(pObject);
if(!child)
break;
pChildrenArray.forEach([&child](Node* obj){
child = static_cast<SpriteBatchNode*>(obj);
child->getTexture()->setAntiAliasTexParameters();
}
});
map->runAction( ScaleBy::create(2, 0.5f) ) ;
}
@ -211,18 +200,13 @@ TMXOrthoTest3::TMXOrthoTest3()
Size CC_UNUSED s = map->getContentSize();
CCLOG("ContentSize: %f, %f", s.width,s.height);
auto pChildrenArray = map->getChildren();
auto& children = map->getChildren();
SpriteBatchNode* child = NULL;
Object* pObject = NULL;
CCARRAY_FOREACH(pChildrenArray, pObject)
{
child = static_cast<SpriteBatchNode*>(pObject);
if(!child)
break;
children.forEach([&child](Node* node){
child = static_cast<SpriteBatchNode*>(node);
child->getTexture()->setAntiAliasTexParameters();
}
});
map->setScale(0.2f);
map->setAnchorPoint( Point(0.5f, 0.5f) );
@ -245,19 +229,12 @@ TMXOrthoTest4::TMXOrthoTest4()
Size CC_UNUSED s1 = map->getContentSize();
CCLOG("ContentSize: %f, %f", s1.width,s1.height);
auto pChildrenArray = map->getChildren();
SpriteBatchNode* child = NULL;
Object* pObject = NULL;
CCARRAY_FOREACH(pChildrenArray, pObject)
{
child = static_cast<SpriteBatchNode*>(pObject);
if(!child)
break;
SpriteBatchNode* child = nullptr;
map->getChildren().forEach([&child](Node* node){
child = static_cast<SpriteBatchNode*>(node);
child->getTexture()->setAntiAliasTexParameters();
}
});
map->setAnchorPoint(Point(0, 0));
@ -551,18 +528,11 @@ TMXUncompressedTest::TMXUncompressedTest()
map->runAction(MoveTo::create(1.0f, Point( -ms.width * ts.width/2, -ms.height * ts.height/2 ) ));
// testing release map
auto pChildrenArray = map->getChildren();
TMXLayer* layer;
Object* pObject = NULL;
CCARRAY_FOREACH(pChildrenArray, pObject)
{
layer= static_cast<TMXLayer*>(pObject);
if(!layer)
break;
map->getChildren().forEach([&layer](Node* node){
layer= static_cast<TMXLayer*>(node);
layer->releaseMap();
}
});
}
@ -615,17 +585,11 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest()
////----CCLOG("----> Iterating over all the group objets");
auto group = map->getObjectGroup("Object Group 1");
auto objects = group->getObjects();
auto& objects = group->getObjects();
Dictionary* dict = NULL;
Object* pObj = NULL;
CCARRAY_FOREACH(objects, pObj)
for (auto& obj : objects)
{
dict = static_cast<Dictionary*>(pObj);
if(!dict)
break;
ValueMap& dict = obj.asValueMap();
////----CCLOG("object: %x", dict);
}
@ -639,30 +603,23 @@ void TMXOrthoObjectsTest::draw()
auto map = static_cast<TMXTiledMap*>( getChildByTag(kTagTileMap) );
auto group = map->getObjectGroup("Object Group 1");
auto objects = group->getObjects();
Dictionary* dict = NULL;
Object* pObj = NULL;
CCARRAY_FOREACH(objects, pObj)
auto& objects = group->getObjects();
for (auto& obj : objects)
{
dict = static_cast<Dictionary*>(pObj);
ValueMap& dict = obj.asValueMap();
if(!dict)
break;
const char* key = "x";
int x = ((String*)dict->objectForKey(key))->intValue();
key = "y";
int y = ((String*)dict->objectForKey(key))->intValue();//dynamic_cast<NSNumber*>(dict->objectForKey("y"))->getNumber();
key = "width";
int width = ((String*)dict->objectForKey(key))->intValue();//dynamic_cast<NSNumber*>(dict->objectForKey("width"))->getNumber();
key = "height";
int height = ((String*)dict->objectForKey(key))->intValue();//dynamic_cast<NSNumber*>(dict->objectForKey("height"))->getNumber();
float x = dict["x"].asFloat();
float y = dict["y"].asFloat();
float width = dict["width"].asFloat();
float height = dict["height"].asFloat();
glLineWidth(3);
DrawPrimitives::drawLine( Point((float)x, (float)y), Point((float)(x+width), (float)y) );
DrawPrimitives::drawLine( Point((float)(x+width), (float)y), Point((float)(x+width), (float)(y+height)) );
DrawPrimitives::drawLine( Point((float)(x+width), (float)(y+height)), Point((float)x, (float)(y+height)) );
DrawPrimitives::drawLine( Point((float)x, (float)(y+height)), Point((float)x, (float)y) );
DrawPrimitives::drawLine( Point(x, y), Point((x+width), y) );
DrawPrimitives::drawLine( Point((x+width), y), Point((x+width), (y+height)) );
DrawPrimitives::drawLine( Point((x+width), (y+height)), Point(x, (y+height)) );
DrawPrimitives::drawLine( Point(x, (y+height)), Point(x, y) );
glLineWidth(1);
}
@ -696,16 +653,11 @@ TMXIsoObjectsTest::TMXIsoObjectsTest()
auto group = map->getObjectGroup("Object Group 1");
//auto objects = group->objects();
auto objects = group->getObjects();
auto& objects = group->getObjects();
//UxMutableDictionary<std::string>* dict;
Dictionary* dict;
Object* pObj = NULL;
CCARRAY_FOREACH(objects, pObj)
for (auto& obj : objects)
{
dict = static_cast<Dictionary*>(pObj);
if(!dict)
break;
ValueMap& dict = obj.asValueMap();
////----CCLOG("object: %x", dict);
}
@ -716,23 +668,14 @@ void TMXIsoObjectsTest::draw()
auto map = (TMXTiledMap*) getChildByTag(kTagTileMap);
auto group = map->getObjectGroup("Object Group 1");
auto objects = group->getObjects();
Dictionary* dict;
Object* pObj = NULL;
CCARRAY_FOREACH(objects, pObj)
auto& objects = group->getObjects();
for (auto& obj : objects)
{
dict = static_cast<Dictionary*>(pObj);
if(!dict)
break;
const char* key = "x";
int x = static_cast<String*>(dict->objectForKey(key))->intValue();
key = "y";
int y = static_cast<String*>(dict->objectForKey(key))->intValue();
key = "width";
int width = static_cast<String*>(dict->objectForKey(key))->intValue();
key = "height";
int height = static_cast<String*>(dict->objectForKey(key))->intValue();
ValueMap& dict = obj.asValueMap();
float x = dict["x"].asFloat();
float y = dict["y"].asFloat();
float width = dict["width"].asFloat();
float height = dict["height"].asFloat();
glLineWidth(3);
@ -809,7 +752,7 @@ TMXIsoZorder::TMXIsoZorder()
map->setPosition(Point(-s.width/2,0));
_tamara = Sprite::create(s_pathSister1);
map->addChild(_tamara, map->getChildren()->count() );
map->addChild(_tamara, map->getChildren().size() );
_tamara->retain();
int mapWidth = map->getMapSize().width * map->getTileSize().width;
_tamara->setPosition(CC_POINT_PIXELS_TO_POINTS(Point( mapWidth/2,0)));
@ -877,7 +820,7 @@ TMXOrthoZorder::TMXOrthoZorder()
CCLOG("ContentSize: %f, %f", s.width,s.height);
_tamara = Sprite::create(s_pathSister1);
map->addChild(_tamara, map->getChildren()->count());
map->addChild(_tamara, map->getChildren().size());
_tamara->retain();
_tamara->setAnchorPoint(Point(0.5f,0));
@ -1126,7 +1069,7 @@ TMXTilePropertyTest::TMXTilePropertyTest()
addChild(map ,0 ,kTagTileMap);
for(int i=1;i<=20;i++){
log("GID:%i, Properties:%p", i, map->getPropertiesForGID(i));
log("GID:%i, Properties:%s", i, map->getPropertiesForGID(i).asString().c_str());
}
}
@ -1154,12 +1097,10 @@ TMXOrthoFlipTest::TMXOrthoFlipTest()
Size CC_UNUSED s = map->getContentSize();
log("ContentSize: %f, %f", s.width,s.height);
Object* pObj = NULL;
CCARRAY_FOREACH(map->getChildren(), pObj)
{
auto child = static_cast<SpriteBatchNode*>(pObj);
map->getChildren().forEach([](Node* node){
auto child = static_cast<SpriteBatchNode*>(node);
child->getTexture()->setAntiAliasTexParameters();
}
});
auto action = ScaleBy::create(2, 0.5f);
map->runAction(action);
@ -1184,12 +1125,10 @@ TMXOrthoFlipRunTimeTest::TMXOrthoFlipRunTimeTest()
auto s = map->getContentSize();
log("ContentSize: %f, %f", s.width,s.height);
Object* pObj = NULL;
CCARRAY_FOREACH(map->getChildren(), pObj)
{
auto child = static_cast<SpriteBatchNode*>(pObj);
map->getChildren().forEach([](Node* node){
auto child = static_cast<SpriteBatchNode*>(node);
child->getTexture()->setAntiAliasTexParameters();
}
});
auto action = ScaleBy::create(2, 0.5f);
map->runAction(action);
@ -1263,12 +1202,10 @@ TMXOrthoFromXMLTest::TMXOrthoFromXMLTest()
auto s = map->getContentSize();
log("ContentSize: %f, %f", s.width,s.height);
Object* pObj = NULL;
CCARRAY_FOREACH(map->getChildren(), pObj)
{
auto child = static_cast<SpriteBatchNode*>(pObj);
map->getChildren().forEach([](Node* node){
auto child = static_cast<SpriteBatchNode*>(node);
child->getTexture()->setAntiAliasTexParameters();
}
});
auto action = ScaleBy::create(2, 0.5f);
map->runAction(action);
@ -1292,15 +1229,10 @@ TMXBug987::TMXBug987()
Size CC_UNUSED s1 = map->getContentSize();
CCLOG("ContentSize: %f, %f", s1.width,s1.height);
auto childs = map->getChildren();
TMXLayer* node;
Object* pObject = NULL;
CCARRAY_FOREACH(childs, pObject)
{
node = static_cast<TMXLayer*>(pObject);
CC_BREAK_IF(!node);
map->getChildren().forEach([](Node* child){
auto node = static_cast<TMXLayer*>(child);
node->getTexture()->setAntiAliasTexParameters();
}
});
map->setAnchorPoint(Point(0, 0));
auto layer = map->getLayer("Tile Layer 1");
@ -1520,25 +1452,15 @@ void TMXGIDObjectsTest::draw()
auto map = (TMXTiledMap*)getChildByTag(kTagTileMap);
auto group = map->getObjectGroup("Object Layer 1");
auto array = group->getObjects();
Dictionary* dict;
Object* pObj = NULL;
CCARRAY_FOREACH(array, pObj)
auto& objects = group->getObjects();
for (auto& obj : objects)
{
dict = static_cast<Dictionary*>(pObj);
if(!dict)
{
break;
}
const char* key = "x";
int x = ((String*)dict->objectForKey(key))->intValue();
key = "y";
int y = ((String*)dict->objectForKey(key))->intValue();
key = "width";
int width = ((String*)dict->objectForKey(key))->intValue();
key = "height";
int height = ((String*)dict->objectForKey(key))->intValue();
ValueMap& dict = obj.asValueMap();
float x = dict["x"].asFloat();
float y = dict["y"].asFloat();
float width = dict["width"].asFloat();
float height = dict["height"].asFloat();
glLineWidth(3);

View File

@ -70,7 +70,7 @@
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\network;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\win32\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_USE_PHYSICS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
@ -103,7 +103,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\network;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\win32\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>

View File

@ -28,7 +28,7 @@ if [ "$GEN_JSB"x = "YES"x ]; then
fi
export NDK_ROOT=$HOME/bin/android-ndk
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-jsbindings.sh
# ./generate-jsbindings.sh
elif [ "$PLATFORM"x = "android"x ]; then
export NDK_ROOT=$HOME/bin/android-ndk
@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then
# Build all samples
echo "Building all samples ..."
cd $COCOS2DX_ROOT/build
./android-build.py -n "NDK_BUG=0 -j10" all
./android-build.py -n "NDK_BUG=0 -j10" hellocpp testcpp simplegame
# Build template
# echo "Building template ..."
@ -74,14 +74,14 @@ elif [ "$PLATFORM"x = "linux"x ]; then
cd $COCOS2DX_ROOT/build
mkdir -p linux-build
cd linux-build
cmake ../..
cmake ../.. -DBUILD_LIBS_LUA=OFF -DBUILD_HelloLua=OFF -DBUILD_TestLua=OFF
make -j10
cd ../../template/multi-platform-cpp
cmake .
make -j10
cd ../multi-platform-lua
cmake .
make -j10
# cd ../multi-platform-lua
# cmake .
# make -j10
elif [ "$PLATFORM"x = "emscripten"x ]; then
# Generate binding glue codes