diff --git a/CMakeLists.txt b/CMakeLists.txt index 08c2eddb1f..c68536b314 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,3 +1,28 @@ +#/**************************************************************************** +# Copyright (c) 2013 cocos2d-x.org +# Copyright (c) 2012-2013 martell malone +# +# 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. +# ****************************************************************************/ + cmake_minimum_required(VERSION 2.8) project (Cocos2dx) @@ -170,12 +195,6 @@ if(WIN32) ) endif() - link_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/external/webp/prebuilt/${PLATFORM_FOLDER} - ${CMAKE_CURRENT_SOURCE_DIR}/external/glfw3/prebuilt/${PLATFORM_FOLDER} - ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/gles/prebuilt - ) - elseif(APPLE) else() diff --git a/build/build-mingw32-gcc-make.sh b/build/build-mingw32-gcc-make.sh new file mode 100644 index 0000000000..c7f45347f8 --- /dev/null +++ b/build/build-mingw32-gcc-make.sh @@ -0,0 +1,62 @@ +#!/bin/bash + +# msys2 Pacman Manager for cocos2d-x + +#/**************************************************************************** +# Copyright (c) 2012-2013 Martell Malone +# +# +# 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. +# ****************************************************************************/ + +set -e + +THISDIR="$(dirname $0)" +test "$THISDIR" = "." && THISDIR=${PWD} +OSTYPE=${OSTYPE//[0-9.]/} +HOST_ARCH=$(uname -m) + +if [ "${HOST_ARCH}" = "i686" ]; then + BITS=32 +elif [ "${HOST_ARCH}" = "x86_64" ]; then + BITS=64 +fi + +if [ "${OSTYPE}" = "msys" ]; then + + CC=${HOST_ARCH}-w64-mingw32-gcc + CXX=${HOST_ARCH}-w64-mingw32-g++ + PP=mingw-w64-${HOST_ARCH} + + MINGW_PACKAGES=(glfw glew libwebp libjpeg-turbo libpng freetype libiconv zlib curl + make gcc binutils headers cmake libxml2) + + MINGW_PACKAGES=(${MINGW_PACKAGES[@]/#/${PP}-}) + + pacman -S --force --noconfirm --needed ${MINGW_PACKAGES[@]} + + mkdir -p mingw${BITS} && cd mingw${BITS} + + export PATH=/mingw${BITS}/bin:${PATH} + + cmake -G"MinGW Makefiles" -DCMAKE_MAKE_PROGRAM="mingw32-make" \ + -DCMAKE_C_COMPILER="${CC}" -DCMAKE_CXX_COMPILER="${CXX}" ../.. + + mingw32-make +fi diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 7240f25838..8f1be0f32e 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -4367613b05de13587c6cd0fb07aeef45f44afcfc \ No newline at end of file +42f742346aec806886a8fd399aa42f689cafa71c \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 8f264968c7..81e2a64b39 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -edf83dc058b5630510ac8d327ae8db62ab062cc6 \ No newline at end of file +133130a8ae8d6597399a7de05ba9b63ee55f5e2d \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 854d56829d..8f06c536bb 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -129,8 +129,10 @@ platform/CCThread.cpp \ ../base/CCObject.cpp \ ../base/CCSet.cpp \ ../base/CCString.cpp \ +../base/CCValue.cpp \ ../base/etc1.cpp \ ../base/s3tc.cpp \ +../base/CCConsole.cpp \ ../math/kazmath/src/aabb.c \ ../math/kazmath/src/mat3.c \ ../math/kazmath/src/mat4.c \ diff --git a/cocos/2d/CCAction.cpp b/cocos/2d/CCAction.cpp index 51670c81f9..5e1a080c4e 100644 --- a/cocos/2d/CCAction.cpp +++ b/cocos/2d/CCAction.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "CCActionInterval.h" #include "CCNode.h" #include "CCDirector.h" +#include "CCString.h" NS_CC_BEGIN // diff --git a/cocos/2d/CCActionCatmullRom.cpp b/cocos/2d/CCActionCatmullRom.cpp index 2ae9a2b77d..bab094f288 100644 --- a/cocos/2d/CCActionCatmullRom.cpp +++ b/cocos/2d/CCActionCatmullRom.cpp @@ -43,7 +43,7 @@ NS_CC_BEGIN; * Implementation of PointArray */ -PointArray* PointArray::create(unsigned int capacity) +PointArray* PointArray::create(int capacity) { PointArray* pointArray = new PointArray(); if (pointArray) @@ -63,7 +63,7 @@ PointArray* PointArray::create(unsigned int capacity) } -bool PointArray::initWithCapacity(unsigned int capacity) +bool PointArray::initWithCapacity(int capacity) { _controlPoints = new vector(); @@ -126,19 +126,19 @@ void PointArray::addControlPoint(Point controlPoint) _controlPoints->push_back(new Point(controlPoint.x, controlPoint.y)); } -void PointArray::insertControlPoint(Point &controlPoint, unsigned int index) +void PointArray::insertControlPoint(Point &controlPoint, int index) { Point *temp = new Point(controlPoint.x, controlPoint.y); _controlPoints->insert(_controlPoints->begin() + index, temp); } -Point PointArray::getControlPointAtIndex(unsigned int index) +Point PointArray::getControlPointAtIndex(int index) { - index = MIN(_controlPoints->size()-1, MAX(index, 0)); + index = static_cast(MIN(_controlPoints->size()-1, MAX(index, 0))); return *(_controlPoints->at(index)); } -void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, unsigned int index) +void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index) { Point *temp = _controlPoints->at(index); @@ -146,7 +146,7 @@ void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, unsigned int temp->y = controlPoint.y; } -void PointArray::removeControlPointAtIndex(unsigned int index) +void PointArray::removeControlPointAtIndex(int index) { vector::iterator iter = _controlPoints->begin() + index; Point* pRemovedPoint = *iter; @@ -154,9 +154,9 @@ void PointArray::removeControlPointAtIndex(unsigned int index) delete pRemovedPoint; } -unsigned int PointArray::count() const +int PointArray::count() const { - return _controlPoints->size(); + return static_cast(_controlPoints->size()); } PointArray* PointArray::reverse() const @@ -177,11 +177,11 @@ PointArray* PointArray::reverse() const void PointArray::reverseInline() { - unsigned long l = _controlPoints->size(); + auto l = _controlPoints->size(); Point *p1 = nullptr; Point *p2 = nullptr; int x, y; - for (unsigned int i = 0; i < l/2; ++i) + for (int i = 0; i < l/2; ++i) { p1 = _controlPoints->at(i); p2 = _controlPoints->at(l-i-1); @@ -291,7 +291,7 @@ CardinalSplineTo* CardinalSplineTo::clone() const void CardinalSplineTo::update(float time) { - unsigned int p; + int p; float lt; // eg. diff --git a/cocos/2d/CCActionCatmullRom.h b/cocos/2d/CCActionCatmullRom.h index 7b4452d1bc..5678407dc0 100644 --- a/cocos/2d/CCActionCatmullRom.h +++ b/cocos/2d/CCActionCatmullRom.h @@ -61,7 +61,7 @@ public: /** creates and initializes a Points array with capacity * @js NA */ - static PointArray* create(unsigned int capacity); + static PointArray* create(int capacity); /** * @js NA @@ -77,7 +77,7 @@ public: /** initializes a Catmull Rom config with a capacity hint * @js NA */ - bool initWithCapacity(unsigned int capacity); + bool initWithCapacity(int capacity); /** appends a control point * @js NA @@ -87,27 +87,27 @@ public: /** inserts a controlPoint at index * @js NA */ - void insertControlPoint(Point &controlPoint, unsigned int index); + void insertControlPoint(Point &controlPoint, int index); /** replaces an existing controlPoint at index * @js NA */ - void replaceControlPoint(Point &controlPoint, unsigned int index); + void replaceControlPoint(Point &controlPoint, int index); /** get the value of a controlPoint at a given index * @js NA */ - Point getControlPointAtIndex(unsigned int index); + Point getControlPointAtIndex(int index); /** deletes a control point at a given index * @js NA */ - void removeControlPointAtIndex(unsigned int index); + void removeControlPointAtIndex(int index); /** returns the number of objects of the control point array * @js NA */ - unsigned int count() const; + int count() const; /** returns a new copy of the array reversed. User is responsible for releasing this copy * @js NA diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index a2ae6b7824..9aca314728 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -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& arrayOfActions) { Sequence* pRet = NULL; do { - long count = arrayOfActions->count(); + auto count = arrayOfActions.size(); CC_BREAK_IF(count == 0); - FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); + auto prev = arrayOfActions.at(0); if (count > 1) { - for (long i = 1; i < count; ++i) + for (int i = 1; i < count; ++i) { - prev = createWithTwoActions(prev, static_cast(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& arrayOfActions) { Spawn* pRet = NULL; do { - long count = arrayOfActions->count(); + auto count = arrayOfActions.size(); CC_BREAK_IF(count == 0); - FiniteTimeAction* prev = static_cast(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(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(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(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(); + auto 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(frames->getObjectAtIndex(i)); + AnimationFrame* frame = frames.at(i); frameToDisplay = frame->getSpriteFrame(); static_cast(_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 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(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); } diff --git a/cocos/2d/CCActionInterval.h b/cocos/2d/CCActionInterval.h index a72327e997..36306e2939 100644 --- a/cocos/2d/CCActionInterval.h +++ b/cocos/2d/CCActionInterval.h @@ -32,6 +32,7 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCSpriteFrame.h" #include "CCAnimation.h" +#include #include 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& 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& arrayOfActions); /** creates the Spawn action */ static Spawn* createWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index dd2b528bce..02ea7bb2dc 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -40,7 +40,7 @@ NS_CC_BEGIN typedef struct _hashElement { struct _ccArray *actions; - Object *target; + Node *target; int actionIndex; Action *currentAction; bool currentActionSalvaged; @@ -87,7 +87,7 @@ void ActionManager::actionAllocWithHashElement(tHashElement *element) } -void ActionManager::removeActionAtIndex(long index, tHashElement *element) +void ActionManager::removeActionAtIndex(int index, tHashElement *element) { Action *action = (Action*)element->actions->arr[index]; @@ -120,7 +120,7 @@ void ActionManager::removeActionAtIndex(long index, tHashElement *element) // pause / resume -void ActionManager::pauseTarget(Object *target) +void ActionManager::pauseTarget(Node *target) { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); @@ -130,7 +130,7 @@ void ActionManager::pauseTarget(Object *target) } } -void ActionManager::resumeTarget(Object *target) +void ActionManager::resumeTarget(Node *target) { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); @@ -140,30 +140,27 @@ void ActionManager::resumeTarget(Object *target) } } -Set* ActionManager::pauseAllRunningActions() +Vector ActionManager::pauseAllRunningActions() { - Set *idsWithActions = new Set(); - idsWithActions->autorelease(); + Vector idsWithActions; for (tHashElement *element=_targets; element != NULL; element = (tHashElement *)element->hh.next) { if (! element->paused) { element->paused = true; - idsWithActions->addObject(element->target); + idsWithActions.pushBack(element->target); } } - return idsWithActions; + return std::move(idsWithActions); } -void ActionManager::resumeTargets(cocos2d::Set *targetsToResume) -{ - SetIterator iter; - for (iter = targetsToResume->begin(); iter != targetsToResume->end(); ++iter) - { - resumeTarget(*iter); - } +void ActionManager::resumeTargets(const Vector& targetsToResume) +{ + targetsToResume.forEach([this](Node* node){ + this->resumeTarget(node); + }); } // run @@ -196,17 +193,17 @@ void ActionManager::addAction(Action *action, Node *target, bool paused) // remove -void ActionManager::removeAllActions(void) +void ActionManager::removeAllActions() { for (tHashElement *element = _targets; element != NULL; ) { - Object *target = element->target; + auto target = element->target; element = (tHashElement*)element->hh.next; removeAllActionsFromTarget(target); } } -void ActionManager::removeAllActionsFromTarget(Object *target) +void ActionManager::removeAllActionsFromTarget(Node *target) { // explicit null handling if (target == NULL) @@ -253,7 +250,7 @@ void ActionManager::removeAction(Action *action) HASH_FIND_PTR(_targets, &target, element); if (element) { - long i = ccArrayGetIndexOfObject(element->actions, action); + auto i = ccArrayGetIndexOfObject(element->actions, action); if (i != CC_INVALID_INDEX) { removeActionAtIndex(i, element); @@ -265,7 +262,7 @@ void ActionManager::removeAction(Action *action) } } -void ActionManager::removeActionByTag(int tag, Object *target) +void ActionManager::removeActionByTag(int tag, Node *target) { CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(target != NULL, ""); @@ -275,8 +272,8 @@ void ActionManager::removeActionByTag(int tag, Object *target) if (element) { - long limit = element->actions->num; - for (long i = 0; i < limit; ++i) + auto limit = element->actions->num; + for (int i = 0; i < limit; ++i) { Action *action = (Action*)element->actions->arr[i]; @@ -293,7 +290,7 @@ void ActionManager::removeActionByTag(int tag, Object *target) // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference -Action* ActionManager::getActionByTag(int tag, const Object *target) const +Action* ActionManager::getActionByTag(int tag, const Node *target) const { CCASSERT(tag != Action::INVALID_TAG, ""); @@ -304,8 +301,8 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const { if (element->actions != NULL) { - long limit = element->actions->num; - for (long i = 0; i < limit; ++i) + auto limit = element->actions->num; + for (int i = 0; i < limit; ++i) { Action *action = (Action*)element->actions->arr[i]; @@ -327,7 +324,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference -long ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const +int ActionManager::getNumberOfRunningActionsInTarget(const Node *target) const { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 8a2c077511..a2fc0dcfb9 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -29,13 +29,11 @@ THE SOFTWARE. #define __ACTION_CCACTION_MANAGER_H__ #include "CCAction.h" -#include "CCArray.h" +#include "CCVector.h" #include "CCObject.h" NS_CC_BEGIN -class Set; - struct _hashElement; /** @@ -78,55 +76,55 @@ public: /** Removes all actions from all the targets. */ - void removeAllActions(void); + void removeAllActions(); /** Removes all actions from a certain target. All the actions that belongs to the target will be removed. */ - void removeAllActionsFromTarget(Object *target); + void removeAllActionsFromTarget(Node *target); /** Removes an action given an action reference. */ void removeAction(Action *pAction); /** Removes an action given its tag and the target */ - void removeActionByTag(int tag, Object *target); + void removeActionByTag(int tag, Node *target); /** Gets an action given its tag an a target @return the Action the with the given tag */ - Action* getActionByTag(int tag, const Object *target) const; + Action* getActionByTag(int tag, const Node *target) const; /** Returns the numbers of actions that are running in a certain target. * Composable actions are counted as 1 action. Example: * - If you are running 1 Sequence of 7 actions, it will return 1. * - If you are running 7 Sequences of 2 actions, it will return 7. */ - long getNumberOfRunningActionsInTarget(const Object *target) const; + int getNumberOfRunningActionsInTarget(const Node *target) const; /** @deprecated use getNumberOfRunningActionsInTarget() instead */ - CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); } + CC_DEPRECATED_ATTRIBUTE inline int numberOfRunningActionsInTarget(Node *target) const { return getNumberOfRunningActionsInTarget(target); } /** Pauses the target: all running actions and newly added actions will be paused. */ - void pauseTarget(Object *target); + void pauseTarget(Node *target); /** Resumes the target. All queued actions will be resumed. */ - void resumeTarget(Object *target); + void resumeTarget(Node *target); /** Pauses all running actions, returning a list of targets whose actions were paused. */ - Set* pauseAllRunningActions(); + Vector pauseAllRunningActions(); /** Resume a set of targets (convenience function to reverse a pauseAllRunningActions call) */ - void resumeTargets(Set *targetsToResume); + void resumeTargets(const Vector& targetsToResume); protected: // declared in ActionManager.m - void removeActionAtIndex(long index, struct _hashElement *pElement); + void removeActionAtIndex(int index, struct _hashElement *pElement); void deleteHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *pElement); void update(float dt); diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index fad60c6533..1f742cf6db 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -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& 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& 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& 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(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& 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(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++; diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 13cf3b1fdc..99fae8882d 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -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 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& 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& 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& getFrames() const { return _frames; }; /** Sets the array of AnimationFrames */ - void setFrames(Array* frames) + void setFrames(const Vector& 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& arrayOfSpriteFrameNames, float delay = 0.0f); + + /** Initializes a Animation with AnimationFrame + @since v2.0 + */ + bool initWithAnimationFrames(const Vector& 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 _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 diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index a2c0fa9303..2c528f0320 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -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(element->getObject()); - Array* frameNames = static_cast(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 frames(static_cast(frameNames.size())); - Object* pObj = NULL; - CCARRAY_FOREACH(frameNames, pObj) + for (auto& frameName : frameNames) { - const std::string& frameName = static_cast(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(element->getObject()); + std::string name = iter->first; + ValueMap& animationDict = const_cast(iter->second.asValueMap()); - const String* loops = animationDict->valueForKey("loops"); - bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue(); + const Value& loops = animationDict["loops"]; + bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].asBool(); - Array* frameArray = static_cast(animationDict->objectForKey("frames")); + ValueVector& frameArray = animationDict["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 array(static_cast(frameArray.size())); - Object* pObj = NULL; - CCARRAY_FOREACH(frameArray, pObj) + for (auto& obj : frameArray) { - Dictionary* entry = static_cast(pObj); - - const char* spriteFrameName = entry->valueForKey("spriteframe")->getCString(); + ValueMap& entry = obj.asValueMap(); + std::string spriteFrameName = entry["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["delayUnits"].asFloat(); + Value& userInfo = entry["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["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(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); } diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index 475c16ce87..cfc48ababb 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -27,8 +27,8 @@ THE SOFTWARE. #define __CC_ANIMATION_CACHE_H__ #include "CCObject.h" -#include "CCDictionary.h" - +#include "CCMap.h" +#include "CCValue.h" #include 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 _animations; static AnimationCache* s_pSharedAnimationCache; }; diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index b756a36193..44c73d3149 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -61,7 +61,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) +AtlasNode * AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) { AtlasNode * pRet = new AtlasNode(); if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -73,14 +73,14 @@ AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tile return NULL; } -bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) +bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) { CCASSERT(tile.size() > 0, "file size should not be empty"); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(tile); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); } -bool AtlasNode::initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender) +bool AtlasNode::initWithTexture(Texture2D* texture, int tileWidth, int tileHeight, int itemsToRender) { _itemWidth = tileWidth; _itemHeight = tileHeight; @@ -245,12 +245,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const return _textureAtlas; } -long AtlasNode::getQuadsToDraw() const +int AtlasNode::getQuadsToDraw() const { return _quadsToDraw; } -void AtlasNode::setQuadsToDraw(long uQuadsToDraw) +void AtlasNode::setQuadsToDraw(int uQuadsToDraw) { _quadsToDraw = uQuadsToDraw; } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index b196f45a1d..676458360e 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -52,7 +52,7 @@ class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol { public: /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - static AtlasNode * create(const std::string& filename, long tileWidth, long tileHeight, long itemsToRender); + static AtlasNode * create(const std::string& filename, int tileWidth, int tileHeight, int itemsToRender); /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses @@ -62,8 +62,8 @@ public: void setTextureAtlas(TextureAtlas* textureAtlas); TextureAtlas* getTextureAtlas() const; - void setQuadsToDraw(long quadsToDraw); - long getQuadsToDraw() const; + void setQuadsToDraw(int quadsToDraw); + int getQuadsToDraw() const; // Overrides @@ -95,10 +95,10 @@ protected: virtual ~AtlasNode(); /** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - bool initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender); + bool initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender); /** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/ - bool initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender); + bool initWithTexture(Texture2D* texture, int tileWidth, int tileHeight, int itemsToRender); void calculateMaxItems(); void updateBlendFunc(); @@ -108,14 +108,14 @@ protected: void setIgnoreContentScaleFactor(bool bIgnoreContentScaleFactor); //! chars per row - long _itemsPerRow; + int _itemsPerRow; //! chars per column - long _itemsPerColumn; + int _itemsPerColumn; //! width of each char - long _itemWidth; + int _itemWidth; //! height of each char - long _itemHeight; + int _itemHeight; Color3B _colorUnmodified; @@ -125,7 +125,7 @@ protected: BlendFunc _blendFunc; // quads to draw - long _quadsToDraw; + int _quadsToDraw; // color uniform GLint _uniformColor; // This varible is only used for LabelAtlas FPS display. So plz don't modify its value. diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index d51fcc5002..710eb3003f 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -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(pObj), p); - } + n->getChildren().forEach([p](Node* child){ + setProgram(child, p); + }); } ClippingNode::ClippingNode() diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index 323be9f642..bae29435be 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -540,8 +540,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Bool CCBool; CC_DEPRECATED_ATTRIBUTE typedef Float CCFloat; CC_DEPRECATED_ATTRIBUTE typedef Double CCDouble; CC_DEPRECATED_ATTRIBUTE typedef Data CCData; -CC_DEPRECATED_ATTRIBUTE typedef Set CCSet; -CC_DEPRECATED_ATTRIBUTE typedef Array CCArray; CC_DEPRECATED_ATTRIBUTE typedef Dictionary CCDictionary; CC_DEPRECATED_ATTRIBUTE typedef DataVisitor CCDataVisitor; CC_DEPRECATED_ATTRIBUTE typedef PrettyPrinter CCPrettyPrinter; @@ -549,7 +547,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Acceleration CCAcceleration; CC_DEPRECATED_ATTRIBUTE typedef TextureAtlas CCTextureAtlas; CC_DEPRECATED_ATTRIBUTE typedef Configuration CCConfiguration; CC_DEPRECATED_ATTRIBUTE typedef PointArray CCPointArray; -CC_DEPRECATED_ATTRIBUTE typedef SetIterator CCSetIterator; CC_DEPRECATED_ATTRIBUTE typedef RemoveSelf CCRemoveSelf; CC_DEPRECATED_ATTRIBUTE typedef IMEDelegate CCIMEDelegate; CC_DEPRECATED_ATTRIBUTE typedef IMEKeyboardNotificationInfo CCIMEKeyboardNotificationInfo; @@ -568,7 +565,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Speed CCSpeed; CC_DEPRECATED_ATTRIBUTE typedef Follow CCFollow; CC_DEPRECATED_ATTRIBUTE typedef GLProgram CCGLProgram; CC_DEPRECATED_ATTRIBUTE typedef Touch CCTouch; -CC_DEPRECATED_ATTRIBUTE typedef Set CCSet; CC_DEPRECATED_ATTRIBUTE typedef Texture2D CCTexture2D; CC_DEPRECATED_ATTRIBUTE typedef Node CCNode; CC_DEPRECATED_ATTRIBUTE typedef NodeRGBA CCNodeRGBA; @@ -1028,6 +1024,12 @@ CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBindVAO(GLuint vaoId) { GL::bindV CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLEnable( int flags ) { /* ignore */ }; CC_DEPRECATED_ATTRIBUTE typedef int ccGLServerState; +CC_DEPRECATED_ATTRIBUTE typedef __Set CCSet; +CC_DEPRECATED_ATTRIBUTE typedef __SetIterator CCSetIterator; +CC_DEPRECATED_ATTRIBUTE typedef __Set Set; +CC_DEPRECATED_ATTRIBUTE typedef __SetIterator SetIterator; + + NS_CC_END diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 36f72c81c5..cd029d737f 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -110,8 +110,7 @@ bool Director::init(void) _notificationNode = nullptr; - _scenesStack = new Array(); - _scenesStack->initWithCapacity(15); + _scenesStack.reserve(15); // projection delegate if "Custom" projection is used _projectionDelegate = nullptr; @@ -164,7 +163,6 @@ Director::~Director(void) CC_SAFE_RELEASE(_runningScene); CC_SAFE_RELEASE(_notificationNode); - CC_SAFE_RELEASE(_scenesStack); CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_eventDispatcher); @@ -597,10 +595,10 @@ void Director::replaceScene(Scene *scene) CCASSERT(_runningScene, "Use runWithScene: instead to start the director"); CCASSERT(scene != nullptr, "the scene should not be null"); - unsigned int index = _scenesStack->count(); + int index = _scenesStack.size(); _sendCleanupToScene = true; - _scenesStack->replaceObjectAtIndex(index - 1, scene); + _scenesStack.replace(index - 1, scene); _nextScene = scene; } @@ -611,7 +609,7 @@ void Director::pushScene(Scene *scene) _sendCleanupToScene = false; - _scenesStack->addObject(scene); + _scenesStack.pushBack(scene); _nextScene = scene; } @@ -619,8 +617,8 @@ void Director::popScene(void) { CCASSERT(_runningScene != nullptr, "running scene should not null"); - _scenesStack->removeLastObject(); - unsigned int c = _scenesStack->count(); + _scenesStack.popBack(); + int c = _scenesStack.size(); if (c == 0) { @@ -629,7 +627,7 @@ void Director::popScene(void) else { _sendCleanupToScene = true; - _nextScene = (Scene*)_scenesStack->getObjectAtIndex(c - 1); + _nextScene = _scenesStack.at(c - 1); } } @@ -641,7 +639,7 @@ void Director::popToRootScene(void) void Director::popToSceneStackLevel(int level) { CCASSERT(_runningScene != nullptr, "A running Scene is needed"); - int c = static_cast(_scenesStack->count()); + int c = _scenesStack.size(); // level 0? -> end if (level == 0) @@ -657,7 +655,7 @@ void Director::popToSceneStackLevel(int level) // pop stack until reaching desired level while (c > level) { - Scene *current = (Scene*)_scenesStack->getLastObject(); + auto current = _scenesStack.back(); if (current->isRunning()) { @@ -666,11 +664,11 @@ void Director::popToSceneStackLevel(int level) } current->cleanup(); - _scenesStack->removeLastObject(); + _scenesStack.popBack(); --c; } - _nextScene = (Scene*)_scenesStack->getLastObject(); + _nextScene = _scenesStack.back(); _sendCleanupToScene = false; } @@ -701,7 +699,7 @@ void Director::purgeDirector() // remove all objects, but don't release it. // runWithScene might be executed after 'end'. - _scenesStack->removeAllObjects(); + _scenesStack.clear(); stopAnimation(); @@ -857,7 +855,7 @@ void Director::calculateMPF() } // returns the FPS image data pointer and len -void Director::getFPSImageData(unsigned char** datapointer, long* length) +void Director::getFPSImageData(unsigned char** datapointer, ssize_t* length) { // XXX fixed me if it should be used *datapointer = cc_fps_images_png; @@ -880,7 +878,7 @@ void Director::createStatsLabel() Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); unsigned char *data = nullptr; - long dataLength = 0; + ssize_t dataLength = 0; getFPSImageData(&data, &dataLength); Image* image = new Image(); @@ -1037,9 +1035,6 @@ void DisplayLinkDirector::mainLoop() } else if (! _invalid) { - // invoke call back from other thread - ThreadHelper::doCallback(); - drawScene(); // release the objects diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 880117a2a3..78c2a96114 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -32,7 +32,7 @@ THE SOFTWARE. #include "CCObject.h" #include "ccTypes.h" #include "CCGeometry.h" -#include "CCArray.h" +#include "CCVector.h" #include "CCGL.h" #include "kazmath/mat4.h" #include "CCLabelAtlas.h" @@ -379,7 +379,7 @@ protected: void showStats(); void createStatsLabel(); void calculateMPF(); - void getFPSImageData(unsigned char** datapointer, long* length); + void getFPSImageData(unsigned char** datapointer, ssize_t* length); /** calculates delta time since last time it was called */ void calculateDeltaTime(); @@ -446,7 +446,7 @@ protected: bool _sendCleanupToScene; /* scheduled scenes */ - Array* _scenesStack; + Vector _scenesStack; /* last time the main loop was updated */ struct timeval *_lastUpdate; diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 28da2da3e8..4d88845957 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -142,7 +142,7 @@ DrawNode* DrawNode::create() return pRet; } -void DrawNode::ensureCapacity(long count) +void DrawNode::ensureCapacity(int count) { CCASSERT(count>=0, "capacity must be >= 0"); @@ -338,7 +338,7 @@ void DrawNode::drawSegment(const Point &from, const Point &to, float radius, con _dirty = true; } -void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) +void DrawNode::drawPolygon(Point *verts, int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) { CCASSERT(count >= 0, "invalid count value"); @@ -346,7 +346,7 @@ void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, f struct ExtrudeVerts* extrude = (struct ExtrudeVerts*)malloc(sizeof(struct ExtrudeVerts)*count); memset(extrude, 0, sizeof(struct ExtrudeVerts)*count); - for (long i = 0; i < count; i++) + for (int i = 0; i < count; i++) { Vertex2F v0 = __v2f(verts[(i-1+count)%count]); Vertex2F v1 = __v2f(verts[i]); @@ -362,15 +362,15 @@ void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, f bool outline = (borderColor.a > 0.0 && borderWidth > 0.0); - unsigned int triangle_count = 3*count - 2; - unsigned int vertex_count = 3*triangle_count; + auto triangle_count = 3*count - 2; + auto vertex_count = 3*triangle_count; ensureCapacity(vertex_count); V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount); V2F_C4B_T2F_Triangle *cursor = triangles; float inset = (outline == false ? 0.5 : 0.0); - for (long i = 0; i < count-2; i++) + for (int i = 0; i < count-2; i++) { Vertex2F v0 = v2fsub(__v2f(verts[0 ]), v2fmult(extrude[0 ].offset, inset)); Vertex2F v1 = v2fsub(__v2f(verts[i+1]), v2fmult(extrude[i+1].offset, inset)); @@ -385,9 +385,9 @@ void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, f *cursor++ = tmp; } - for(long i = 0; i < count; i++) + for(int i = 0; i < count; i++) { - long j = (i+1)%count; + int j = (i+1)%count; Vertex2F v0 = __v2f(verts[i]); Vertex2F v1 = __v2f(verts[j]); diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 7636cf7326..38f899fc72 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -60,7 +60,7 @@ public: * In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor) * @endcode */ - void drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); + void drawPolygon(Point *verts, int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); /** Clear the geometry in the node's buffer. */ void clear(); @@ -92,13 +92,13 @@ protected: virtual ~DrawNode(); virtual bool init(); - void ensureCapacity(long count); + void ensureCapacity(int count); void render(); GLuint _vao; GLuint _vbo; - long _bufferCapacity; + int _bufferCapacity; GLsizei _bufferCount; V2F_C4B_T2F *_buffer; diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 3387e8b3bf..fbbe534cde 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -190,17 +190,17 @@ EventDispatcher::~EventDispatcher() void EventDispatcher::visitTarget(Node* node) { int i = 0; - Array* children = node->getChildren(); - int childrenCount = children ? children->count() : 0; + auto& children = node->getChildren(); + + auto childrenCount = children.size(); if(childrenCount > 0) { - Node* child = nullptr; // visit children zOrder < 0 for( ; i < childrenCount; i++ ) { - child = static_cast( 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( children->getObjectAtIndex(i) ); + child = children.at(i); if (child) visitTarget(child); } @@ -491,7 +491,7 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); - long i = 0; + int i = 0; // priority < 0 if (fixedPriorityListeners) { @@ -527,7 +527,7 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s if (!shouldStopPropagation) { // priority > 0 - for (; i < static_cast(fixedPriorityListeners->size()); ++i) + for (; i < fixedPriorityListeners->size(); ++i) { auto l = fixedPriorityListeners->at(i); @@ -976,7 +976,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerI }); // FIXME: Should use binary search - long index = 0; + int index = 0; for (auto& listener : *fixedlisteners) { if (listener->getFixedPriority() >= 0) @@ -1080,7 +1080,7 @@ void EventDispatcher::removeCustomEventListeners(const std::string& customEventN void EventDispatcher::removeAllEventListeners() { - std::vector types(_listeners.size()); + std::vector types(_listeners.size()); for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) { diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index c6127135f2..b8b1aa8efb 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -136,12 +136,12 @@ private: inline std::vector* getFixedPriorityListeners() const { return _fixedListeners; }; inline std::vector* getSceneGraphPriorityListeners() const { return _sceneGraphListeners; }; - inline long getGt0Index() const { return _gt0Index; }; - inline void setGt0Index(long index) { _gt0Index = index; }; + inline int getGt0Index() const { return _gt0Index; }; + inline void setGt0Index(int index) { _gt0Index = index; }; private: std::vector* _fixedListeners; std::vector* _sceneGraphListeners; - long _gt0Index; + int _gt0Index; }; /** Adds event listener with item */ diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 72f29e13d8..e0b97aa286 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -141,7 +141,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) } float scaleFactor = CC_CONTENT_SCALE_FACTOR(); - int newLetterCount = fontDefs.size(); + size_t newLetterCount = fontDefs.size(); float glyphWidth; for (int i = 0; i < newLetterCount; ++i) { diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 25709c714e..7ea6609f5c 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -149,7 +149,7 @@ FontAtlas * FontFNT::createFontAtlas() if (!_configuration->_fontDefDictionary) return nullptr; - int numGlyphs = _configuration->_characterSet->size(); + size_t numGlyphs = _configuration->_characterSet->size(); if (!numGlyphs) return nullptr; diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 25063eb023..08e8d0304d 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -99,7 +99,7 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) { FT_Face face; - long len = 0; + ssize_t len = 0; _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len); if (!_ttfData) return false; @@ -297,7 +297,7 @@ int FontFreeType::getAdvanceForChar(unsigned short theChar) const return 0; // get to the advance for this glyph - return (_fontRef->glyph->advance.x >> 6); + return (static_cast(_fontRef->glyph->advance.x >> 6)); } int FontFreeType::getBearingXForChar(unsigned short theChar) const @@ -316,7 +316,7 @@ int FontFreeType::getBearingXForChar(unsigned short theChar) const if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT)) return 0; - return (_fontRef->glyph->metrics.horiBearingX >>6); + return (static_cast(_fontRef->glyph->metrics.horiBearingX >>6)); } int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const @@ -346,12 +346,12 @@ int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsign if (FT_Get_Kerning( _fontRef, glyphIndex1, glyphIndex2, FT_KERNING_DEFAULT, &kerning)) return 0; - return (kerning.x >> 6); + return (static_cast(kerning.x >> 6)); } int FontFreeType::getFontMaxHeight() const { - return (_fontRef->size->metrics.height >> 6); + return (static_cast(_fontRef->size->metrics.height >> 6)); } unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index 717277eff8..b99077bbcf 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -113,13 +113,13 @@ bool GridBase::initWithSize(const Size& gridSize) Director *pDirector = Director::getInstance(); Size s = pDirector->getWinSizeInPixels(); - unsigned long POTWide = ccNextPOT((unsigned int)s.width); - unsigned long POTHigh = ccNextPOT((unsigned int)s.height); + auto POTWide = ccNextPOT((unsigned int)s.width); + auto POTHigh = ccNextPOT((unsigned int)s.height); // we only use rgba8888 Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888; - long dataLen = POTWide * POTHigh * 4; + auto dataLen = POTWide * POTHigh * 4; void *data = calloc(dataLen, 1); if (! data) { diff --git a/cocos/2d/CCGrid.h b/cocos/2d/CCGrid.h index 61a8cbbe34..7c5f7e03da 100644 --- a/cocos/2d/CCGrid.h +++ b/cocos/2d/CCGrid.h @@ -95,7 +95,7 @@ public: protected: bool _active; - long _reuseGrid; + int _reuseGrid; Size _gridSize; Texture2D *_texture; Point _step; diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 07b652a897..0310f69cba 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -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( 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( child ); - if (pNode) + RGBAProtocol *pRGBAProtocol = dynamic_cast(child); + if (pRGBAProtocol) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(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( child ); item->updateDisplayedOpacity(_displayedOpacity); - } + }); + V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - int count = _textureAtlas->getTotalQuads(); + auto 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( child ); item->updateDisplayedColor(_displayedColor); - } + }); V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - int count = _textureAtlas->getTotalQuads(); + auto count = _textureAtlas->getTotalQuads(); Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); // special opacity for premultiplied textures diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 4c64ca3418..8ec15a3c1c 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN //CCLabelAtlas - Creation & Init -LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) +LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { LabelAtlas *pRet = new LabelAtlas(); if(pRet && pRet->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) @@ -54,15 +54,15 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& cha return NULL; } -bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) +bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(charMapFile); return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } -bool LabelAtlas::initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap) +bool LabelAtlas::initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) { - if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, string.size())) + if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, static_cast(string.size()))) { _mapStartChar = startCharMap; this->setString(string); @@ -112,7 +112,7 @@ bool LabelAtlas::initWithString(const std::string& theString, const std::string& //CCLabelAtlas - Atlas generation void LabelAtlas::updateAtlasValues() { - size_t n = _string.length(); + auto n = _string.length(); const unsigned char *s = (unsigned char*)_string.c_str(); @@ -127,9 +127,9 @@ void LabelAtlas::updateAtlasValues() itemHeightInPixels = _itemHeight; } - CCASSERT( static_cast(n) <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); + CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads(); - for(long i = 0; i < static_cast(n); i++) { + for(int i = 0; i < n; i++) { unsigned char a = s[i] - _mapStartChar; float row = (float) (a % _itemsPerRow); @@ -177,9 +177,9 @@ void LabelAtlas::updateAtlasValues() } if (n > 0 ){ _textureAtlas->setDirty(true); - long totalQuads = _textureAtlas->getTotalQuads(); - if (static_cast(n) > totalQuads) { - _textureAtlas->increaseTotalQuadsWith(n - totalQuads); + auto totalQuads = _textureAtlas->getTotalQuads(); + if (n > totalQuads) { + _textureAtlas->increaseTotalQuadsWith(static_cast(n - totalQuads)); } } } @@ -187,10 +187,10 @@ void LabelAtlas::updateAtlasValues() //CCLabelAtlas - LabelProtocol void LabelAtlas::setString(const std::string &label) { - size_t len = label.size(); - if (static_cast(len) > _textureAtlas->getTotalQuads()) + auto len = label.size(); + if (len > _textureAtlas->getTotalQuads()) { - _textureAtlas->resizeCapacity(len); + _textureAtlas->resizeCapacity(static_cast(len)); } _string.clear(); _string = label; @@ -200,7 +200,7 @@ void LabelAtlas::setString(const std::string &label) this->setContentSize(s); - _quadsToDraw = len; + _quadsToDraw = static_cast(len); } const std::string& LabelAtlas::getString(void) const diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 8fd81b9bda..47adb534a1 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -67,7 +67,7 @@ public: } /** creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - static LabelAtlas * create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap); + static LabelAtlas * create(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); /** creates the LabelAtlas with a string and a configuration file @since v2.0 @@ -75,7 +75,7 @@ public: static LabelAtlas* create(const std::string& string, const std::string& fntFile); /** initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - bool initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap); + bool initWithString(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); /** initializes the LabelAtlas with a string and a configuration file @since v2.0 @@ -83,7 +83,7 @@ public: bool initWithString(const std::string& string, const std::string& fntFile); /** initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the starting char of the atlas */ - bool initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap); + bool initWithString(const std::string& string, Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); // super methods virtual void updateAtlasValues(); @@ -99,7 +99,7 @@ protected: // string to render std::string _string; // the first char in the charmap - long _mapStartChar; + int _mapStartChar; }; // end of GUI group diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 88fb154770..05e85eb95b 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -267,8 +267,8 @@ void CCBMFontConfiguration::parseImageFileName(std::string line, const std::stri ////////////////////////////////////////////////////////////////////////// // page ID. Sanity check - long index = line.find('=')+1; - long index2 = line.find(' ', index); + auto index = line.find('=')+1; + auto index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); CCASSERT(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); // file @@ -288,8 +288,8 @@ void CCBMFontConfiguration::parseInfoArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // padding - long index = line.find("padding="); - long index2 = line.find(' ', index); + auto index = line.find("padding="); + auto index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "padding=%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left); CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom); @@ -303,8 +303,8 @@ void CCBMFontConfiguration::parseCommonArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // Height - long index = line.find("lineHeight="); - long index2 = line.find(' ', index); + auto index = line.find("lineHeight="); + auto index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "lineHeight=%d", &_commonHeight); // scaleW. sanity check @@ -334,8 +334,8 @@ void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontD ////////////////////////////////////////////////////////////////////////// // Character ID - long index = line.find("id="); - long index2 = line.find(' ', index); + auto index = line.find("id="); + auto index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "id=%u", &characterDefinition->charID); @@ -385,8 +385,8 @@ void CCBMFontConfiguration::parseKerningEntry(std::string line) // first int first; - long index = line.find("first="); - long index2 = line.find(' ', index); + auto index = line.find("first="); + auto index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "first=%d", &first); @@ -494,7 +494,7 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string texture->autorelease(); } - if (SpriteBatchNode::initWithTexture(texture, theString.size())) + if (SpriteBatchNode::initWithTexture(texture, static_cast(theString.size()))) { _width = width; _alignment = alignment; @@ -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( 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( child ); - if (pNode) + RGBAProtocol *pRGBAProtocol = dynamic_cast(child); + if (pRGBAProtocol) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(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( pObj ); + _children.forEach([this](Node* child){ + Sprite *item = static_cast( 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( pObj ); + _children.forEach([this](Node* child){ + Sprite *item = static_cast( child ); item->updateDisplayedColor(_displayedColor); - } + }); } bool LabelBMFont::isCascadeColorEnabled() const @@ -917,7 +899,7 @@ void LabelBMFont::updateLabel() { // Step 1: Make multiline vector str_whole = cc_utf16_vec_from_utf16_str(_string); - unsigned int stringLength = str_whole.size(); + size_t stringLength = str_whole.size(); vector multiline_string; multiline_string.reserve( stringLength ); vector 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,14 +1078,14 @@ 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) { lineNumber++; continue; } - int index = i + line_length - 1 + lineNumber; + int index = static_cast(i + line_length - 1 + lineNumber); if (index < 0) continue; Sprite* lastChar = static_cast( getChildByTag(index) ); diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 6f85e1495a..ca1fa7ac04 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -39,7 +39,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) { // Step 1: Make multiline vector strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String()); - unsigned int stringLength = strWhole.size(); + size_t stringLength = strWhole.size(); vector multiline_string; multiline_string.reserve( stringLength ); @@ -197,7 +197,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) 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* strNew = new unsigned short[size + 1]; for (int j = 0; j < size; ++j) @@ -231,7 +231,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) if (currentChar == '\n' || currentChar == 0) { float lineWidth = 0.0f; - unsigned int lineLength = lastLine.size(); + size_t lineLength = lastLine.size(); // if last line is empty we must just increase lineNumber and work with next line if (lineLength == 0) @@ -239,7 +239,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) lineNumber++; continue; } - int index = i + lineLength - 1 + lineNumber; + int index = static_cast(i + lineLength - 1 + lineNumber); if (index < 0) continue; if(currentChar == 0) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index e7fe6f5342..59ed0e1841 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -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(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(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(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& 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& 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 diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index fe96a5d40a..bccf5b091d 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -70,10 +70,10 @@ public: CC_DEPRECATED_ATTRIBUTE virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} /* Callback function should not be deprecated, it will generate lots of warnings. Since 'setTouchEnabled' was deprecated, it will make warnings if developer overrides onTouchXXX and invokes setTouchEnabled(true) instead of using EventDispatcher::addEventListenerWithXXX. @@ -412,7 +412,7 @@ public: @since v2.1 * @js NA */ - static LayerMultiplex* createWithArray(Array* arrayOfLayers); + static LayerMultiplex* createWithArray(const Vector& 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& arrayOfLayers); + unsigned int _enabledLayer; - Array* _layers; + Vector _layers; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(LayerMultiplex); }; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 6fef9d78a6..825a73a25f 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -30,7 +30,6 @@ THE SOFTWARE. #include "CCInteger.h" #include "CCEventListenerTouch.h" - #include #include @@ -38,18 +37,6 @@ using namespace std; NS_CC_BEGIN -static std::vector ccarray_to_std_vector(Array* pArray) -{ - std::vector ret; - Object* pObj; - CCARRAY_FOREACH(pArray, pObj) - { - Integer* pInteger = static_cast(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& 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 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()); } -bool Menu::initWithArray(Array* pArrayOfItems) +bool Menu::initWithArray(const Vector& 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(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(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(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(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(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 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(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(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 columns = ccarray_to_std_vector(columnArray); - - vector columnWidths; - vector columnHeights; + vector columnWidths; + vector 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(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(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(pObject); + MenuItem* child = dynamic_cast(*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; diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 04aeb831a4..47e1f4eafe 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -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& 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& arrayOfItems); /** whether or not the menu will receive events */ bool _enabled; - MenuItem* itemForTouch(Touch * touch); + MenuItem* getItemForTouch(Touch * touch); State _state; MenuItem *_selectedItem; diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 89aa7eaba6..f4709c5156 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -42,7 +42,7 @@ THE SOFTWARE. NS_CC_BEGIN -static long _globalFontSize = kItemSize; +static int _globalFontSize = kItemSize; static std::string _globalFontName = "Marker Felt"; static bool _globalFontNameRelease = false; @@ -310,13 +310,13 @@ void MenuItemLabel::setEnabled(bool enabled) //CCMenuItemAtlasFont // -MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap) +MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap) { return MenuItemAtlasFont::create(value, charMapFile, itemWidth, itemHeight, startCharMap, (const ccMenuCallback&)nullptr); } // XXX: deprecated -MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) +MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) { MenuItemAtlasFont *ret = new MenuItemAtlasFont(); ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); @@ -324,7 +324,7 @@ MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* cha return ret; } -MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback) +MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) { MenuItemAtlasFont *ret = new MenuItemAtlasFont(); ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); @@ -333,14 +333,14 @@ MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const st } // XXX: deprecated -bool MenuItemAtlasFont::initWithString(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) +bool MenuItemAtlasFont::initWithString(const char* value, const char* charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) { _target = target; CC_SAFE_RETAIN(_target); return initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback) +bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) { CCASSERT( value.size() != 0, "value length must be greater than 0"); LabelAtlas *label = new LabelAtlas(); @@ -357,12 +357,12 @@ bool MenuItemAtlasFont::initWithString(const std::string& value, const std::stri //CCMenuItemFont // -void MenuItemFont::setFontSize(long s) +void MenuItemFont::setFontSize(int s) { _globalFontSize = s; } -long MenuItemFont::getFontSize() +int MenuItemFont::getFontSize() { return _globalFontSize; } @@ -449,13 +449,13 @@ void MenuItemFont::recreateLabel() this->setLabel(label); } -void MenuItemFont::setFontSizeObj(long s) +void MenuItemFont::setFontSizeObj(int s) { _fontSize = s; recreateLabel(); } -long MenuItemFont::getFontSizeObj() const +int MenuItemFont::getFontSizeObj() const { return _fontSize; } @@ -806,37 +806,21 @@ void MenuItemImage::setDisabledSpriteFrame(SpriteFrame * frame) // // XXX: deprecated -MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems) +MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, const Vector& menuItems) { 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 = menuItems; ret->_selectedIndex = UINT_MAX; ret->setSelectedIndex(0); return ret; } -MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems) +MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, const Vector& menuItems) { 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 = menuItems; ret->_selectedIndex = UINT_MAX; ret->setSelectedIndex(0); return ret; @@ -884,14 +868,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 +893,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 +909,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(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 +930,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 +941,13 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::selected() { MenuItem::selected(); - static_cast(_subItems->getObjectAtIndex(_selectedIndex))->selected(); + _subItems.at(_selectedIndex)->selected(); } void MenuItemToggle::unselected() { MenuItem::unselected(); - static_cast(_subItems->getObjectAtIndex(_selectedIndex))->unselected(); + _subItems.at(_selectedIndex)->unselected(); } void MenuItemToggle::activate() @@ -978,7 +955,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 +966,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(pObj); - pItem->setEnabled(enabled); - } - } + _subItems.forEach([&enabled](MenuItem* item){ + item->setEnabled(enabled); + }); } } MenuItem* MenuItemToggle::getSelectedItem() { - return static_cast(_subItems->getObjectAtIndex(_selectedIndex)); + return _subItems.at(_selectedIndex); } NS_CC_END diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 09de7fe399..57ce4dad9e 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -212,11 +212,11 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** creates a menu item from a string and atlas with a target/selector */ - static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap); + static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ - CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); + CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ - static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); + static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); protected: /** @@ -230,9 +230,9 @@ protected: virtual ~MenuItemAtlasFont(){} /** initializes a menu item from a string and atlas with a target/selector */ - CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); + CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** initializes a menu item from a string and atlas with a target/selector */ - bool initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); private: CC_DISALLOW_COPY_AND_ASSIGN(MenuItemAtlasFont); @@ -253,10 +253,10 @@ public: static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback); /** set default font size */ - static void setFontSize(long size); + static void setFontSize(int size); /** get default font size */ - static long getFontSize(); - CC_DEPRECATED_ATTRIBUTE static unsigned int fontSize() { return MenuItemFont::getFontSize(); }; + static int getFontSize(); + CC_DEPRECATED_ATTRIBUTE static int fontSize() { return MenuItemFont::getFontSize(); }; /** set the default font name */ static void setFontName(const std::string& name); /** get the default font name */ @@ -268,13 +268,13 @@ public: * so change the name to setFontSizeObj * @js setFontSize */ - void setFontSizeObj(long size); + void setFontSizeObj(int size); /** get font size * @js getFontSize */ - long getFontSizeObj() const; - CC_DEPRECATED_ATTRIBUTE unsigned int fontSizeObj() const { return getFontSizeObj(); }; + int getFontSizeObj() const; + CC_DEPRECATED_ATTRIBUTE int fontSizeObj() const { return getFontSizeObj(); }; /** set the font name * c++ can not overload static and non-static member functions with the same parameter types @@ -309,7 +309,7 @@ protected: void recreateLabel(); - long _fontSize; + int _fontSize; std::string _fontName; private: @@ -453,8 +453,19 @@ private: class CC_DLL MenuItemToggle : public MenuItem { public: + /** creates a menu item from a Array with a target selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static MenuItemToggle * createWithTarget(Object* target, SEL_MenuHandler selector, const Vector& menuItems); + /** creates a menu item from a list of items with a target/selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static MenuItemToggle* createWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, ...)CC_REQUIRES_NULL_TERMINATION; + /** creates a menu item from a Array with a callable object */ - static MenuItemToggle * createWithCallback(const ccMenuCallback& callback, Array* menuItems); + static MenuItemToggle * createWithCallback(const ccMenuCallback& callback, const Vector& menuItems); /** creates a menu item from a list of items with a callable object */ static MenuItemToggle* createWithCallback(const ccMenuCallback& callback, MenuItem* item, ...) CC_REQUIRES_NULL_TERMINATION; /** creates a menu item with no target/selector and no items */ @@ -481,13 +492,11 @@ public: * @js NA * @lua NA */ - - inline Array* getSubItems() const { return _subItems; }; + inline const Vector& getSubItems() const { return _subItems; }; + inline Vector& 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& items) { _subItems = items; } @@ -498,22 +507,11 @@ public: virtual void setEnabled(bool var) override; protected: - /** creates a menu item from a Array with a target selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static MenuItemToggle * createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems); - /** creates a menu item from a list of items with a target/selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static MenuItemToggle* createWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, ...)CC_REQUIRES_NULL_TERMINATION; /** * @js ctor */ MenuItemToggle() : _selectedIndex(0) - , _subItems(NULL) {} /** * @js NA @@ -537,7 +535,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 _subItems; private: CC_DISALLOW_COPY_AND_ASSIGN(MenuItemToggle); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index bdff745edf..3a31d7efdf 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -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(child); - if (node) - { - node->_parent = NULL; - } + child->_parent = NULL; } } - // children - CC_SAFE_RELEASE(_children); - removeAllComponents(); CC_SAFE_DELETE(_componentContainer); @@ -404,9 +395,9 @@ void Node::setPositionY(float y) setPosition(Point(_position.x, y)); } -long Node::getChildrenCount() const +int 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(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); + auto index = _children.getIndex(child); if( index != CC_INVALID_INDEX ) this->detachChild( child, index, cleanup ); } @@ -725,38 +712,36 @@ 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(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(); } } -void Node::detachChild(Node *child, long childIndex, bool doCleanup) +void Node::detachChild(Node *child, int childIndex, bool doCleanup) { // IMPORTANT: // -1st do onExit @@ -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( _children->getObjectAtIndex(i) ); - auto tempJ = static_cast( _children->getObjectAtIndex(j) ); + auto tempI = static_cast( _children.at(i) ); + auto tempJ = static_cast( _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( _children->getObjectAtIndex(j) ); + tempJ = static_cast( _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 @@ -869,13 +854,13 @@ void Node::visit() this->transform(); int 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( _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( _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 +int 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(pObj); + _children.forEach([this](Node* child){ + RGBAProtocol* item = dynamic_cast(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(obj); + _children.forEach([this](Node* child){ + RGBAProtocol *item = dynamic_cast(child); if (item) { item->updateDisplayedColor(_displayedColor); } - } + }); } } diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 617244a40b..c9de3a916c 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -38,8 +38,7 @@ #include "CCScriptSupport.h" #include "CCProtocols.h" #include "CCEventDispatcher.h" - -#include +#include "CCVector.h" NS_CC_BEGIN @@ -614,15 +613,15 @@ public: * * @return An array of children */ - virtual Array* getChildren() { return _children; } - virtual const Array *getChildren() const { return _children; } - - /** + virtual Vector& getChildren() { return _children; } + virtual const Vector& getChildren() const { return _children; } + + /** * Get the amount of children. * * @return The amount of children. */ - long getChildrenCount() const; + int getChildrenCount() const; /** * Sets the parent node @@ -1043,10 +1042,10 @@ public: * * @return The number of actions that are running plus the ones that are schedule to run */ - unsigned int getNumberOfRunningActions() const; + int getNumberOfRunningActions() const; /** @deprecated Use getNumberOfRunningActions() instead */ - CC_DEPRECATED_ATTRIBUTE unsigned int numberOfRunningActions() const { return getNumberOfRunningActions(); }; + CC_DEPRECATED_ATTRIBUTE int numberOfRunningActions() const { return getNumberOfRunningActions(); }; /// @} end of Actions @@ -1398,12 +1397,12 @@ protected: /// lazy allocs void childrenAlloc(void); - + /// helper that reorder a child void insertChild(Node* child, int z); /// Removes a child, call child->onExit(), do cleanup, remove it from children array. - void detachChild(Node *child, long index, bool doCleanup); + void detachChild(Node *child, int index, bool doCleanup); /// Convert cocos2d coordinates to UI windows coordinate. Point convertToWindowSpace(const Point& nodePoint) const; @@ -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 _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 diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index a6d1fff5cb..74df4b4ad0 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -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(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); + auto 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(_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) +int 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); + auto 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(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(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; + int 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(_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(int* oldIndex, int* newIndex, Node* child, int z) { bool foundCurrentIdx = false; bool foundNewIdx = false; int minusOne = 0; - unsigned int count = _children->count(); + auto count = _children.size(); - for( unsigned int i=0; i < count; i++ ) + for( int i=0; i < count; i++ ) { - Node* pNode = (Node *)_children->getObjectAtIndex(i); + Node* pNode = _children.at(i); // new index if( pNode->getZOrder() > z && ! foundNewIdx ) @@ -337,25 +330,25 @@ void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* ne if( ! foundNewIdx ) { - *newIndex = count; + *newIndex = static_cast(count); } *newIndex += minusOne; } -unsigned int ParticleBatchNode::searchNewPositionInChildrenForZ(int z) +int ParticleBatchNode::searchNewPositionInChildrenForZ(int z) { - unsigned int count = _children->count(); + auto count = _children.size(); - for( unsigned int i=0; i < count; i++ ) + for( int i=0; i < count; i++ ) { - Node *child = (Node *)_children->getObjectAtIndex(i); + Node *child = _children.at(i); if (child->getZOrder() > z) { return i; } } - return count; + return static_cast(count); } // override removeChild: @@ -366,7 +359,7 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup) return; CCASSERT( dynamic_cast(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(aChild); Node::removeChild(child, cleanup); @@ -383,14 +376,16 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup) updateAllAtlasIndexes(); } -void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) +void ParticleBatchNode::removeChildAtIndex(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(child)->setBatchNode(nullptr); + }); Node::removeAllChildrenWithCleanup(doCleanup); @@ -417,7 +412,7 @@ void ParticleBatchNode::draw(void) -void ParticleBatchNode::increaseAtlasCapacityTo(unsigned int quantity) +void ParticleBatchNode::increaseAtlasCapacityTo(int quantity) { CCLOG("cocos2d: ParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", (long)_textureAtlas->getCapacity(), @@ -431,7 +426,7 @@ void ParticleBatchNode::increaseAtlasCapacityTo(unsigned int quantity) } //sets a 0'd quad into the quads array -void ParticleBatchNode::disableParticle(unsigned int particleIndex) +void ParticleBatchNode::disableParticle(int particleIndex) { V3F_C4B_T2F_Quad* quad = &((_textureAtlas->getQuads())[particleIndex]); quad->br.vertices.x = quad->br.vertices.y = quad->tr.vertices.x = quad->tr.vertices.y = quad->tl.vertices.x = quad->tl.vertices.y = quad->bl.vertices.x = quad->bl.vertices.y = 0.0f; @@ -467,20 +462,18 @@ 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(pObj); - child->setAtlasIndex(index); - index += child->getTotalParticles(); - } + int index = 0; + + _children.forEach([&index](Node* child){ + ParticleSystem* partiSys = static_cast(child); + partiSys->setAtlasIndex(index); + index += partiSys->getTotalParticles(); + }); } // ParticleBatchNode - CocosNodeTexture protocol -void ParticleBatchNode::updateBlendFunc(void) +void ParticleBatchNode::updateBlendFunc() { if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha()) _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED; @@ -497,7 +490,7 @@ void ParticleBatchNode::setTexture(Texture2D* texture) } } -Texture2D* ParticleBatchNode::getTexture(void) const +Texture2D* ParticleBatchNode::getTexture() const { return _textureAtlas->getTexture(); } @@ -507,7 +500,7 @@ void ParticleBatchNode::setBlendFunc(const BlendFunc &blendFunc) _blendFunc = blendFunc; } // returns the blending function used for the texture -const BlendFunc& ParticleBatchNode::getBlendFunc(void) const +const BlendFunc& ParticleBatchNode::getBlendFunc() const { return _blendFunc; } diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index 937c348500..9f1a22b2ac 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -91,11 +91,11 @@ public: /** Inserts a child into the ParticleBatchNode */ void insertChild(ParticleSystem* system, int index); - void removeChildAtIndex(unsigned int index, bool doCleanup); + void removeChildAtIndex(int index, bool doCleanup); void removeAllChildrenWithCleanup(bool doCleanup); /** disables a particle by inserting a 0'd quad into the texture atlas */ - void disableParticle(unsigned int particleIndex); + void disableParticle(int particleIndex); /** Gets the texture atlas used for drawing the quads */ inline TextureAtlas* getTextureAtlas() const { return _textureAtlas; }; @@ -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(int quantity); + int searchNewPositionInChildrenForZ(int z); + void getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z); + int addChildHelper(ParticleSystem* child, int z, int aTag); void updateBlendFunc(void); /** the texture atlas used for drawing the quads */ TextureAtlas* _textureAtlas; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 53fa60625f..91e05caa05 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -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) + auto dataLen = textureData.size(); + if (dataLen != 0) { // if it fails, try to get it from the base64-gzipped data - int decodeLen = base64Decode((unsigned char*)textureData, (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"); + ssize_t deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated); + CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage() @@ -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"); } diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 7300c90ca9..c09dc527a6 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -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); diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index a35a564f85..a0f395c5bf 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -198,8 +198,8 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); // textures must be power of two squared - long powW = 0; - long powH = 0; + int powW = 0; + int powH = 0; if (Configuration::getInstance()->supportsNPOT()) { @@ -212,7 +212,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat powH = ccNextPOT(h); } - long dataLen = (long)(powW * powH * 4); + auto dataLen = powW * powH * 4; data = malloc(dataLen); CC_BREAK_IF(! data); @@ -528,16 +528,12 @@ void RenderTexture::draw() //! make sure all children are drawn sortAllChildren(); - Object *pElement; - CCARRAY_FOREACH(_children, pElement) - { - Node *child = static_cast(pElement); - + _children.forEach([this](Node* child){ if (child != _sprite) { child->visit(); } - } + }); end(); } diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 97d4fbec65..86e8def996 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -132,25 +132,17 @@ void Scene::addChildToPhysicsWorld(Node* child) { if (_physicsWorld) { - std::function addToPhysicsWorldFunc = nullptr; - addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void + std::function addToPhysicsWorldFunc = nullptr; + addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Node* node) -> void { - - if (dynamic_cast(obj) != nullptr) + if (node->getPhysicsBody()) { - Node* node = dynamic_cast(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); diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 59c6cdce65..a617a4b693 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -256,15 +256,15 @@ Scheduler::Scheduler(void) , _currentTarget(nullptr) , _currentTargetSalvaged(false) , _updateHashLocked(false) -, _scriptHandlerEntries(nullptr) +, _scriptHandlerEntries(20) { - + // I don't expect to have more than 30 functions to all per frame + _functionsToPerform.reserve(30); } Scheduler::~Scheduler(void) { unscheduleAll(); - CC_SAFE_RELEASE(_scriptHandlerEntries); } void Scheduler::removeHashElement(_hashSelectorEntry *element) @@ -629,10 +629,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) } } - if (_scriptHandlerEntries) - { - _scriptHandlerEntries->removeAllObjects(); - } + _scriptHandlerEntries.clear(); } void Scheduler::unscheduleAllForTarget(Object *target) @@ -674,20 +671,15 @@ void Scheduler::unscheduleAllForTarget(Object *target) unsigned int Scheduler::scheduleScriptFunc(unsigned int handler, float interval, bool paused) { SchedulerScriptHandlerEntry* entry = SchedulerScriptHandlerEntry::create(handler, interval, paused); - if (!_scriptHandlerEntries) - { - _scriptHandlerEntries = Array::createWithCapacity(20); - _scriptHandlerEntries->retain(); - } - _scriptHandlerEntries->addObject(entry); + _scriptHandlerEntries.pushBack(entry); return entry->getEntryId(); } void Scheduler::unscheduleScriptEntry(unsigned int scheduleScriptEntryID) { - for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) + for (int i = _scriptHandlerEntries.size() - 1; i >= 0; i--) { - SchedulerScriptHandlerEntry* entry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + SchedulerScriptHandlerEntry* entry = _scriptHandlerEntries.at(i); if (entry->getEntryId() == (int)scheduleScriptEntryID) { entry->markedForDeletion(); @@ -763,22 +755,21 @@ bool Scheduler::isTargetPaused(Object *target) return false; // should never get here } -Set* Scheduler::pauseAllTargets() +Vector Scheduler::pauseAllTargets() { return pauseAllTargetsWithMinPriority(PRIORITY_SYSTEM); } -Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) +Vector Scheduler::pauseAllTargetsWithMinPriority(int minPriority) { - Set* idsWithSelectors = new Set();// setWithCapacity:50]; - idsWithSelectors->autorelease(); + Vector idsWithSelectors(50); // Custom Selectors for(tHashTimerEntry *element = _hashForTimers; element != nullptr; element = (tHashTimerEntry*)element->hh.next) { element->paused = true; - idsWithSelectors->addObject(element->target); + idsWithSelectors.pushBack(element->target); } // Updates selectors @@ -790,7 +781,7 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) if(entry->priority >= minPriority) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } } @@ -800,7 +791,7 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) DL_FOREACH_SAFE( _updates0List, entry, tmp ) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } @@ -809,20 +800,27 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) if(entry->priority >= minPriority) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } - return idsWithSelectors; + return std::move(idsWithSelectors); } -void Scheduler::resumeTargets(Set* targetsToResume) +void Scheduler::resumeTargets(const Vector& targetsToResume) { - SetIterator iter; - for (iter = targetsToResume->begin(); iter != targetsToResume->end(); ++iter) - { - resumeTarget(*iter); - } + targetsToResume.forEach([this](Object* obj){ + this->resumeTarget(obj); + }); +} + +void Scheduler::performFunctionInCocosThread(const std::function &function) +{ + _performMutex.lock(); + + _functionsToPerform.push_back(function); + + _performMutex.unlock(); } // main loop @@ -835,6 +833,10 @@ void Scheduler::update(float dt) dt *= _timeScale; } + // + // Selector callbacks + // + // Iterate over all the Updates' selectors tListEntry *entry, *tmp; @@ -904,23 +906,6 @@ void Scheduler::update(float dt) } } - // Iterate over all the script callbacks - if (_scriptHandlerEntries) - { - for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) - { - SchedulerScriptHandlerEntry* eachEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); - if (eachEntry->isMarkedForDeletion()) - { - _scriptHandlerEntries->removeObjectAtIndex(i); - } - else if (!eachEntry->isPaused()) - { - eachEntry->getTimer()->update(dt); - } - } - } - // delete all updates that are marked for deletion // updates with priority < 0 DL_FOREACH_SAFE(_updatesNegList, entry, tmp) @@ -950,8 +935,43 @@ void Scheduler::update(float dt) } _updateHashLocked = false; - _currentTarget = nullptr; + + // + // Script callbacks + // + + // Iterate over all the script callbacks + if (!_scriptHandlerEntries.empty()) + { + for (auto i = _scriptHandlerEntries.size() - 1; i >= 0; i--) + { + SchedulerScriptHandlerEntry* eachEntry = _scriptHandlerEntries.at(i); + if (eachEntry->isMarkedForDeletion()) + { + _scriptHandlerEntries.remove(i); + } + else if (!eachEntry->isPaused()) + { + eachEntry->getTimer()->update(dt); + } + } + } + + // + // Functions allocated from another thread + // + + // Testing size is faster than locking / unlocking. + // And almost never there will be functions scheduled to be called. + if( !_functionsToPerform.empty() ) { + _performMutex.lock(); + for( const auto &function : _functionsToPerform ) { + function(); + } + _functionsToPerform.clear(); + _performMutex.unlock(); + } } diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 51ac4cd6ba..3146729205 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -28,8 +28,12 @@ THE SOFTWARE. #define __CCSCHEDULER_H__ #include "CCObject.h" +#include "CCVector.h" #include "uthash.h" +#include +#include + NS_CC_BEGIN /** @@ -37,7 +41,6 @@ NS_CC_BEGIN * @{ */ -class Set; // // Timer // @@ -104,8 +107,7 @@ protected: struct _listEntry; struct _hashSelectorEntry; struct _hashUpdateEntry; - -class Array; +class SchedulerScriptHandlerEntry; /** @brief Scheduler is responsible for triggering the scheduled callbacks. You should not use NSTimer. Instead use this class. @@ -243,21 +245,27 @@ public: You should NEVER call this method, unless you know what you are doing. @since v2.0.0 */ - Set* pauseAllTargets(); + Vector pauseAllTargets(); /** Pause all selectors from all targets with a minimum priority. You should only call this with kPriorityNonSystemMin or higher. @since v2.0.0 */ - Set* pauseAllTargetsWithMinPriority(int minPriority); + Vector pauseAllTargetsWithMinPriority(int minPriority); /** Resume selectors on a set of targets. This can be useful for undoing a call to pauseAllSelectors. @since v2.0.0 */ - void resumeTargets(Set* targetsToResume); + void resumeTargets(const Vector& targetsToResume); -private: + /** calls a function on the cocos2d thread. Useful when you need to call a cocos2d function from another thread. + This function is thread safe. + @since v3.0 + */ + void performFunctionInCocosThread( const std::function &function); + +protected: void removeHashElement(struct _hashSelectorEntry *element); void removeUpdateFromHash(struct _listEntry *entry); @@ -266,7 +274,7 @@ private: void priorityIn(struct _listEntry **list, Object *target, int priority, bool paused); void appendIn(struct _listEntry **list, Object *target, bool paused); -protected: + float _timeScale; // @@ -283,7 +291,11 @@ protected: bool _currentTargetSalvaged; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. bool _updateHashLocked; - Array* _scriptHandlerEntries; + Vector _scriptHandlerEntries; + + // Used for "perform Function" + std::vector> _functionsToPerform; + std::mutex _performMutex; }; // end of global group diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 36577238b0..824af33470 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -613,7 +613,7 @@ void Sprite::draw(void) long offset = 0; setGLBufferData(&_quad, 4 * kQuadSize, 0); #else - long offset = (long)&_quad; + size_t offset = (size_t)&_quad; #endif // EMSCRIPTEN // vertex @@ -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(object); - if (child) + _children.forEach([this](Node* child){ + Sprite* sprite = dynamic_cast(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(object); - if (child) + _children.forEach([](Node* child){ + Sprite* sp = dynamic_cast(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( a->getFrames()->getObjectAtIndex(frameIndex) ); + AnimationFrame* frame = a->getFrames().at(frameIndex); CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 03a71abf1c..748a248f58 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, int capacity * creation with File Image */ -SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, long capacity/* = DEFAULT_CAPACITY*/) +SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = DEFAULT_CAPACITY*/) { SpriteBatchNode *batchNode = new SpriteBatchNode(); batchNode->initWithFile(fileImage, capacity); @@ -76,7 +76,7 @@ SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, long capacity/* /* * init with Texture2D */ -bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) +bool SpriteBatchNode::initWithTexture(Texture2D *tex, int capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -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); @@ -112,7 +110,7 @@ bool SpriteBatchNode::init() /* * init with FileImage */ -bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity) +bool SpriteBatchNode::initWithFile(const char* fileImage, int capacity) { Texture2D *texture2D = Director::getInstance()->getTextureCache()->addImage(fileImage); return initWithTexture(texture2D, 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(_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(obj); - updateAtlasIndex(child, &index); - } + _children.forEach([this, &index](Node* child){ + Sprite* sp = static_cast(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(); + auto count = array.size(); int oldIndex = 0; @@ -315,7 +309,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { bool needNewIndex=true; - if (static_cast(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(obj); - if (needNewIndex && child->getZOrder() >= 0) + array.forEach([&](Node* child){ + Sprite* sp = static_cast(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 ); @@ -415,9 +408,9 @@ void SpriteBatchNode::increaseAtlasCapacity(void) // this is likely computationally expensive int quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; - CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", - (long)_textureAtlas->getCapacity(), - (long)quantity); + CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%d] to [%d].", + _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(child); + if (sp && (sp->getZOrder() < 0)) { - Sprite* child = static_cast(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(child); + if (sp && (sp->getZOrder() >= 0)) { - Sprite* child = static_cast(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(children->getLastObject())); + return highestAtlasIndexInChild( static_cast(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(children->getObjectAtIndex(0))); + return lowestAtlasIndexInChild(static_cast(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(); + auto 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(siblings->getObjectAtIndex(childIndex - 1)); + prev = static_cast(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; + int index = static_cast(_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(obj); - appendChild(child); - } + sprite->getChildren().forEach([this](Node* child){ + appendChild(static_cast(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(obj); + if (child) { - Sprite* child = static_cast(object); - if (child) - { - removeSpriteFromAtlas(child); - } + removeSpriteFromAtlas(child); } - } + }); } void SpriteBatchNode::updateBlendFunc(void) diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 8d1b930771..6ba402fe57 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -74,7 +74,7 @@ public: The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. */ - static SpriteBatchNode* create(const char* fileImage, long capacity = DEFAULT_CAPACITY); + static SpriteBatchNode* create(const char* fileImage, int capacity = DEFAULT_CAPACITY); /** * @js ctor */ @@ -88,14 +88,14 @@ public: /** initializes a SpriteBatchNode with a texture2d and capacity of children. The capacity will be increased in 33% in runtime if it run out of space. */ - bool initWithTexture(Texture2D *tex, long capacity); + bool initWithTexture(Texture2D *tex, int capacity); /** initializes a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children. The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. * @js init * @lua init */ - bool initWithFile(const char* fileImage, long capacity); + bool initWithFile(const char* fileImage, int capacity); bool init(); /** returns the TextureAtlas object */ diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 80cff587b5..23c702bb00 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -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(); 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,25 @@ 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& framesDict = dictionary["frames"].asValueMap(); int format = 0; // get the format - if(metadataDict != NULL) + if (dictionary.find("metadata") != dictionary.end()) { - format = metadataDict->valueForKey("format")->intValue(); + ValueMap& metadataDict = dictionary["metadata"].asValueMap(); + 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(element->getObject()); - std::string spriteFrameName = element->getStrKey(); - SpriteFrame* spriteFrame = static_cast(_spriteFrames->objectForKey(spriteFrameName)); + ValueMap& frameDict = iter->second.asValueMap(); + std::string spriteFrameName = iter->first; + SpriteFrame* spriteFrame = _spriteFrames.at(spriteFrameName); if (spriteFrame) { continue; @@ -116,14 +112,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 +130,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 +139,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 +163,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(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 +192,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex } // add sprite frame - _spriteFrames->setObject(spriteFrame, spriteFrameName); + _spriteFrames.insert(spriteFrameName, spriteFrame); spriteFrame->release(); } } @@ -207,10 +200,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 +227,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( dict->objectForKey("metadata") ); - if (metadataDict) + if (dict.find("metadata") != dict.end()) { + ValueMap& metadataDict = dict["metadata"].asValueMap(); // 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 +269,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 toRemoveFrames; + + for (auto iter = _spriteFrames.begin(); iter != _spriteFrames.end(); ++iter) { - SpriteFrame* spriteFrame = static_cast(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 +317,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 +336,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::iterator ret = _loadedFileNames->find(plist); @@ -356,55 +350,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->objectForKey("frames")); - Array* keysToRemove = Array::create(); + ValueMap framesDict = dictionary["frames"].asValueMap(); + std::vector 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 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(_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 +405,4 @@ SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) } NS_CC_END + diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 11733fa0ff..d9fff83c08 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -37,13 +37,13 @@ THE SOFTWARE. #include "CCSpriteFrame.h" #include "CCTexture2D.h" #include "CCObject.h" +#include "CCValue.h" +#include "CCMap.h" #include #include 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 _spriteFrames; + ValueMap _spriteFramesAliases; std::set* _loadedFileNames; }; diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 87a9893126..8515989a6f 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -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(_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(); } } } @@ -381,7 +379,7 @@ Sprite * TMXLayer::insertTileForGID(unsigned int gid, const Point& pos) setupTileSprite(tile, pos, gid); // get atlas index - unsigned int indexForZ = atlasIndexForNewZ(z); + unsigned int indexForZ = atlasIndexForNewZ(static_cast(z)); // Optimization: add the quad without adding a child this->insertQuadFromSprite(tile, indexForZ); @@ -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(child); + if (child) { - Sprite* child = static_cast(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(obj); + if (child) { - Sprite* child = static_cast(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); } } - } + }); } } } diff --git a/cocos/2d/CCTMXLayer.h b/cocos/2d/CCTMXLayer.h index b85de82c1e..2667739599 100644 --- a/cocos/2d/CCTMXLayer.h +++ b/cocos/2d/CCTMXLayer.h @@ -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 diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index b232b2f807..3cc08a0473 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -35,41 +35,38 @@ 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.empty()) { - Object* pObj = nullptr; - CCARRAY_FOREACH(_objects, pObj) + for (const auto& v : _objects) { - Dictionary* pDict = static_cast(pObj); - String *name = static_cast(pDict->objectForKey("name")); - if (name && name->_string == objectName) + const ValueMap& dict = v.asValueMap(); + if (dict.find("name") != dict.end()) { - return pDict; + if (dict.at("name").asString() == objectName) + 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(_properties->objectForKey(propertyName)); + if (_properties.find(propertyName) != _properties.end()) + return _properties.at(propertyName); + + return Value(); } NS_CC_END diff --git a/cocos/2d/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h index 7a06e4b961..2064b6bd67 100644 --- a/cocos/2d/CCTMXObjectGroup.h +++ b/cocos/2d/CCTMXObjectGroup.h @@ -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 diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 7ab6da363b..5df77a56e7 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -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(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(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(pObj); + TMXLayer* layer = dynamic_cast(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(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(_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(_tileProperties->objectForKey(GID)); + if (_tileProperties.find(GID) != _tileProperties.end()) + return _tileProperties.at(GID); + + return Value(); } diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index 7148711e56..7138e2bac0 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -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& getObjectGroups() const { return _objectGroups; }; + inline Vector& getObjectGroups() { return _objectGroups; }; + inline void setObjectGroups(const Vector& 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 _objectGroups; /** properties */ - Dictionary* _properties; + ValueMap _properties; //! tile properties - Dictionary* _tileProperties; + IntValueMap _tileProperties; private: CC_DISALLOW_COPY_AND_ASSIGN(TMXTiledMap); diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 06a25e3e37..4fa31b4683 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -38,47 +38,33 @@ using namespace std; NS_CC_BEGIN -static const char* valueForKey(const char *key, std::unordered_map* dict) -{ - if (dict) - { - std::unordered_map::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 *attributeDict = new std::unordered_map(); + 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(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)); + ssize_t sizeHint = s.width * s.height * sizeof(unsigned int); - int inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint); + ssize_t 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; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 80afafd1aa..4753bf81a0 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -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 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& getLayers() const { return _layers; }; + inline Vector& getLayers() { return _layers; }; + inline void setLayers(const Vector& 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& getTilesets() const { return _tilesets; }; + inline Vector& getTilesets() { return _tilesets; }; + inline void setTilesets(const Vector& 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& getObjectGroups() const { return _objectGroups; }; + inline Vector& getObjectGroups() { return _objectGroups; }; + inline void setObjectGroups(const Vector& 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 _layers; /// tilesets - Array* _tilesets; + Vector _tilesets; /// ObjectGroups - Array* _objectGroups; + Vector _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; }; diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 895aab58de..1b97b187cb 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -164,7 +164,7 @@ void TextFieldTTF::insertText(const char * text, int len) std::string sInsert(text, len); // insert \n means input end - int nPos = sInsert.find('\n'); + int nPos = static_cast(sInsert.find('\n')); if ((int)sInsert.npos != nPos) { len = nPos; @@ -201,7 +201,7 @@ void TextFieldTTF::insertText(const char * text, int len) void TextFieldTTF::deleteBackward() { - int nStrLen = _inputText.length(); + size_t nStrLen = _inputText.length(); if (! nStrLen) { // there is no string @@ -279,7 +279,7 @@ void TextFieldTTF::setString(const std::string &text) { static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; std::string displayText; - int length; + size_t length; if (text.length()>0) { diff --git a/cocos/2d/CCTextImage.cpp b/cocos/2d/CCTextImage.cpp index 3e8398ba02..1fb7016bd9 100644 --- a/cocos/2d/CCTextImage.cpp +++ b/cocos/2d/CCTextImage.cpp @@ -49,7 +49,7 @@ TextPageDef::TextPageDef(int pageNum, int width, int height): _pageNum(pageNum TextPageDef::~TextPageDef() { - int numLines = _lines.size(); + size_t numLines = _lines.size(); for( int c = 0; c(_glyphs.size()); } const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } private: @@ -115,7 +115,7 @@ public: ~TextPageDef(); void addLine(TextLineDef *theLine) { _lines.push_back(theLine); } - int getNumLines() const { return _lines.size(); } + int getNumLines() const { return static_cast(_lines.size()); } TextLineDef * getLineAt(int index) const { return _lines[index]; } int getWidth() const { return _width; } int getHeight() const { return _height; } @@ -156,7 +156,7 @@ public: ~TextFontPagesDef(); void addPage(TextPageDef *newPage) { _pages.push_back(newPage); } - int getNumPages() const { return _pages.size(); } + int getNumPages() const { return static_cast(_pages.size()); } TextPageDef* getPageAt(int index) const { return _pages[index]; } private: diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index d8c0bfbaf8..50338299c7 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -119,9 +119,9 @@ static bool _PVRHaveAlphaPremultiplied = false; //conventer function // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBB -void Texture2D::convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i=0; i < dataLen; ++i) + for (ssize_t i=0; i < dataLen; ++i) { *outData++ = data[i]; //R *outData++ = data[i]; //G @@ -130,9 +130,9 @@ void Texture2D::convertI8ToRGB888(const unsigned char* data, long dataLen, unsig } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB -void Texture2D::convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 1; i < l; i += 2) + for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *outData++ = data[i]; //R *outData++ = data[i]; //G @@ -141,9 +141,9 @@ void Texture2D::convertAI88ToRGB888(const unsigned char* data, long dataLen, uns } // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0; i < dataLen; ++i) + for (ssize_t i = 0; i < dataLen; ++i) { *outData++ = data[i]; //R *outData++ = data[i]; //G @@ -153,9 +153,9 @@ void Texture2D::convertI8ToRGBA8888(const unsigned char* data, long dataLen, uns } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 1; i < l; i += 2) + for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *outData++ = data[i]; //R *outData++ = data[i]; //G @@ -165,7 +165,7 @@ void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, long dataLen, u } // IIIIIIII -> RRRRRGGGGGGBBBBB -void Texture2D::convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -177,10 +177,10 @@ void Texture2D::convertI8ToRGB565(const unsigned char* data, long dataLen, unsig } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGGBBBBB -void Texture2D::convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 1; i < l; i += 2) + for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i] & 0x00FC) << 3 //G @@ -189,10 +189,10 @@ void Texture2D::convertAI88ToRGB565(const unsigned char* data, long dataLen, uns } // IIIIIIII -> RRRRGGGGBBBBAAAA -void Texture2D::convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0; i < dataLen; ++i) + for (ssize_t i = 0; i < dataLen; ++i) { *out16++ = (data[i] & 0x00F0) << 8 //R | (data[i] & 0x00F0) << 4 //G @@ -202,10 +202,10 @@ void Texture2D::convertI8ToRGBA4444(const unsigned char* data, long dataLen, uns } // IIIIIIIIAAAAAAAA -> RRRRGGGGBBBBAAAA -void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 1; i < l; i += 2) + for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *out16++ = (data[i] & 0x00F0) << 8 //R | (data[i] & 0x00F0) << 4 //G @@ -215,7 +215,7 @@ void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, long dataLen, u } // IIIIIIII -> RRRRRGGGGGBBBBBA -void Texture2D::convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -228,10 +228,10 @@ void Texture2D::convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsig } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGBBBBBA -void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 1; i < l; i += 2) + for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i] & 0x00F8) << 3 //G @@ -241,10 +241,10 @@ void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, long dataLen, uns } // IIIIIIII -> IIIIIIIIAAAAAAAA -void Texture2D::convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertI8ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0; i < dataLen; ++i) + for (ssize_t i = 0; i < dataLen; ++i) { *out16++ = 0xFF00 //A | data[i]; //I @@ -252,27 +252,27 @@ void Texture2D::convertI8ToAI88(const unsigned char* data, long dataLen, unsigne } // IIIIIIIIAAAAAAAA -> AAAAAAAA -void Texture2D::convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 1; i < dataLen; i += 2) + for (ssize_t i = 1; i < dataLen; i += 2) { *outData++ = data[i]; //A } } // IIIIIIIIAAAAAAAA -> IIIIIIII -void Texture2D::convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertAI88ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 1; i < l; i += 2) + for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *outData++ = data[i]; //R } } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = data[i]; //R *outData++ = data[i + 1]; //G @@ -282,9 +282,9 @@ void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB -void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 3; i < l; i += 4) + for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *outData++ = data[i]; //R *outData++ = data[i + 1]; //G @@ -293,10 +293,10 @@ void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGGBBBBB -void Texture2D::convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00FC) << 3 //G @@ -305,10 +305,10 @@ void Texture2D::convertRGB888ToRGB565(const unsigned char* data, long dataLen, u } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRGGGGGGBBBBB -void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 3; i < l; i += 4) + for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00FC) << 3 //G @@ -317,36 +317,36 @@ void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIII -void Texture2D::convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIII -void Texture2D::convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 3; i < l; i += 4) + for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> AAAAAAAA -void Texture2D::convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen -3; i < l; i += 4) + for (ssize_t i = 0, l = dataLen -3; i < l; i += 4) { *outData++ = data[i + 3]; //A } } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIIIAAAAAAAA -void Texture2D::convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 *outData++ = 0xFF; @@ -355,9 +355,9 @@ void Texture2D::convertRGB888ToAI88(const unsigned char* data, long dataLen, uns // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIIIAAAAAAAA -void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { - for (int i = 0, l = dataLen - 3; i < l; i += 4) + for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 *outData++ = data[i + 3]; @@ -365,10 +365,10 @@ void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, long dataLen, u } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRGGGGBBBBAAAA -void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = ((data[i] & 0x00F0) << 8 //R | (data[i + 1] & 0x00F0) << 4 //G @@ -378,10 +378,10 @@ void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRGGGGBBBBAAAA -void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 3; i < l; i += 4) + for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *out16++ = (data[i] & 0x00F0) << 8 //R | (data[i + 1] & 0x00F0) << 4 //G @@ -391,10 +391,10 @@ void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLe } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA -void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (long i = 0, l = dataLen - 2; i < l; i += 3) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G @@ -404,10 +404,10 @@ void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, u } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA -void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (long i = 0, l = dataLen - 2; i < l; i += 4) + for (ssize_t i = 0, l = dataLen - 2; i < l; i += 4) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G @@ -451,12 +451,12 @@ Texture2D::PixelFormat Texture2D::getPixelFormat() const return _pixelFormat; } -long Texture2D::getPixelsWide() const +int Texture2D::getPixelsWide() const { return _pixelsWide; } -long Texture2D::getPixelsHigh() const +int Texture2D::getPixelsHigh() const { return _pixelsHigh; } @@ -529,14 +529,14 @@ bool Texture2D::hasPremultipliedAlpha() const return _hasPremultipliedAlpha; } -bool Texture2D::initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize) +bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::PixelFormat pixelFormat, int pixelsWide, int pixelsHigh, const Size& contentSize) { CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size"); //if data has no mipmaps, we will consider it has only one mipmap MipmapInfo mipmap; mipmap.address = (unsigned char*)data; - mipmap.len = dataLen; + mipmap.len = static_cast(dataLen); return initWithMipmaps(&mipmap, 1, pixelFormat, pixelsWide, pixelsHigh); //update information @@ -546,7 +546,7 @@ bool Texture2D::initWithData(const void *data, long dataLen, Texture2D::PixelFor } -bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, long pixelsWide, long pixelsHigh) +bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh) { //the pixelFormat must be a certain value CCASSERT(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); @@ -622,8 +622,8 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat CHECK_GL_ERROR_DEBUG(); // clean possible GL error // Specify OpenGL texture image - long width = pixelsWide; - long height = pixelsHigh; + int width = pixelsWide; + int height = pixelsHigh; for (int i = 0; i < mipmapsNum; ++i) { @@ -641,7 +641,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat if (i > 0 && (width != height || ccNextPOT(width) != width )) { - CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%ld != height=%ld", i, width, height); + CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%d != height=%d", i, width, height); } GLenum err = glGetError(); @@ -742,7 +742,7 @@ bool Texture2D::initWithImage(Image *image, PixelFormat format) } unsigned char* outTempData = NULL; - int outTempDataLen = 0; + ssize_t outTempDataLen = 0; pixelFormat = convertDataToFormat(tempData, tempDataLen, renderFormat, pixelFormat, &outTempData, &outTempDataLen); @@ -774,7 +774,7 @@ bool Texture2D::initWithImage(Image *image, PixelFormat format) } } -Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { @@ -823,7 +823,7 @@ Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, l return format; } -Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { @@ -878,7 +878,7 @@ Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, return format; } -Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { @@ -926,7 +926,7 @@ Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* dat return format; } -Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) @@ -998,7 +998,7 @@ rgb(2) -> 1235678 rgba(1) -> 12345678 */ -Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (originFormat) { @@ -1243,7 +1243,7 @@ void Texture2D::PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied) void Texture2D::generateMipmap() { - CCASSERT( static_cast(_pixelsWide) == ccNextPOT(_pixelsWide) && static_cast(_pixelsHigh) == ccNextPOT(_pixelsHigh), "Mipmap texture only works in POT textures"); + CCASSERT(_pixelsWide == ccNextPOT(_pixelsWide) && _pixelsHigh == ccNextPOT(_pixelsHigh), "Mipmap texture only works in POT textures"); GL::bindTexture2D( _name ); glGenerateMipmap(GL_TEXTURE_2D); _hasMipmaps = true; @@ -1256,8 +1256,8 @@ bool Texture2D::hasMipmaps() const void Texture2D::setTexParameters(const TexParams &texParams) { - CCASSERT( (static_cast(_pixelsWide) == ccNextPOT(_pixelsWide) || texParams.wrapS == GL_CLAMP_TO_EDGE) && - (static_cast(_pixelsHigh) == ccNextPOT(_pixelsHigh) || texParams.wrapT == GL_CLAMP_TO_EDGE), + CCASSERT((_pixelsWide == ccNextPOT(_pixelsWide) || texParams.wrapS == GL_CLAMP_TO_EDGE) && + (_pixelsHigh == ccNextPOT(_pixelsHigh) || texParams.wrapT == GL_CLAMP_TO_EDGE), "GL_CLAMP_TO_EDGE should be used in NPOT dimensions"); GL::bindTexture2D( _name ); diff --git a/cocos/2d/CCTexture2D.h b/cocos/2d/CCTexture2D.h index 96c861c341..03b91e49b9 100644 --- a/cocos/2d/CCTexture2D.h +++ b/cocos/2d/CCTexture2D.h @@ -217,10 +217,10 @@ public: * @js NA * @lua NA */ - bool initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize); + bool initWithData(const void *data, ssize_t dataLen, Texture2D::PixelFormat pixelFormat, int pixelsWide, int pixelsHigh, const Size& contentSize); /** Initializes with mipmaps */ - bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh); + bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, int pixelsWide, int pixelsHigh); /** Drawing extensions to make it easy to draw basic quads using a Texture2D object. @@ -327,10 +327,10 @@ public: Texture2D::PixelFormat getPixelFormat() const; /** Gets the width of the texture in pixels */ - long getPixelsWide() const; + int getPixelsWide() const; /** Gets the height of the texture in pixels */ - long getPixelsHigh() const; + int getPixelsHigh() const; /** Gets the texture name */ GLuint getName() const; @@ -361,56 +361,56 @@ private: Convert the format to the format param you specified, if the format is PixelFormat::Automatic, it will detect it automatically and convert to the closest format for you. It will return the converted format to you. if the outData != data, you must delete it manually. */ - static PixelFormat convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertDataToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, ssize_t* outDataLen); - static PixelFormat convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertI8ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen); + static PixelFormat convertAI88ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen); + static PixelFormat convertRGB888ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen); + static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen); //I8 to XXX - static void convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertI8ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertI8ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertI8ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertI8ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertI8ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData); //AI88 to XXX - static void convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertAI88ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertAI88ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertAI88ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertAI88ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertAI88ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertAI88ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData); //RGB888 to XXX - static void convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGB888ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGB888ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGB888ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGB888ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGB888ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData); //RGBA8888 to XXX - static void convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGBA8888ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGBA8888ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGBA8888ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGBA8888ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData); protected: /** pixel format of the texture */ Texture2D::PixelFormat _pixelFormat; /** width in pixels */ - long _pixelsWide; + int _pixelsWide; /** height in pixels */ - long _pixelsHigh; + int _pixelsHigh; /** texture name */ GLuint _name; diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index ec42b9dbfd..1a325d248b 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -74,12 +74,12 @@ TextureAtlas::~TextureAtlas() #endif } -long TextureAtlas::getTotalQuads() const +int TextureAtlas::getTotalQuads() const { return _totalQuads; } -long TextureAtlas::getCapacity() const +int TextureAtlas::getCapacity() const { return _capacity; } @@ -110,7 +110,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas * TextureAtlas::create(const char* file, long capacity) +TextureAtlas * TextureAtlas::create(const char* file, int capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if(textureAtlas && textureAtlas->initWithFile(file, capacity)) @@ -122,7 +122,7 @@ TextureAtlas * TextureAtlas::create(const char* file, long capacity) return NULL; } -TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity) +TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if (textureAtlas && textureAtlas->initWithTexture(texture, capacity)) @@ -134,7 +134,7 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity return NULL; } -bool TextureAtlas::initWithFile(const char * file, long capacity) +bool TextureAtlas::initWithFile(const char * file, int capacity) { // retained in property Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file); @@ -150,7 +150,7 @@ bool TextureAtlas::initWithFile(const char * file, long capacity) } } -bool TextureAtlas::initWithTexture(Texture2D *texture, long capacity) +bool TextureAtlas::initWithTexture(Texture2D *texture, int capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -224,7 +224,7 @@ void TextureAtlas::listenBackToForeground(Object *obj) const char* TextureAtlas::description() const { - return String::createWithFormat("", _totalQuads)->getCString(); + return String::createWithFormat("", _totalQuads)->getCString(); } @@ -317,7 +317,7 @@ void TextureAtlas::mapBuffers() // TextureAtlas - Update, Insert, Move & Remove -void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, long index) +void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index) { CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index"); @@ -330,7 +330,7 @@ void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, long index) } -void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index) +void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index) { CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index"); @@ -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; + auto remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining > 0) @@ -354,7 +354,7 @@ void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index) } -void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) +void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount"); @@ -363,7 +363,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); // issue #575. index can be > totalQuads - long remaining = (_totalQuads-1) - index - amount; + auto remaining = (_totalQuads-1) - index - amount; // last object doesn't need to be moved if( remaining > 0) @@ -373,9 +373,9 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) } - long max = index + amount; + auto max = index + amount; int j = 0; - for (long i = index; i < max ; i++) + for (int i = index; i < max ; i++) { _quads[index] = quads[j]; index++; @@ -385,7 +385,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) _dirty = true; } -void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) +void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) { CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -396,9 +396,9 @@ void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) } // because it is ambiguous in iphone, so we implement abs ourselves // unsigned int howMany = abs( oldIndex - newIndex); - long howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); - long dst = oldIndex; - long src = oldIndex + 1; + auto howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); + auto dst = oldIndex; + auto src = oldIndex + 1; if( oldIndex > newIndex) { dst = newIndex+1; @@ -414,11 +414,11 @@ void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) _dirty = true; } -void TextureAtlas::removeQuadAtIndex(long index) +void TextureAtlas::removeQuadAtIndex(int index) { CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); - long remaining = (_totalQuads-1) - index; + auto remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining ) @@ -433,11 +433,11 @@ void TextureAtlas::removeQuadAtIndex(long index) _dirty = true; } -void TextureAtlas::removeQuadsAtIndex(long index, long amount) +void TextureAtlas::removeQuadsAtIndex(int index, int amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); - long remaining = (_totalQuads) - (index + amount); + auto remaining = (_totalQuads) - (index + amount); _totalQuads -= amount; @@ -455,14 +455,14 @@ void TextureAtlas::removeAllQuads() } // TextureAtlas - Resize -bool TextureAtlas::resizeCapacity(long newCapacity) +bool TextureAtlas::resizeCapacity(int newCapacity) { CCASSERT(newCapacity>=0, "capacity >= 0"); if( newCapacity == _capacity ) { return true; } - long oldCapactiy = _capacity; + auto oldCapactiy = _capacity; // update capacity and totolQuads _totalQuads = MIN(_totalQuads, newCapacity); _capacity = newCapacity; @@ -529,13 +529,13 @@ bool TextureAtlas::resizeCapacity(long newCapacity) return true; } -void TextureAtlas::increaseTotalQuadsWith(long amount) +void TextureAtlas::increaseTotalQuadsWith(int amount) { CCASSERT(amount>=0, "amount >= 0"); _totalQuads += amount; } -void TextureAtlas::moveQuadsFromIndex(long oldIndex, long amount, long newIndex) +void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) { CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -567,7 +567,7 @@ void TextureAtlas::moveQuadsFromIndex(long oldIndex, long amount, long newIndex) _dirty = true; } -void TextureAtlas::moveQuadsFromIndex(long index, long newIndex) +void TextureAtlas::moveQuadsFromIndex(int index, int newIndex) { CCASSERT(index>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds"); @@ -575,14 +575,14 @@ void TextureAtlas::moveQuadsFromIndex(long index, long newIndex) memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0])); } -void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount) +void TextureAtlas::fillWithEmptyQuadsFromIndex(int index, int amount) { CCASSERT(index>=0 && amount>=0, "values must be >= 0"); V3F_C4B_T2F_Quad quad; memset(&quad, 0, sizeof(quad)); - long to = index + amount; - for (long i = index ; i < to ; i++) + auto to = index + amount; + for (int i = index ; i < to ; i++) { _quads[i] = quad; } @@ -595,13 +595,13 @@ void TextureAtlas::drawQuads() this->drawNumberOfQuads(_totalQuads, 0); } -void TextureAtlas::drawNumberOfQuads(long numberOfQuads) +void TextureAtlas::drawNumberOfQuads(int numberOfQuads) { CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0"); this->drawNumberOfQuads(numberOfQuads, 0); } -void TextureAtlas::drawNumberOfQuads(long numberOfQuads, long start) +void TextureAtlas::drawNumberOfQuads(int numberOfQuads, int start) { CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0"); diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index 86f0ba209f..47a5c1c484 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -59,13 +59,13 @@ public: /** creates a TextureAtlas with an filename and with an initial capacity for Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* create(const char* file , long capacity); + static TextureAtlas* create(const char* file , int capacity); /** creates a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for n Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* createWithTexture(Texture2D *texture, long capacity); + static TextureAtlas* createWithTexture(Texture2D *texture, int capacity); /** * @js ctor */ @@ -81,7 +81,7 @@ public: * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) */ - bool initWithFile(const char* file, long capacity); + bool initWithFile(const char* file, int capacity); /** initializes a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for Quads. @@ -89,43 +89,43 @@ public: * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) */ - bool initWithTexture(Texture2D *texture, long capacity); + bool initWithTexture(Texture2D *texture, int capacity); /** updates a Quad (texture, vertex and color) at a certain index * index must be between 0 and the atlas capacity - 1 @since v0.8 */ - void updateQuad(V3F_C4B_T2F_Quad* quad, long index); + void updateQuad(V3F_C4B_T2F_Quad* quad, int index); /** Inserts a Quad (texture, vertex and color) at a certain index index must be between 0 and the atlas capacity - 1 @since v0.8 */ - void insertQuad(V3F_C4B_T2F_Quad* quad, long index); + void insertQuad(V3F_C4B_T2F_Quad* quad, int index); /** Inserts a c array of quads at a given index index must be between 0 and the atlas capacity - 1 this method doesn't enlarge the array when amount + index > totalQuads @since v1.1 */ - void insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount); + void insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount); /** Removes the quad that is located at a certain index and inserts it at a new index This operation is faster than removing and inserting in a quad in 2 different steps @since v0.7.2 */ - void insertQuadFromIndex(long fromIndex, long newIndex); + void insertQuadFromIndex(int fromIndex, int newIndex); /** removes a quad at a given index number. The capacity remains the same, but the total number of quads to be drawn is reduced in 1 @since v0.7.2 */ - void removeQuadAtIndex(long index); + void removeQuadAtIndex(int index); /** removes a amount of quads starting from index @since 1.1 */ - void removeQuadsAtIndex(long index, long amount); + void removeQuadsAtIndex(int index, int amount); /** removes all Quads. The TextureAtlas capacity remains untouched. No memory is freed. The total number of quads to be drawn will be 0 @@ -138,19 +138,19 @@ public: * It returns true if the resize was successful. * If it fails to resize the capacity it will return false with a new capacity of 0. */ - bool resizeCapacity(long capacity); + bool resizeCapacity(int capacity); /** Used internally by ParticleBatchNode don't use this unless you know what you're doing @since 1.1 */ - void increaseTotalQuadsWith(long amount); + void increaseTotalQuadsWith(int amount); /** Moves an amount of quads from oldIndex at newIndex @since v1.1 */ - void moveQuadsFromIndex(long oldIndex, long amount, long newIndex); + void moveQuadsFromIndex(int oldIndex, int amount, int newIndex); /** Moves quads from index till totalQuads to the newIndex @@ -158,26 +158,26 @@ public: This method doesn't enlarge the array if newIndex + quads to be moved > capacity @since 1.1 */ - void moveQuadsFromIndex(long index, long newIndex); + void moveQuadsFromIndex(int index, int newIndex); /** Ensures that after a realloc quads are still empty Used internally by ParticleBatchNode @since 1.1 */ - void fillWithEmptyQuadsFromIndex(long index, long amount); + void fillWithEmptyQuadsFromIndex(int index, int amount); /** draws n quads * n can't be greater than the capacity of the Atlas */ - void drawNumberOfQuads(long n); + void drawNumberOfQuads(int n); /** draws n quads from an index (offset). n + start can't be greater than the capacity of the atlas @since v1.0 */ - void drawNumberOfQuads(long numberOfQuads, long start); + void drawNumberOfQuads(int numberOfQuads, int start); /** draws all the Atlas's Quads */ @@ -197,10 +197,10 @@ public: const char* description() const; /** Gets the quantity of quads that are going to be drawn */ - long getTotalQuads() const; + int getTotalQuads() const; /** Gets the quantity of quads that can be stored with the current texture atlas size */ - long getCapacity() const; + int getCapacity() const; /** Gets the texture of the texture atlas */ Texture2D* getTexture() const; @@ -226,9 +226,9 @@ protected: GLuint _buffersVBO[2]; //0: vertex 1: indices bool _dirty; //indicates whether or not the array buffer of the VBO needs to be updated /** quantity of quads that are going to be drawn */ - long _totalQuads; + int _totalQuads; /** quantity of quads that can be stored with the current texture atlas size */ - long _capacity; + int _capacity; /** Texture of the texture atlas */ Texture2D* _texture; /** Quads that are going to be rendered */ diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index a16f85f28d..55afd2588d 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -34,7 +34,6 @@ THE SOFTWARE. #include "ccMacros.h" #include "CCDirector.h" #include "platform/CCFileUtils.h" -#include "platform/CCThread.h" #include "ccUtils.h" #include "CCScheduler.h" #include "CCString.h" @@ -93,18 +92,6 @@ const char* TextureCache::description() const return String::createWithFormat("", _textures.size() )->getCString(); } -//Dictionary* TextureCache::snapshotTextures() -//{ -// Dictionary* pRet = new Dictionary(); -// DictElement* pElement = NULL; -// CCDICT_FOREACH(_textures, pElement) -// { -// pRet->setObject(pElement->getObject(), pElement->getStrKey()); -// } -// pRet->autorelease(); -// return pRet; -//} - void TextureCache::addImageAsync(const std::string &path, Object *target, SEL_CallFuncO selector) { Texture2D *texture = NULL; @@ -446,7 +433,7 @@ void TextureCache::dumpCachedTextureInfo() const Texture2D* tex = it->second; unsigned int bpp = tex->getBitsPerPixelForFormat(); // Each texture takes up width * height * bytesPerPixel bytes. - long bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; + auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; totalBytes += bytes; count++; log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", @@ -607,7 +594,7 @@ void VolatileTextureMgr::reloadAllTextures() case VolatileTexture::kImageFile: { Image* image = new Image(); - long size = 0; + ssize_t size = 0; unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &size); if (image && image->initWithImageData(pBuffer, size)) diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index 1d40acf461..c01db753bf 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -58,7 +58,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; //CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt"); - long nSize; + ssize_t nSize; char* pXmlBuffer = (char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) @@ -404,7 +404,7 @@ void UserDefault::setDataForKey(const char* pKey, const Data& value) { char *encodedData = 0; - base64Encode(value.getBytes(), value.getSize(), &encodedData); + base64Encode(value.getBytes(), static_cast(value.getSize()), &encodedData); setValueForKey(pKey, encodedData); diff --git a/cocos/2d/CCUserDefault.mm b/cocos/2d/CCUserDefault.mm index e64f339b8d..09cc5aec1c 100644 --- a/cocos/2d/CCUserDefault.mm +++ b/cocos/2d/CCUserDefault.mm @@ -73,7 +73,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - long size; + ssize_t size; char* pXmlBuffer = (char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) @@ -420,11 +420,11 @@ Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue) else { unsigned char *bytes = {0}; - unsigned long size = 0; + int size = 0; if (data.length > 0) { bytes = (unsigned char*)data.bytes; - size = data.length; + size = static_cast(data.length); } Data *ret = new Data(bytes, size); diff --git a/cocos/2d/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp index 8f6895f572..7a381aa634 100644 --- a/cocos/2d/CCUserDefaultAndroid.cpp +++ b/cocos/2d/CCUserDefaultAndroid.cpp @@ -74,7 +74,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - long size; + ssize_t size; char* pXmlBuffer = (char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) @@ -470,7 +470,7 @@ void UserDefault::setDataForKey(const char* pKey, const Data& value) CCLOG("SET DATA ENCODED: --%s", encodedData); - return setStringForKeyJNI(pKey, encodedData); + setStringForKeyJNI(pKey, encodedData); if (encodedData) free(encodedData); diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index ebde2f9963..6ac9272f24 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -39,7 +39,7 @@ bool ZipUtils::s_bEncryptionKeyIsValid = false; // --------------------- ZipUtils --------------------- -inline void ZipUtils::decodeEncodedPvr(unsigned int *data, long len) +inline void ZipUtils::decodeEncodedPvr(unsigned int *data, ssize_t len) { const int enclen = 1024; const int securelen = 512; @@ -108,7 +108,7 @@ inline void ZipUtils::decodeEncodedPvr(unsigned int *data, long len) } } -inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, long len) +inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, ssize_t len) { unsigned int cs = 0; const int cslen = 128; @@ -127,12 +127,12 @@ inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, long len) // Should buffer factor be 1.5 instead of 2 ? #define BUFFER_INC_FACTOR (2) -int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint) +int ZipUtils::inflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t *outLength, ssize_t outLenghtHint) { /* ret value */ int err = Z_OK; - long bufferSize = outLenghtHint; + ssize_t bufferSize = outLenghtHint; *out = (unsigned char*)malloc(bufferSize); z_stream d_stream; /* decompression stream */ @@ -141,9 +141,9 @@ int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned c d_stream.opaque = (voidpf)0; d_stream.next_in = in; - d_stream.avail_in = inLength; + d_stream.avail_in = static_cast(inLength); d_stream.next_out = *out; - d_stream.avail_out = bufferSize; + d_stream.avail_out = static_cast(bufferSize); /* window size to hold 256k */ if( (err = inflateInit2(&d_stream, 15 + 32)) != Z_OK ) @@ -182,7 +182,7 @@ int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned c } d_stream.next_out = *out + bufferSize; - d_stream.avail_out = bufferSize; + d_stream.avail_out = static_cast(bufferSize); bufferSize *= BUFFER_INC_FACTOR; } } @@ -192,9 +192,9 @@ int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned c return err; } -int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint) +ssize_t ZipUtils::inflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t outLengthHint) { - long outLength = 0; + ssize_t outLength = 0; int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); if (err != Z_OK || *out == NULL) { @@ -225,7 +225,7 @@ int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned c return outLength; } -int ZipUtils::inflateMemory(unsigned char *in, long inLength, unsigned char **out) +ssize_t ZipUtils::inflateMemory(unsigned char *in, ssize_t inLength, unsigned char **out) { // 256k for hint return inflateMemoryWithHint(in, inLength, out, 256 * 1024); @@ -363,7 +363,7 @@ bool ZipUtils::isGZipBuffer(const unsigned char *buffer, long len) } -int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsigned char **out) +int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, ssize_t bufferLen, unsigned char **out) { struct CCZHeader *header = (struct CCZHeader*) buffer; @@ -407,7 +407,7 @@ int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsi // decrypt unsigned int* ints = (unsigned int*)(buffer+12); - int enclen = (bufferLen-12)/4; + ssize_t enclen = (bufferLen-12)/4; decodeEncodedPvr(ints, enclen); @@ -439,7 +439,7 @@ int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsi } unsigned long destlen = len; - unsigned long source = (unsigned long) buffer + sizeof(*header); + size_t source = (size_t) buffer + sizeof(*header); int ret = uncompress(*out, &destlen, (Bytef*)source, bufferLen - sizeof(*header) ); if( ret != Z_OK ) @@ -591,7 +591,7 @@ bool ZipFile::fileExists(const std::string &fileName) const return ret; } -unsigned char *ZipFile::getFileData(const std::string &fileName, long *size) +unsigned char *ZipFile::getFileData(const std::string &fileName, ssize_t *size) { unsigned char * buffer = NULL; if (size) @@ -614,7 +614,7 @@ unsigned char *ZipFile::getFileData(const std::string &fileName, long *size) CC_BREAK_IF(UNZ_OK != nRet); buffer = (unsigned char*)malloc(fileInfo.uncompressed_size); - int CC_UNUSED nSize = unzReadCurrentFile(_data->zipFile, buffer, fileInfo.uncompressed_size); + int CC_UNUSED nSize = unzReadCurrentFile(_data->zipFile, buffer, static_cast(fileInfo.uncompressed_size)); CCASSERT(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong"); if (size) diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index c322f8300a..1d2275633b 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -65,8 +65,8 @@ namespace cocos2d * @since v0.8.1 */ - CC_DEPRECATED_ATTRIBUTE static int ccInflateMemory(unsigned char *in, long inLength, unsigned char **out) { return inflateMemory(in, inLength, out); } - static int inflateMemory(unsigned char *in, long inLength, unsigned char **out); + CC_DEPRECATED_ATTRIBUTE static ssize_t ccInflateMemory(unsigned char *in, ssize_t inLength, unsigned char **out) { return inflateMemory(in, inLength, out); } + static ssize_t inflateMemory(unsigned char *in, ssize_t inLength, unsigned char **out); /** * Inflates either zlib or gzip deflated memory. The inflated memory is @@ -78,8 +78,8 @@ namespace cocos2d * @since v1.0.0 */ - CC_DEPRECATED_ATTRIBUTE static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint) { return inflateMemoryWithHint(in, inLength, out, outLengthHint); } - static int inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint); + CC_DEPRECATED_ATTRIBUTE static ssize_t ccInflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t outLengthHint) { return inflateMemoryWithHint(in, inLength, out, outLengthHint); } + static ssize_t inflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t outLengthHint); /** inflates a GZip file into memory * @@ -105,8 +105,8 @@ namespace cocos2d * * @since v3.0 */ - CC_DEPRECATED_ATTRIBUTE static bool ccIsGZipBuffer(const unsigned char *buffer, long len) { return isGZipBuffer(buffer, len); } - static bool isGZipBuffer(const unsigned char *buffer, long len); + CC_DEPRECATED_ATTRIBUTE static bool ccIsGZipBuffer(const unsigned char *buffer, ssize_t len) { return isGZipBuffer(buffer, len); } + static bool isGZipBuffer(const unsigned char *buffer, ssize_t len); /** inflates a CCZ file into memory * @@ -123,8 +123,8 @@ namespace cocos2d * * @since v3.0 */ - CC_DEPRECATED_ATTRIBUTE static int ccInflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out) { return inflateCCZBuffer(buffer, len, out); } - static int inflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out); + CC_DEPRECATED_ATTRIBUTE static int ccInflateCCZBuffer(const unsigned char *buffer, ssize_t len, unsigned char **out) { return inflateCCZBuffer(buffer, len, out); } + static int inflateCCZBuffer(const unsigned char *buffer, ssize_t len, unsigned char **out); /** test a file is a CCZ format file or not * @@ -141,8 +141,8 @@ namespace cocos2d * * @since v3.0 */ - CC_DEPRECATED_ATTRIBUTE static bool ccIsCCZBuffer(const unsigned char *buffer, long len) { return isCCZBuffer(buffer, len); } - static bool isCCZBuffer(const unsigned char *buffer, long len); + CC_DEPRECATED_ATTRIBUTE static bool ccIsCCZBuffer(const unsigned char *buffer, ssize_t len) { return isCCZBuffer(buffer, len); } + static bool isCCZBuffer(const unsigned char *buffer, ssize_t len); /** Sets the pvr.ccz encryption key parts separately for added * security. @@ -199,9 +199,9 @@ namespace cocos2d static void setPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); private: - static int inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint); - static inline void decodeEncodedPvr (unsigned int *data, long len); - static inline unsigned int checksumPvr(const unsigned int *data, long len); + static int inflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t *outLength, ssize_t outLenghtHint); + static inline void decodeEncodedPvr (unsigned int *data, ssize_t len); + static inline unsigned int checksumPvr(const unsigned int *data, ssize_t len); static unsigned int s_uEncryptedPvrKeyParts[4]; static unsigned int s_uEncryptionKey[1024]; @@ -264,7 +264,7 @@ namespace cocos2d * * @since v2.0.5 */ - unsigned char *getFileData(const std::string &fileName, long *size); + unsigned char *getFileData(const std::string &fileName, ssize_t *size); private: /** Internal data like zip file pointer / file list array and so on */ diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index f280bc5787..2607450a55 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -28,10 +28,10 @@ THE SOFTWARE. NS_CC_BEGIN -const long CC_INVALID_INDEX = -1; +const int CC_INVALID_INDEX = -1; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(long capacity) +ccArray* ccArrayNew(int capacity) { if (capacity == 0) capacity = 7; @@ -68,13 +68,13 @@ void ccArrayDoubleCapacity(ccArray *arr) arr->arr = newArr; } -void ccArrayEnsureExtraCapacity(ccArray *arr, long extra) +void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) { while (arr->max < arr->num + extra) { - CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%lu] to [%lu].", - (long) arr->max, - (long) arr->max*2); + CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].", + arr->max, + arr->max*2); ccArrayDoubleCapacity(arr); } @@ -82,7 +82,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, long extra) void ccArrayShrink(ccArray *arr) { - long newSize = 0; + int newSize = 0; //only resize when necessary if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) @@ -104,13 +104,13 @@ void ccArrayShrink(ccArray *arr) } /** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */ -long ccArrayGetIndexOfObject(ccArray *arr, Object* object) +int ccArrayGetIndexOfObject(ccArray *arr, Object* object) { - const long arrNum = arr->num; + const auto arrNum = arr->num; Object** ptr = arr->arr; - for(long i = 0; i < arrNum; ++i, ++ptr) + for (int i = 0; i < arrNum; ++i, ++ptr) { - if( *ptr == object ) + if (*ptr == object) return i; } @@ -143,7 +143,7 @@ void ccArrayAppendObjectWithResize(ccArray *arr, Object* object) enough capacity. */ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr) { - for(long i = 0; i < plusArr->num; i++) + for (int i = 0; i < plusArr->num; i++) { ccArrayAppendObject(arr, plusArr->arr[i]); } @@ -157,15 +157,15 @@ void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr) } /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index) +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index) { CCASSERT(index<=arr->num, "Invalid index. Out of bounds"); CCASSERT(object != NULL, "Invalid parameter!"); ccArrayEnsureExtraCapacity(arr, 1); - long remaining = arr->num - index; - if( remaining > 0) + int remaining = arr->num - index; + if (remaining > 0) { memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining ); } @@ -176,7 +176,7 @@ void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index) } /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2) +void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2) { CCASSERT(index1>=0 && index1 < arr->num, "(1) Invalid index. Out of bounds"); CCASSERT(index2>=0 && index2 < arr->num, "(2) Invalid index. Out of bounds"); @@ -190,7 +190,7 @@ void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2) /** Removes all objects from arr */ void ccArrayRemoveAllObjects(ccArray *arr) { - while( arr->num > 0 ) + while (arr->num > 0) { (arr->arr[--arr->num])->release(); } @@ -198,7 +198,7 @@ void ccArrayRemoveAllObjects(ccArray *arr) /** Removes object at specified index and pushes back all subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj/* = true*/) +void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = true*/) { CCASSERT(arr && arr->num > 0 && index>=0 && index < arr->num, "Invalid index. Out of bounds"); if (bReleaseObj) @@ -208,7 +208,7 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj/* = t arr->num--; - long remaining = arr->num - index; + int remaining = arr->num - index; if(remaining>0) { memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*)); @@ -218,16 +218,16 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj/* = t /** Removes object at specified index and fills the gap with the last object, thereby avoiding the need to push back subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index) +void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index) { CC_SAFE_RELEASE(arr->arr[index]); - long last = --arr->num; + auto last = --arr->num; arr->arr[index] = arr->arr[last]; } void ccArrayFastRemoveObject(ccArray *arr, Object* object) { - long index = ccArrayGetIndexOfObject(arr, object); + auto index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayFastRemoveObjectAtIndex(arr, index); @@ -238,7 +238,7 @@ void ccArrayFastRemoveObject(ccArray *arr, Object* object) found the function has no effect. */ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/) { - long index = ccArrayGetIndexOfObject(arr, object); + auto index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj); @@ -249,7 +249,7 @@ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true first matching instance in arr will be removed. */ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) { - for(long i = 0; i < minusArr->num; i++) + for (int i = 0; i < minusArr->num; i++) { ccArrayRemoveObject(arr, minusArr->arr[i]); } @@ -259,12 +259,11 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) matching instances in arr will be removed. */ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) { - long back = 0; - long i = 0; + int back = 0; - for( i = 0; i < arr->num; i++) + for (int i = 0; i < arr->num; i++) { - if( ccArrayContainsObject(minusArr, arr->arr[i]) ) + if (ccArrayContainsObject(minusArr, arr->arr[i])) { CC_SAFE_RELEASE(arr->arr[i]); back++; @@ -282,16 +281,16 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) // #pragma mark ccCArray for Values (c structures) /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(long capacity) +ccCArray* ccCArrayNew(int capacity) { if (capacity == 0) { capacity = 7; } - ccCArray *arr = (ccCArray*)malloc( sizeof(ccCArray) ); + ccCArray *arr = (ccCArray*)malloc(sizeof(ccCArray)); arr->num = 0; - arr->arr = (void**)malloc( capacity * sizeof(void*) ); + arr->arr = (void**)malloc(capacity * sizeof(void*)); arr->max = capacity; return arr; @@ -300,7 +299,7 @@ ccCArray* ccCArrayNew(long capacity) /** Frees C array after removing all remaining values. Silently ignores NULL arr. */ void ccCArrayFree(ccCArray *arr) { - if( arr == NULL ) + if (arr == NULL) { return; } @@ -317,15 +316,15 @@ void ccCArrayDoubleCapacity(ccCArray *arr) } /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra) +void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra) { ccArrayEnsureExtraCapacity((ccArray*)arr,extra); } /** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */ -long ccCArrayGetIndexOfValue(ccCArray *arr, void* value) +int ccCArrayGetIndexOfValue(ccCArray *arr, void* value) { - for(long i = 0; i < arr->num; i++) + for(int i = 0; i < arr->num; i++) { if( arr->arr[i] == value ) return i; @@ -340,11 +339,11 @@ bool ccCArrayContainsValue(ccCArray *arr, void* value) } /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index) +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index) { CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index"); - long remaining = arr->num - index; + auto remaining = arr->num - index; // make sure it has enough capacity if (arr->num + 1 == arr->max) { @@ -385,7 +384,7 @@ void ccCArrayAppendValueWithResize(ccCArray *arr, void* value) enough capacity. */ void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) { - for( long i = 0; i < plusArr->num; i++) + for( int i = 0; i < plusArr->num; i++) { ccCArrayAppendValue(arr, plusArr->arr[i]); } @@ -408,9 +407,9 @@ void ccCArrayRemoveAllValues(ccCArray *arr) Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index) +void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) { - for( long last = --arr->num; index < last; index++) + for( int last = --arr->num; index < last; index++) { arr->arr[index] = arr->arr[index + 1]; } @@ -421,9 +420,9 @@ void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index) Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index) +void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) { - long last = --arr->num; + auto last = --arr->num; arr->arr[index] = arr->arr[last]; } @@ -432,7 +431,7 @@ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index) */ void ccCArrayRemoveValue(ccCArray *arr, void* value) { - long index = ccCArrayGetIndexOfValue(arr, value); + auto index = ccCArrayGetIndexOfValue(arr, value); if (index != CC_INVALID_INDEX) { ccCArrayRemoveValueAtIndex(arr, index); @@ -444,7 +443,7 @@ void ccCArrayRemoveValue(ccCArray *arr, void* value) */ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) { - for(long i = 0; i < minusArr->num; i++) + for(int i = 0; i < minusArr->num; i++) { ccCArrayRemoveValue(arr, minusArr->arr[i]); } @@ -455,9 +454,9 @@ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) */ void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) { - long back = 0; + int back = 0; - for(long i = 0; i < arr->num; i++) + for(int i = 0; i < arr->num; i++) { if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) { diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index 2bfff6224f..fff5152904 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -51,20 +51,20 @@ THE SOFTWARE. NS_CC_BEGIN -extern const long CC_INVALID_INDEX; +extern const int CC_INVALID_INDEX; // Easy integration #define CCARRAYDATA_FOREACH(__array__, __object__) \ -__object__=__array__->arr[0]; for(long i=0, num=__array__->num; iarr[i]) \ +__object__=__array__->arr[0]; for(int i=0, num=__array__->num; iarr[i]) \ typedef struct _ccArray { - long num, max; + int num, max; Object** arr; } ccArray; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(long capacity); +ccArray* ccArrayNew(int capacity); /** Frees array after removing all remaining objects. Silently ignores nil arr. */ void ccArrayFree(ccArray*& arr); @@ -73,13 +73,13 @@ void ccArrayFree(ccArray*& arr); void ccArrayDoubleCapacity(ccArray *arr); /** Increases array capacity such that max >= num + extra. */ -void ccArrayEnsureExtraCapacity(ccArray *arr, long extra); +void ccArrayEnsureExtraCapacity(ccArray *arr, int extra); /** shrinks the array so the memory footprint corresponds with the number of items */ void ccArrayShrink(ccArray *arr); /** Returns index of first occurrence of object, NSNotFound if object not found. */ -long ccArrayGetIndexOfObject(ccArray *arr, Object* object); +int ccArrayGetIndexOfObject(ccArray *arr, Object* object); /** Returns a Boolean value that indicates whether object is present in array. */ bool ccArrayContainsObject(ccArray *arr, Object* object); @@ -98,22 +98,22 @@ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr); void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr); /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index); +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index); /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2); +void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2); /** Removes all objects from arr */ void ccArrayRemoveAllObjects(ccArray *arr); /** Removes object at specified index and pushes back all subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj = true); +void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj = true); /** Removes object at specified index and fills the gap with the last object, thereby avoiding the need to push back subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index); +void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index); void ccArrayFastRemoveObject(ccArray *arr, Object* object); @@ -133,12 +133,12 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr); // #pragma mark ccCArray for Values (c structures) typedef struct _ccCArray { - long num, max; + int num, max; void** arr; } ccCArray; /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(long capacity); +ccCArray* ccCArrayNew(int capacity); /** Frees C array after removing all remaining values. Silently ignores nil arr. */ void ccCArrayFree(ccCArray *arr); @@ -147,16 +147,16 @@ void ccCArrayFree(ccCArray *arr); void ccCArrayDoubleCapacity(ccCArray *arr); /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra); +void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra); /** Returns index of first occurrence of value, NSNotFound if value not found. */ -long ccCArrayGetIndexOfValue(ccCArray *arr, void* value); +int ccCArrayGetIndexOfValue(ccCArray *arr, void* value); /** Returns a Boolean value that indicates whether value is present in the C array. */ bool ccCArrayContainsValue(ccCArray *arr, void* value); /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index); +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index); /** Appends an value. Behavior undefined if array doesn't have enough capacity. */ void ccCArrayAppendValue(ccCArray *arr, void* value); @@ -178,14 +178,14 @@ void ccCArrayRemoveAllValues(ccCArray *arr); Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index); +void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index); /** Removes value at specified index and fills the gap with the last value, thereby avoiding the need to push back subsequent values. Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index); +void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index); /** Searches for the first occurrence of value and removes it. If value is not found the function has no effect. @since v0.99.4 diff --git a/cocos/2d/ccConfig.h b/cocos/2d/ccConfig.h index f801066bfe..5858fe88a0 100644 --- a/cocos/2d/ccConfig.h +++ b/cocos/2d/ccConfig.h @@ -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__ diff --git a/cocos/2d/ccUTF8.cpp b/cocos/2d/ccUTF8.cpp index 963d5cd2c4..6546dcf3e3 100644 --- a/cocos/2d/ccUTF8.cpp +++ b/cocos/2d/ccUTF8.cpp @@ -129,7 +129,7 @@ static const char *const g_utf8_skip = utf8_skip_data; * */ unsigned int cc_utf8_find_last_not_char(std::vector str, unsigned short c) { - int len = str.size(); + int len = static_cast(str.size()); int i = len - 1; for (; i >= 0; --i) @@ -148,7 +148,7 @@ unsigned int cc_utf8_find_last_not_char(std::vector str, unsigne * */ static void cc_utf8_trim_from(std::vector* str, int index) { - int size = str->size(); + int size = static_cast(str->size()); if (index >= size || index < 0) return; @@ -171,7 +171,7 @@ bool isspace_unicode(unsigned short ch) void cc_utf8_trim_ws(std::vector* str) { - int len = str->size(); + int len = static_cast(str->size()); if ( len <= 0 ) return; @@ -277,7 +277,7 @@ cc_utf8_get_char (const char * p) unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* rUtf16Size/* = NULL */) { - int len = cc_utf8_strlen(str_old, length); + unsigned short len = cc_utf8_strlen(str_old, length); if (rUtf16Size != NULL) { *rUtf16Size = len; } @@ -335,21 +335,23 @@ cc_unichar_to_utf8 (unsigned short c, first = 0xc0; len = 2; } - else if (c < 0x10000) - { - first = 0xe0; - len = 3; - } - else if (c < 0x200000) - { - first = 0xf0; - len = 4; - } - else if (c < 0x4000000) - { - first = 0xf8; - len = 5; - } + // XXX FIXME + // These conditions are alwasy true. +// else if (c < 0x10000) +// { +// first = 0xe0; +// len = 3; +// } +// else if (c < 0x200000) +// { +// first = 0xf0; +// len = 4; +// } +// else if (c < 0x4000000) +// { +// first = 0xf8; +// len = 5; +// } else { first = 0xfc; @@ -452,7 +454,7 @@ cc_utf16_to_utf8 (const unsigned short *str, } /********** DIFFERENT for UTF8/UCS4 **********/ - n_bytes += UTF8_LENGTH (wc); + n_bytes += UTF8_LENGTH (static_cast(wc)); next1: in++; diff --git a/cocos/2d/ccUtils.cpp b/cocos/2d/ccUtils.cpp index d78324565b..e9d6eedf4a 100644 --- a/cocos/2d/ccUtils.cpp +++ b/cocos/2d/ccUtils.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. namespace cocos2d { -unsigned long ccNextPOT(unsigned long x) +int ccNextPOT(int x) { x = x - 1; x = x | (x >> 1); diff --git a/cocos/2d/ccUtils.h b/cocos/2d/ccUtils.h index f882114b0f..3379db33bf 100644 --- a/cocos/2d/ccUtils.h +++ b/cocos/2d/ccUtils.h @@ -43,7 +43,7 @@ Examples: @since v0.99.5 */ -unsigned long ccNextPOT( unsigned long value ); +int ccNextPOT(int value); } diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index b25bb7bee8..da8fbd5317 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -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" @@ -199,6 +202,7 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCNotificationCenter.h" #include "CCProfiling.h" +#include "CCConsole.h" #include "CCUserDefault.h" #include "CCVertex.h" diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 72b52b3b97..a026926c95 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -74,7 +74,7 @@ Disabled $(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) - WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks MultiThreadedDebugDLL @@ -121,7 +121,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou $(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) - WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL @@ -169,6 +169,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + @@ -177,6 +178,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + @@ -327,6 +329,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + @@ -334,12 +337,15 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + + + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 969c60324f..69900696e1 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -560,6 +560,12 @@ physics\chipmunk + + base + + + base + @@ -1125,5 +1131,17 @@ physics\chipmunk + + base + + + base + + + base + + + base + \ No newline at end of file diff --git a/cocos/2d/cocos2dx.props b/cocos/2d/cocos2dx.props index 5abd534933..4e347ee14b 100644 --- a/cocos/2d/cocos2dx.props +++ b/cocos/2d/cocos2dx.props @@ -7,7 +7,7 @@ - opengl32.lib;glew32.lib;libzlib.lib;libpng.lib;libjpeg.lib;libtiff.lib;libwebp.lib;libiconv.lib;glfw3.lib;freetype250.lib;winmm.lib;%(AdditionalDependencies) + opengl32.lib;glew32.lib;libzlib.lib;libpng.lib;libjpeg.lib;libtiff.lib;libwebp.lib;libiconv.lib;glfw3.lib;freetype250.lib;winmm.lib;ws2_32.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) false diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index c6623a234f..2eb4e3495e 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -12,7 +12,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { NULL }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -198,9 +198,9 @@ const std::string& EGLViewProtocol::getViewName() const return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, long ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) { - long id = 0; + int id = 0; float x = 0.0f; float y = 0.0f; int nUnusedIndex = 0; @@ -248,9 +248,9 @@ void EGLViewProtocol::handleTouchesBegin(int num, long ids[], float xs[], float dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, long ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) { - long id = 0; + int id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -280,7 +280,7 @@ void EGLViewProtocol::handleTouchesMove(int num, long ids[], float xs[], float y else { // It is error, should return. - CCLOG("Moving touches with id: %ld error", id); + CCLOG("Moving touches with id: %d error", id); return; } } @@ -296,9 +296,9 @@ void EGLViewProtocol::handleTouchesMove(int num, long ids[], float xs[], float y dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) { - long id = 0; + int id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -333,7 +333,7 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } else { - CCLOG("Ending touches with id: %ld error", id); + CCLOG("Ending touches with id: %d error", id); return; } @@ -356,12 +356,12 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, long ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, long ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index 53f9400dcf..f5ed1255f6 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -135,10 +135,10 @@ public: const std::string& getViewName() const; /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, long ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, long ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, long ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, int ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -157,7 +157,7 @@ public: protected: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); EGLTouchDelegate* _delegate; diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index ddd9c25dfe..6522d88317 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -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 _dictStack; + ValueMap _rootDict; + ValueVector _rootArray; + std::string _curKey; ///< parsed key std::string _curValue; // parsed value SAXState _state; - Array* _array; - std::stack _arrayStack; + ValueMap* _curDict; + ValueVector* _curArray; + + std::stack _dictStack; + std::stack _arrayStack; std::stack _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 : "); } - _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(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(object)) - return generateElementForArray(array, pDoc); + if (value.getType() == Value::Type::VECTOR) + return generateElementForArray(value.asValueVector(), pDoc); // object is Dictionary - if (Dictionary *innerDict = dynamic_cast(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); } @@ -488,10 +492,10 @@ void FileUtils::purgeCachedEntries() _fullPathCache.clear(); } -unsigned char* FileUtils::getFileData(const char* filename, const char* mode, long *size) +unsigned char* FileUtils::getFileData(const char* filename, const char* mode, ssize_t *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 { @@ -518,10 +522,10 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, lo return buffer; } -unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, long *size) +unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, ssize_t *size) { - unsigned char * buffer = NULL; - unzFile pFile = NULL; + unsigned char * buffer = nullptr; + unzFile pFile = nullptr; *size = 0; do @@ -537,14 +541,14 @@ 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); CC_BREAK_IF(UNZ_OK != nRet); buffer = (unsigned char*)malloc(FileInfo.uncompressed_size); - int CC_UNUSED nSize = unzReadCurrentFile(pFile, buffer, FileInfo.uncompressed_size); + int CC_UNUSED nSize = unzReadCurrentFile(pFile, buffer, static_cast(FileInfo.uncompressed_size)); CCASSERT(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong"); *size = FileInfo.uncompressed_size; @@ -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( dict->objectForKey("metadata") ); - int version = static_cast( 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()); + CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, filename.c_str()); return; } - setFilenameLookupDictionary( static_cast( dict->objectForKey("filenames")) ); + setFilenameLookupDictionary( dict["filenames"].asValueMap()); } } } diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 672e4b7234..e5925e2818 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -29,11 +29,10 @@ THE SOFTWARE. #include #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. */ @@ -88,7 +84,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, long *size); + virtual unsigned char* getFileData(const char* filename, const char* mode, ssize_t *size); /** * Gets resource file data from a zip file. @@ -98,7 +94,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned. */ - virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, long *size); + virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, ssize_t *size); /** Returns the fullpath for a given filename. @@ -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. diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index ba90d380e3..6351ff6439 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -121,10 +121,10 @@ public: * @js NA * @lua NA */ - bool initWithImageData(const unsigned char * data, long dataLen); + bool initWithImageData(const unsigned char * data, ssize_t dataLen); // @warning kFmtRawData only support RGBA8888 - bool initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti = false); + bool initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti = false); /** @brief Create image with specified string. @@ -175,9 +175,9 @@ public: // Getters inline unsigned char * getData() { return _data; } - inline int getDataLen() { return _dataLen; } + inline ssize_t getDataLen() { return _dataLen; } inline Format getFileType() {return _fileType; } - inline Texture2D::PixelFormat getRenderFormat() { return _renderFormat; } + inline Texture2D::PixelFormat getRenderFormat() { return _renderFormat; } inline int getWidth() { return _width; } inline int getHeight() { return _height; } inline bool isPremultipliedAlpha() { return _preMulti; } @@ -198,16 +198,16 @@ public: bool saveToFile(const std::string &filename, bool isToRGB = true); protected: - bool initWithJpgData(const unsigned char * data, int dataLen); - bool initWithPngData(const unsigned char * data, int dataLen); - bool initWithTiffData(const unsigned char * data, int dataLen); - bool initWithWebpData(const unsigned char * data, int dataLen); - bool initWithPVRData(const unsigned char * data, int dataLen); - bool initWithPVRv2Data(const unsigned char * data, int dataLen); - bool initWithPVRv3Data(const unsigned char * data, int dataLen); - bool initWithETCData(const unsigned char * data, int dataLen); - bool initWithS3TCData(const unsigned char * data, int dataLen); - bool initWithATITCData(const unsigned char *data, int dataLen); + bool initWithJpgData(const unsigned char * data, ssize_t dataLen); + bool initWithPngData(const unsigned char * data, ssize_t dataLen); + bool initWithTiffData(const unsigned char * data, ssize_t dataLen); + bool initWithWebpData(const unsigned char * data, ssize_t dataLen); + bool initWithPVRData(const unsigned char * data, ssize_t dataLen); + bool initWithPVRv2Data(const unsigned char * data, ssize_t dataLen); + bool initWithPVRv3Data(const unsigned char * data, ssize_t dataLen); + bool initWithETCData(const unsigned char * data, ssize_t dataLen); + bool initWithS3TCData(const unsigned char * data, ssize_t dataLen); + bool initWithATITCData(const unsigned char *data, ssize_t dataLen); typedef struct sImageTGA tImageTGA; bool initWithTGAData(tImageTGA* tgaData); @@ -221,7 +221,7 @@ private: */ static const int MIPMAP_MAX = 16; unsigned char *_data; - int _dataLen; + ssize_t _dataLen; int _width; int _height; Format _fileType; @@ -248,15 +248,15 @@ private: */ bool initWithImageFileThreadSafe(const char *fullpath); - Format detectFormat(const unsigned char * data, int dataLen); - bool isPng(const unsigned char * data, int dataLen); - bool isJpg(const unsigned char * data, int dataLen); - bool isTiff(const unsigned char * data, int dataLen); - bool isWebp(const unsigned char * data, int dataLen); - bool isPvr(const unsigned char * data, int dataLen); - bool isEtc(const unsigned char * data, int dataLen); - bool isS3TC(const unsigned char * data,int dataLen); - bool isATITC(const unsigned char *data, int dataLen); + Format detectFormat(const unsigned char * data, ssize_t dataLen); + bool isPng(const unsigned char * data, ssize_t dataLen); + bool isJpg(const unsigned char * data, ssize_t dataLen); + bool isTiff(const unsigned char * data, ssize_t dataLen); + bool isWebp(const unsigned char * data, ssize_t dataLen); + bool isPvr(const unsigned char * data, ssize_t dataLen); + bool isEtc(const unsigned char * data, ssize_t dataLen); + bool isS3TC(const unsigned char * data,ssize_t dataLen); + bool isATITC(const unsigned char *data, ssize_t dataLen); }; // end of platform group diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index edbf424868..8cbafd7817 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -349,7 +349,7 @@ namespace typedef struct { const unsigned char * data; - int size; + ssize_t size; int offset; }tImageSource; @@ -420,7 +420,7 @@ bool Image::initWithImageFile(const char * strPath) SDL_FreeSurface(iSurf); #else - long bufferLen = 0; + ssize_t bufferLen = 0; unsigned char* buffer = FileUtils::getInstance()->getFileData(_filePath.c_str(), "rb", &bufferLen); if (buffer != nullptr && bufferLen > 0) @@ -437,7 +437,7 @@ bool Image::initWithImageFile(const char * strPath) bool Image::initWithImageFileThreadSafe(const char *fullpath) { bool ret = false; - long dataLen = 0; + ssize_t dataLen = 0; _filePath = fullpath; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) FileUtilsAndroid *fileUitls = (FileUtilsAndroid*)FileUtils::getInstance(); @@ -453,7 +453,7 @@ bool Image::initWithImageFileThreadSafe(const char *fullpath) return ret; } -bool Image::initWithImageData(const unsigned char * data, long dataLen) +bool Image::initWithImageData(const unsigned char * data, ssize_t dataLen) { bool ret = false; @@ -462,7 +462,7 @@ bool Image::initWithImageData(const unsigned char * data, long dataLen) CC_BREAK_IF(! data || dataLen <= 0); unsigned char* unpackedData = nullptr; - int unpackedLen = 0; + ssize_t unpackedLen = 0; //detecgt and unzip the compress file if (ZipUtils::isCCZBuffer(data, dataLen)) @@ -535,7 +535,7 @@ bool Image::initWithImageData(const unsigned char * data, long dataLen) return ret; } -bool Image::isPng(const unsigned char * data, int dataLen) +bool Image::isPng(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 8) { @@ -548,13 +548,13 @@ bool Image::isPng(const unsigned char * data, int dataLen) } -bool Image::isEtc(const unsigned char * data, int dataLen) +bool Image::isEtc(const unsigned char * data, ssize_t dataLen) { return etc1_pkm_is_valid((etc1_byte*)data) ? true : false; } -bool Image::isS3TC(const unsigned char * data, int dataLen) +bool Image::isS3TC(const unsigned char * data, ssize_t dataLen) { S3TCTexHeader *header = (S3TCTexHeader *)data; @@ -567,7 +567,7 @@ bool Image::isS3TC(const unsigned char * data, int dataLen) return true; } -bool Image::isATITC(const unsigned char *data, int dataLen) +bool Image::isATITC(const unsigned char *data, ssize_t dataLen) { ATITCTexHeader *header = (ATITCTexHeader *)data; @@ -579,7 +579,7 @@ bool Image::isATITC(const unsigned char *data, int dataLen) return true; } -bool Image::isJpg(const unsigned char * data, int dataLen) +bool Image::isJpg(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 4) { @@ -591,7 +591,7 @@ bool Image::isJpg(const unsigned char * data, int dataLen) return memcmp(data, JPG_SOI, 2) == 0; } -bool Image::isTiff(const unsigned char * data, int dataLen) +bool Image::isTiff(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 4) { @@ -605,7 +605,7 @@ bool Image::isTiff(const unsigned char * data, int dataLen) (memcmp(data, TIFF_MM, 2) == 0 && *(static_cast(data) + 2) == 0 && *(static_cast(data) + 3) == 42); } -bool Image::isWebp(const unsigned char * data, int dataLen) +bool Image::isWebp(const unsigned char * data, ssize_t dataLen) { if (dataLen <= 12) { @@ -619,7 +619,7 @@ bool Image::isWebp(const unsigned char * data, int dataLen) && memcmp(static_cast(data) + 8, WEBP_WEBP, 4) == 0; } -bool Image::isPvr(const unsigned char * data, int dataLen) +bool Image::isPvr(const unsigned char * data, ssize_t dataLen) { if (static_cast(dataLen) < sizeof(PVRv2TexHeader) || static_cast(dataLen) < sizeof(PVRv3TexHeader)) { @@ -632,7 +632,7 @@ bool Image::isPvr(const unsigned char * data, int dataLen) return memcmp(&headerv2->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) == 0 || CC_SWAP_INT32_BIG_TO_HOST(headerv3->version) == 0x50565203; } -Image::Format Image::detectFormat(const unsigned char * data, int dataLen) +Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen) { if (isPng(data, dataLen)) { @@ -744,7 +744,7 @@ namespace } } -bool Image::initWithJpgData(const unsigned char * data, int dataLen) +bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen) { /* these are standard libjpeg structures for reading(decompression) */ struct jpeg_decompress_struct cinfo; @@ -841,7 +841,7 @@ bool Image::initWithJpgData(const unsigned char * data, int dataLen) return bRet; } -bool Image::initWithPngData(const unsigned char * data, int dataLen) +bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen) { // length of bytes to check if it is a valid png file #define PNGSIGSIZE 8 @@ -941,7 +941,7 @@ bool Image::initWithPngData(const unsigned char * data, int dataLen) } // read png data - png_uint_32 rowbytes; + png_size_t rowbytes; png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * _height ); rowbytes = png_get_rowbytes(png_ptr, info_ptr); @@ -1085,7 +1085,7 @@ namespace } } -bool Image::initWithTiffData(const unsigned char * data, int dataLen) +bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen) { bool bRet = false; do @@ -1179,7 +1179,7 @@ namespace } } -bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) +bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen) { int dataLength = 0, dataOffset = 0, dataSize = 0; int blockSize = 0, widthBlocks = 0, heightBlocks = 0; @@ -1305,7 +1305,7 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) return true; } -bool Image::initWithPVRv3Data(const unsigned char * data, int dataLen) +bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen) { if (static_cast(dataLen) < sizeof(PVRv3TexHeader)) { @@ -1414,11 +1414,11 @@ bool Image::initWithPVRv3Data(const unsigned char * data, int dataLen) } dataSize = widthBlocks * heightBlocks * ((blockSize * it->second.bpp) / 8); - int packetLength = _dataLen - dataOffset; + auto packetLength = _dataLen - dataOffset; packetLength = packetLength > dataSize ? dataSize : packetLength; _mipmaps[i].address = _data + dataOffset; - _mipmaps[i].len = packetLength; + _mipmaps[i].len = static_cast(packetLength); dataOffset += packetLength; CCAssert(dataOffset <= _dataLen, "CCTexurePVR: Invalid lenght"); @@ -1431,7 +1431,7 @@ bool Image::initWithPVRv3Data(const unsigned char * data, int dataLen) return true; } -bool Image::initWithETCData(const unsigned char * data, int dataLen) +bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen) { const etc1_byte* header = static_cast(data); @@ -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; @@ -1575,7 +1575,7 @@ namespace } } -bool Image::initWithS3TCData(const unsigned char * data, int dataLen) +bool Image::initWithS3TCData(const unsigned char * data, ssize_t dataLen) { const uint32_t FOURCC_DXT1 = makeFourCC('D', 'X', 'T', '1'); @@ -1697,7 +1697,7 @@ bool Image::initWithS3TCData(const unsigned char * data, int dataLen) } -bool Image::initWithATITCData(const unsigned char *data, int dataLen) +bool Image::initWithATITCData(const unsigned char *data, ssize_t dataLen) { /* load the .ktx file */ ATITCTexHeader *header = (ATITCTexHeader *)data; @@ -1826,12 +1826,12 @@ bool Image::initWithATITCData(const unsigned char *data, int dataLen) return true; } -bool Image::initWithPVRData(const unsigned char * data, int dataLen) +bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen) { return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen); } -bool Image::initWithWebpData(const unsigned char * data, int dataLen) +bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen) { bool bRet = false; do @@ -1866,7 +1866,7 @@ bool Image::initWithWebpData(const unsigned char * data, int dataLen) return bRet; } -bool Image::initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti) +bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti) { bool bRet = false; do diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 056a088826..ccbd11a9f1 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -23,7 +23,6 @@ ****************************************************************************/ #include "CCSAXParser.h" -#include "CCDictionary.h" #include "CCFileUtils.h" #include "tinyxml2.h" @@ -82,7 +81,7 @@ bool XmlSaxHander::VisitExit( const tinyxml2::XMLElement& element ) bool XmlSaxHander::Visit( const tinyxml2::XMLText& text ) { //log("Visit %s",text.Value()); - SAXParser::textHandler(_ccsaxParserImp, (const CC_XML_CHAR *)text.Value(), strlen(text.Value())); + SAXParser::textHandler(_ccsaxParserImp, (const CC_XML_CHAR *)text.Value(), static_cast(strlen(text.Value()))); return true; } @@ -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); @@ -115,7 +114,7 @@ bool SAXParser::parse(const char* pXMLData, unsigned int uDataLength) bool SAXParser::parse(const char *pszFile) { bool ret = false; - long size = 0; + ssize_t size = 0; char* pBuffer = (char*)FileUtils::getInstance()->getFileData(pszFile, "rt", &size); if (pBuffer != NULL && size > 0) { diff --git a/cocos/2d/platform/CCSAXParser.h b/cocos/2d/platform/CCSAXParser.h index 452061776a..d79e3c1c6a 100644 --- a/cocos/2d/platform/CCSAXParser.h +++ b/cocos/2d/platform/CCSAXParser.h @@ -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 diff --git a/cocos/2d/platform/CCThread.cpp b/cocos/2d/platform/CCThread.cpp index 7d4a23a216..0a33d2ddf6 100644 --- a/cocos/2d/platform/CCThread.cpp +++ b/cocos/2d/platform/CCThread.cpp @@ -29,10 +29,6 @@ NS_CC_BEGIN // iOS and Mac already has a Thread.mm #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_MAC) -std::list>* ThreadHelper::_callbackList = new std::list>(); -std::mutex* ThreadHelper::_mutex = new std::mutex; -long ThreadHelper::_callbackNumberPerFrame = 5; - void* ThreadHelper::createAutoreleasePool() { @@ -44,42 +40,6 @@ void ThreadHelper::releaseAutoreleasePool(void* autoreleasePool) } -void ThreadHelper::runOnGLThread(std::function f) -{ - // Insert call back function - _mutex->lock(); - _callbackList->push_back(f); - _mutex->unlock(); -} - -void ThreadHelper::doCallback() -{ - _mutex->lock(); - auto iter = _callbackList->begin(); - long i = 0; - while (iter != _callbackList->end()) - { - auto f = *iter; - f(); - - ++i; - if (i >= _callbackNumberPerFrame) - { - break; - } - else - { - iter = _callbackList->erase(iter); - } - } - _mutex->unlock(); -} - -void ThreadHelper::setCallbackNumberPerFrame(long callbackNumberPerFrame) -{ - _callbackNumberPerFrame = callbackNumberPerFrame; -} - #endif NS_CC_END diff --git a/cocos/2d/platform/CCThread.h b/cocos/2d/platform/CCThread.h index b0998eeb59..7596d29c02 100644 --- a/cocos/2d/platform/CCThread.h +++ b/cocos/2d/platform/CCThread.h @@ -59,29 +59,6 @@ public: * @lua NA */ static void releaseAutoreleasePool(void *autoreleasePool); - - /** To run a function in gl thread. - * @js NA - * @lua NA - @since v3.0 - */ - static void runOnGLThread(std::function f); - - /** Set how many callback functions being invoked per frame. Default value is 5. - * @js NA - * @lua NA - @since v3.0 - */ - static void setCallbackNumberPerFrame(long callbackNumberPerFrame); - -private: - // This function will be call by Director to call some call back function on gl thread - static void doCallback(); - - static std::list> *_callbackList; - static std::mutex *_mutex; - // How many callback functions invoked per frame - static long _callbackNumberPerFrame; }; // end of platform group diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp index af910cfe71..e0ce2a3886 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp @@ -130,17 +130,17 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const } -unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* mode, long * size) +unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* mode, ssize_t * size) { return doGetFileData(filename, mode, size, false); } -unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, long * pSize) +unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, ssize_t * pSize) { return doGetFileData(filename, pszMode, pSize, true); } -unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* mode, long * size, bool forAsync) +unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* mode, ssize_t * size, bool forAsync) { unsigned char * data = 0; diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.h b/cocos/2d/platform/android/CCFileUtilsAndroid.h index 3bee6d2e39..4e3c4c3125 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.h +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.h @@ -55,7 +55,7 @@ public: /* override funtions */ bool init(); - virtual unsigned char* getFileData(const char* filename, const char* mode, long * size); + virtual unsigned char* getFileData(const char* filename, const char* mode, ssize_t * size); virtual std::string getWritablePath() const; virtual bool isFileExist(const std::string& strFilePath) const; @@ -64,10 +64,10 @@ public: /** This function is android specific. It is used for TextureCache::addImageAsync(). Don't use it in your codes. */ - unsigned char* getFileDataForAsync(const char* filename, const char* mode, long * size); + unsigned char* getFileDataForAsync(const char* filename, const char* mode, ssize_t * size); private: - unsigned char* doGetFileData(const char* filename, const char* mode, long * size, bool forAsync); + unsigned char* doGetFileData(const char* filename, const char* mode, ssize_t * size, bool forAsync); static AAssetManager* assetmanager; }; diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index e7eeb1606a..30dda46a5f 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -296,7 +296,7 @@ static void engine_term_display(struct engine* engine) { /* * Get X, Y positions and ID's for all pointers */ -static void getTouchPos(AInputEvent *event, long ids[], float xs[], float ys[]) { +static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { int pointerCount = AMotionEvent_getPointerCount(event); for(int i = 0; i < pointerCount; ++i) { ids[i] = AMotionEvent_getPointerId(event, i); @@ -325,11 +325,10 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - long pId = pointerId; float x = xP; float y = yP; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pId, &x, &y); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); return 1; } break; @@ -344,11 +343,10 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - long pId = pointerId; float x = xP; float y = yP; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pId, &x, &y); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); return 1; } break; @@ -357,7 +355,7 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); int pointerCount = AMotionEvent_getPointerCount(event); - long ids[pointerCount]; + int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); @@ -373,11 +371,10 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - long pId = pointerId; float x = xP; float y = yP; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pId, &x, &y); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); return 1; } break; @@ -391,11 +388,10 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", xP, yP, pointerIndex); - long pId = pointerId; float x = xP; float y = yP; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pId, &x, &y); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); return 1; } break; @@ -404,7 +400,7 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); int pointerCount = AMotionEvent_getPointerCount(event); - long ids[pointerCount]; + int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.h b/cocos/2d/platform/apple/CCFileUtilsApple.h index 5be1708df1..b80a54b908 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.h +++ b/cocos/2d/platform/apple/CCFileUtilsApple.h @@ -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 diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.mm b/cocos/2d/platform/apple/CCFileUtilsApple.mm index 811a4189b1..11b2644a6b 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -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(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(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(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(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(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(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) { diff --git a/cocos/2d/platform/apple/CCThread.mm b/cocos/2d/platform/apple/CCThread.mm index 4e138fb889..1d060c5028 100644 --- a/cocos/2d/platform/apple/CCThread.mm +++ b/cocos/2d/platform/apple/CCThread.mm @@ -26,10 +26,6 @@ THE SOFTWARE. NS_CC_BEGIN -std::list>* ThreadHelper::_callbackList = new std::list>(); -std::mutex* ThreadHelper::_mutex = new std::mutex; -long ThreadHelper::_callbackNumberPerFrame = 5; - void* ThreadHelper::createAutoreleasePool() { id pool = [[NSAutoreleasePool alloc] init]; @@ -41,40 +37,4 @@ void ThreadHelper::releaseAutoreleasePool(void *autoreleasePool) [(NSAutoreleasePool*)autoreleasePool release]; } -void ThreadHelper::runOnGLThread(std::function f) -{ - // Insert call back function - _mutex->lock(); - _callbackList->push_back(f); - _mutex->unlock(); -} - -void ThreadHelper::doCallback() -{ - _mutex->lock(); - auto iter = _callbackList->begin(); - long i = 0; - while (iter != _callbackList->end()) - { - auto f = *iter; - f(); - - ++i; - if (i >= _callbackNumberPerFrame) - { - break; - } - else - { - iter = _callbackList->erase(iter); - } - } - _mutex->unlock(); -} - -void ThreadHelper::setCallbackNumberPerFrame(long callbackNumberPerFrame) -{ - _callbackNumberPerFrame = callbackNumberPerFrame; -} - NS_CC_END diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index bb00a70c54..f792282367 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -413,7 +413,7 @@ static CCEAGLView *__view = 0; ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (long*)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (int*)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -433,7 +433,7 @@ static CCEAGLView *__view = 0; ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, (long*)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesMove(i, (int*)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -454,7 +454,7 @@ static CCEAGLView *__view = 0; ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (long*)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (int*)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -475,7 +475,7 @@ static CCEAGLView *__view = 0; ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (long*)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (int*)ids, xs, ys); } #pragma mark - UIView - Responder diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index d8fbbf5737..360e96f101 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -186,7 +186,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -195,7 +195,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -231,7 +231,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index 5d4f23b281..580436def9 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -206,7 +206,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -215,7 +215,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -253,7 +253,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/mac/CCImage.mm b/cocos/2d/platform/mac/CCImage.mm index 6c52115847..84d23234ae 100644 --- a/cocos/2d/platform/mac/CCImage.mm +++ b/cocos/2d/platform/mac/CCImage.mm @@ -39,8 +39,8 @@ NS_CC_BEGIN typedef struct { - unsigned int height; - unsigned int width; + int height; + int width; bool hasAlpha; bool isPremultipliedAlpha; unsigned char* data; @@ -138,8 +138,8 @@ static bool _initWithString(const char * pText, cocos2d::Image::TextAlign eAlign dimensions.height = realDimensions.height; } - NSUInteger POTWide = (NSUInteger)dimensions.width; - NSUInteger POTHigh = (NSUInteger)(MAX(dimensions.height, realDimensions.height)); + NSInteger POTWide = dimensions.width; + NSInteger POTHigh = MAX(dimensions.height, realDimensions.height); unsigned char* data; //Alignment @@ -185,8 +185,8 @@ static bool _initWithString(const char * pText, cocos2d::Image::TextAlign eAlign if (dataNew) { memcpy(dataNew, data, textureSize); // output params - pInfo->width = POTWide; - pInfo->height = POTHigh; + pInfo->width = static_cast(POTWide); + pInfo->height = static_cast(POTHigh); pInfo->data = dataNew; pInfo->hasAlpha = true; pInfo->isPremultipliedAlpha = true; diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm index 1894440ced..8276f8e02c 100644 --- a/cocos/2d/platform/mac/EAGLView.mm +++ b/cocos/2d/platform/mac/EAGLView.mm @@ -335,7 +335,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (long*)ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (int*)ids, xs, ys); } - (void)mouseMoved:(NSEvent *)theEvent @@ -359,7 +359,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (long*)ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (int*)ids, xs, ys); } - (void)mouseUp:(NSEvent *)theEvent @@ -378,7 +378,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (long*)ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (int*)ids, xs, ys); } - (void)rightMouseDown:(NSEvent *)theEvent { diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index ce9b7f43d8..e83eb289f2 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -303,7 +303,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -312,7 +312,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -348,7 +348,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - long id = 0; + int id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/win32/CCImage.cpp b/cocos/2d/platform/win32/CCImage.cpp index a5d4d68a21..dd6d64742a 100644 --- a/cocos/2d/platform/win32/CCImage.cpp +++ b/cocos/2d/platform/win32/CCImage.cpp @@ -22,6 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #define __CC_PLATFORM_IMAGE_CPP__ +#if _MSC_VER +#include +#endif #include "platform/CCImageCommon_cpp.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index 4716dc6524..1090404d89 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -52,6 +52,12 @@ THE SOFTWARE. #include #include +#ifndef M_PI + #define M_PI 3.14159265358 +#endif +#ifndef M_PI_2 + #define M_PI_2 1.57079632679 +#endif // for MIN MAX and sys/time.h on win32 platform #ifdef __MINGW32__ #include @@ -73,7 +79,9 @@ THE SOFTWARE. #endif #define _WINSOCKAPI_ -#define NOMINMAX +#ifndef NOMINMAX + #define NOMINMAX +#endif // Structure timeval has define in winsock.h, include windows.h for it. #include diff --git a/cocos/audio/win32/MciPlayer.cpp b/cocos/audio/win32/MciPlayer.cpp index 25520cb9b9..a01dbddb1e 100644 --- a/cocos/audio/win32/MciPlayer.cpp +++ b/cocos/audio/win32/MciPlayer.cpp @@ -8,11 +8,11 @@ namespace CocosDenshion { static HINSTANCE s_hInstance; static MCIERROR s_mciError; -static LRESULT WINAPI _SoundPlayProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +LRESULT WINAPI _SoundPlayProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); MciPlayer::MciPlayer() : _wnd(NULL) -, _dev(NULL) +, _dev(0L) , _soundID(0) , _times(0) , _playing(false) @@ -56,7 +56,7 @@ MciPlayer::MciPlayer() NULL ); if (_wnd) { - SetWindowLong(_wnd, GWL_USERDATA, (LONG)this); + SetWindowLongPtr(_wnd, GWLP_USERDATA, (LONG_PTR)this); } } @@ -85,7 +85,7 @@ void MciPlayer::Open(const char* pFileName, UINT uId) mciOpen.lpstrDeviceType = (LPCTSTR)MCI_ALL_DEVICE_ID; mciOpen.lpstrElementName = pFileName; - mciError = mciSendCommand(0,MCI_OPEN, MCI_OPEN_ELEMENT, (DWORD)&mciOpen); + mciError = mciSendCommand(0,MCI_OPEN, MCI_OPEN_ELEMENT, reinterpret_cast(&mciOpen)); BREAK_IF(mciError); _dev = mciOpen.wDeviceID; @@ -101,8 +101,8 @@ void MciPlayer::Play(UINT uTimes /* = 1 */) return; } MCI_PLAY_PARMS mciPlay = {0}; - mciPlay.dwCallback = (DWORD_PTR)_wnd; - s_mciError = mciSendCommand(_dev,MCI_PLAY, MCI_FROM|MCI_NOTIFY,(DWORD)&mciPlay); + mciPlay.dwCallback = reinterpret_cast(_wnd); + s_mciError = mciSendCommand(_dev,MCI_PLAY, MCI_FROM|MCI_NOTIFY,reinterpret_cast(&mciPlay)); if (! s_mciError) { _playing = true; @@ -149,8 +149,8 @@ void MciPlayer::Rewind() mciSendCommand(_dev, MCI_SEEK, MCI_SEEK_TO_START, 0); MCI_PLAY_PARMS mciPlay = {0}; - mciPlay.dwCallback = (DWORD)_wnd; - _playing = mciSendCommand(_dev, MCI_PLAY, MCI_NOTIFY,(DWORD)&mciPlay) ? false : true; + mciPlay.dwCallback = reinterpret_cast(_wnd); + _playing = mciSendCommand(_dev, MCI_PLAY, MCI_NOTIFY,reinterpret_cast(&mciPlay)) ? false : true; } bool MciPlayer::IsPlaying() @@ -185,7 +185,7 @@ LRESULT WINAPI _SoundPlayProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) MciPlayer * pPlayer = NULL; if (MM_MCINOTIFY == Msg && MCI_NOTIFY_SUCCESSFUL == wParam - &&(pPlayer = (MciPlayer *)GetWindowLong(hWnd, GWL_USERDATA))) + &&(pPlayer = (MciPlayer *)GetWindowLongPtr(hWnd, GWLP_USERDATA))) { if (pPlayer->_times) { @@ -197,8 +197,8 @@ LRESULT WINAPI _SoundPlayProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) mciSendCommand(lParam, MCI_SEEK, MCI_SEEK_TO_START, 0); MCI_PLAY_PARMS mciPlay = {0}; - mciPlay.dwCallback = (DWORD)hWnd; - mciSendCommand(lParam, MCI_PLAY, MCI_NOTIFY,(DWORD)&mciPlay); + mciPlay.dwCallback = reinterpret_cast(hWnd); + mciSendCommand(lParam, MCI_PLAY, MCI_NOTIFY,reinterpret_cast(&mciPlay)); } else { diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index fdb96b2de9..333183a822 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -26,25 +26,25 @@ THE SOFTWARE. #include "CCArray.h" #include "CCString.h" #include "platform/CCFileUtils.h" +#include // std::for_each NS_CC_BEGIN - #if CC_USE_ARRAY_VECTOR // ---------------------------------------------------------------------------------- // std::vector implementation // ---------------------------------------------------------------------------------- -Array::Array() +__Array::Array() : data(NULL) { init(); } -Array* Array::create() +__Array* __Array::create() { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(7)) { @@ -58,9 +58,9 @@ Array* Array::create() return array; } -Array* Array::createWithObject(Object* object) +__Array* __Array::createWithObject(Object* object) { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithObject(object)) { @@ -74,12 +74,12 @@ Array* Array::createWithObject(Object* object) return array; } -Array* Array::create(Object* object, ...) +__Array* __Array::create(Object* object, ...) { va_list args; va_start(args,object); - Array* array = create(); + __Array* array = create(); if (array && object) { array->addObject(object); @@ -100,16 +100,16 @@ Array* Array::create(Object* object, ...) return array; } -Array* Array::createWithArray(Array* otherArray) +__Array* __Array::createWithArray(__Array* otherArray) { return otherArray->clone(); } -Array* Array::createWithCapacity(size_t capacity) +__Array* __Array::createWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(capacity)) { @@ -123,9 +123,9 @@ Array* Array::createWithCapacity(size_t capacity) return array; } -Array* Array::createWithContentsOfFile(const char* fileName) +__Array* __Array::createWithContentsOfFile(const char* fileName) { - Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); + __Array* ret = __Array::createWithContentsOfFileThreadSafe(fileName); if (ret != nullptr) { ret->autorelease(); @@ -133,17 +133,17 @@ Array* Array::createWithContentsOfFile(const char* fileName) return ret; } -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +__Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName) { return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); } -bool Array::init() +bool __Array::init() { return initWithCapacity(7); } -bool Array::initWithObject(Object* object) +bool __Array::initWithObject(Object* object) { bool ret = initWithCapacity(7); if (ret) @@ -154,7 +154,7 @@ bool Array::initWithObject(Object* object) } /** Initializes an array with some objects */ -bool Array::initWithObjects(Object* object, ...) +bool __Array::initWithObjects(Object* object, ...) { bool ret = false; do @@ -182,7 +182,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(size_t capacity) +bool __Array::initWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -190,17 +190,17 @@ bool Array::initWithCapacity(size_t capacity) return true; } -bool Array::initWithArray(Array* otherArray) +bool __Array::initWithArray(__Array* otherArray) { data = otherArray->data; return true; } -size_t Array::getIndexOfObject(Object* object) const +int __Array::getIndexOfObject(Object* object) const { auto it = data.begin(); - for (size_t i = 0; it != data.end(); ++it, ++i) + for (int i = 0; it != data.end(); ++it, ++i) { if (it->get() == object) { @@ -211,7 +211,7 @@ size_t Array::getIndexOfObject(Object* object) const return -1; } -Object* Array::getRandomObject() +Object* __Array::getRandomObject() { if (data.size()==0) { @@ -230,15 +230,15 @@ Object* Array::getRandomObject() return data[r].get(); } -bool Array::containsObject(Object* object) const +bool __Array::containsObject(Object* object) const { auto i = this->getIndexOfObject(object); return (i >= 0); } -bool Array::isEqualToArray(Array* otherArray) +bool __Array::isEqualToArray(__Array* otherArray) { - for (size_t i = 0; i < this->count(); ++i) + for (int i = 0; i < this->count(); ++i) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -248,64 +248,64 @@ bool Array::isEqualToArray(Array* otherArray) return true; } -void Array::addObject(Object* object) +void __Array::addObject(Object* object) { data.push_back(RCPtr(object)); } -void Array::addObjectsFromArray(Array* otherArray) +void __Array::addObjectsFromArray(__Array* otherArray) { data.insert(data.end(), otherArray->data.begin(), otherArray->data.end()); } -void Array::insertObject(Object* object, size_t index) +void __Array::insertObject(Object* object, int index) { data.insert(std::begin(data) + index, RCPtr(object)); } -void Array::setObject(Object* object, size_t index) +void __Array::setObject(Object* object, int index) { data[index] = RCPtr(object); } -void Array::removeLastObject(bool releaseObj) +void __Array::removeLastObject(bool releaseObj) { CCASSERT(data.size(), "no objects added"); data.pop_back(); } -void Array::removeObject(Object* object, bool releaseObj /* ignored */) +void __Array::removeObject(Object* object, bool releaseObj /* ignored */) { data.erase(std::remove(data.begin(), data.end(), object)); } -void Array::removeObjectAtIndex(size_t index, bool releaseObj /* ignored */) +void __Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) { auto obj = data[index]; data.erase(data.begin() + index); } -void Array::removeObjectsInArray(Array* otherArray) +void __Array::removeObjectsInArray(__Array* otherArray) { CCASSERT(false, "not implemented"); } -void Array::removeAllObjects() +void __Array::removeAllObjects() { data.erase(std::begin(data), std::end(data)); } -void Array::fastRemoveObjectAtIndex(size_t index) +void __Array::fastRemoveObjectAtIndex(int index) { removeObjectAtIndex(index); } -void Array::fastRemoveObject(Object* object) +void __Array::fastRemoveObject(Object* object) { removeObject(object); } -void Array::exchangeObject(Object* object1, Object* object2) +void __Array::exchangeObject(Object* object1, Object* object2) { auto idx1 = getIndexOfObject(object1); auto idx2 = getIndexOfObject(object2); @@ -315,34 +315,34 @@ void Array::exchangeObject(Object* object1, Object* object2) std::swap(data[idx1], data[idx2]); } -void Array::exchangeObjectAtIndex(size_t index1, size_t index2) +void __Array::exchangeObjectAtIndex(int index1, int index2) { std::swap(data[index1], data[index2]); } -void Array::replaceObjectAtIndex(size_t index, Object* object, bool releaseObject /* ignored */) +void __Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) { data[index] = object; } -void Array::reverseObjects() +void __Array::reverseObjects() { std::reverse(std::begin(data), std::end(data)); } -void Array::reduceMemoryFootprint() +void __Array::reduceMemoryFootprint() { // N/A } -Array::~Array() +__Array::~Array() { CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); } -Array* Array::clone() const +__Array* __Array::clone() const { - Array* ret = new Array(); + __Array* ret = new __Array(); ret->autorelease(); ret->initWithCapacity(this->data.size() > 0 ? this->data.size() : 1); @@ -368,7 +368,7 @@ Array* Array::clone() const return ret; } -void Array::acceptVisitor(DataVisitor &visitor) +void __Array::acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } @@ -379,15 +379,15 @@ void Array::acceptVisitor(DataVisitor &visitor) #else -Array::Array() +__Array::__Array() : data(nullptr) { // init(); } -Array* Array::create() +__Array* __Array::create() { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(7)) { @@ -401,9 +401,9 @@ Array* Array::create() return array; } -Array* Array::createWithObject(Object* object) +__Array* __Array::createWithObject(Object* object) { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithObject(object)) { @@ -417,12 +417,12 @@ Array* Array::createWithObject(Object* object) return array; } -Array* Array::create(Object* object, ...) +__Array* __Array::create(Object* object, ...) { va_list args; va_start(args,object); - Array* array = create(); + __Array* array = create(); if (array && object) { array->addObject(object); @@ -443,16 +443,16 @@ Array* Array::create(Object* object, ...) return array; } -Array* Array::createWithArray(Array* otherArray) +__Array* __Array::createWithArray(__Array* otherArray) { return otherArray->clone(); } -Array* Array::createWithCapacity(size_t capacity) +__Array* __Array::createWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(capacity)) { @@ -466,9 +466,9 @@ Array* Array::createWithCapacity(size_t capacity) return array; } -Array* Array::createWithContentsOfFile(const char* fileName) +__Array* __Array::createWithContentsOfFile(const char* fileName) { - Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); + __Array* ret = __Array::createWithContentsOfFileThreadSafe(fileName); if (ret != nullptr) { ret->autorelease(); @@ -476,19 +476,27 @@ Array* Array::createWithContentsOfFile(const char* fileName) return ret; } -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +__Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName) { - return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); + ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName); + + __Array* ret = __Array::createWithCapacity(static_cast(arr.size())); + + std::for_each(arr.cbegin(), arr.cend(), [&ret](const Value& value){ + ret->addObject(String::create(value.asString())); + }); + + return ret; } -bool Array::init() +bool __Array::init() { CCASSERT(!data, "Array cannot be re-initialized"); return initWithCapacity(7); } -bool Array::initWithObject(Object* object) +bool __Array::initWithObject(Object* object) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -501,7 +509,7 @@ bool Array::initWithObject(Object* object) } /** Initializes an array with some objects */ -bool Array::initWithObjects(Object* object, ...) +bool __Array::initWithObjects(Object* object, ...) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -531,7 +539,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(size_t capacity) +bool __Array::initWithCapacity(int capacity) { CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); @@ -539,7 +547,7 @@ bool Array::initWithCapacity(size_t capacity) return true; } -bool Array::initWithArray(Array* otherArray) +bool __Array::initWithArray(__Array* otherArray) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -555,12 +563,12 @@ bool Array::initWithArray(Array* otherArray) return ret; } -size_t Array::getIndexOfObject(Object* object) const +int __Array::getIndexOfObject(Object* object) const { return ccArrayGetIndexOfObject(data, object); } -Object* Array::getRandomObject() +Object* __Array::getRandomObject() { if (data->num == 0) { @@ -574,17 +582,17 @@ Object* Array::getRandomObject() r = 0; } - return data->arr[static_cast(data->num * r)]; + return data->arr[static_cast(data->num * r)]; } -bool Array::containsObject(Object* object) const +bool __Array::containsObject(Object* object) const { return ccArrayContainsObject(data, object); } -bool Array::isEqualToArray(Array* otherArray) +bool __Array::isEqualToArray(__Array* otherArray) { - for (size_t i = 0; i < this->count(); ++i) + for (int i = 0; i < this->count(); ++i) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -594,25 +602,25 @@ bool Array::isEqualToArray(Array* otherArray) return true; } -void Array::addObject(Object* object) +void __Array::addObject(Object* object) { CCASSERT(data, "Array not initialized"); ccArrayAppendObjectWithResize(data, object); } -void Array::addObjectsFromArray(Array* otherArray) +void __Array::addObjectsFromArray(__Array* otherArray) { CCASSERT(data, "Array not initialized"); ccArrayAppendArrayWithResize(data, otherArray->data); } -void Array::insertObject(Object* object, size_t index) +void __Array::insertObject(Object* object, int index) { CCASSERT(data, "Array not initialized"); ccArrayInsertObjectAtIndex(data, object, index); } -void Array::setObject(Object* object, size_t index) +void __Array::setObject(Object* object, int index) { CCASSERT(index >= 0 && index < count(), "Invalid index"); @@ -624,43 +632,43 @@ void Array::setObject(Object* object, size_t index) } } -void Array::removeLastObject(bool releaseObj) +void __Array::removeLastObject(bool releaseObj) { CCASSERT(data->num, "no objects added"); ccArrayRemoveObjectAtIndex(data, data->num - 1, releaseObj); } -void Array::removeObject(Object* object, bool releaseObj/* = true*/) +void __Array::removeObject(Object* object, bool releaseObj/* = true*/) { ccArrayRemoveObject(data, object, releaseObj); } -void Array::removeObjectAtIndex(size_t index, bool releaseObj) +void __Array::removeObjectAtIndex(int index, bool releaseObj) { ccArrayRemoveObjectAtIndex(data, index, releaseObj); } -void Array::removeObjectsInArray(Array* otherArray) +void __Array::removeObjectsInArray(__Array* otherArray) { ccArrayRemoveArray(data, otherArray->data); } -void Array::removeAllObjects() +void __Array::removeAllObjects() { ccArrayRemoveAllObjects(data); } -void Array::fastRemoveObjectAtIndex(size_t index) +void __Array::fastRemoveObjectAtIndex(int index) { ccArrayFastRemoveObjectAtIndex(data, index); } -void Array::fastRemoveObject(Object* object) +void __Array::fastRemoveObject(Object* object) { ccArrayFastRemoveObject(data, object); } -void Array::exchangeObject(Object* object1, Object* object2) +void __Array::exchangeObject(Object* object1, Object* object2) { auto index1 = ccArrayGetIndexOfObject(data, object1); if (index1 == CC_INVALID_INDEX) @@ -677,18 +685,18 @@ void Array::exchangeObject(Object* object1, Object* object2) ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::exchangeObjectAtIndex(size_t index1, size_t index2) +void __Array::exchangeObjectAtIndex(int index1, int index2) { ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::replaceObjectAtIndex(size_t index, Object* object, bool releaseObject/* = true*/) +void __Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) { ccArrayInsertObjectAtIndex(data, object, index); ccArrayRemoveObjectAtIndex(data, index + 1); } -void Array::reverseObjects() +void __Array::reverseObjects() { if (data->num > 1) { @@ -704,21 +712,21 @@ void Array::reverseObjects() } } -void Array::reduceMemoryFootprint() +void __Array::reduceMemoryFootprint() { ccArrayShrink(data); } -Array::~Array() +__Array::~__Array() { CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); ccArrayFree(data); } -Array* Array::clone() const +__Array* __Array::clone() const { - Array* ret = new Array(); + __Array* ret = new __Array(); ret->autorelease(); ret->initWithCapacity(this->data->num > 0 ? this->data->num : 1); @@ -744,7 +752,7 @@ Array* Array::clone() const return ret; } -void Array::acceptVisitor(DataVisitor &visitor) +void __Array::acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } diff --git a/cocos/base/CCArray.h b/cocos/base/CCArray.h index 32b57d8a4d..d5df307745 100644 --- a/cocos/base/CCArray.h +++ b/cocos/base/CCArray.h @@ -230,7 +230,7 @@ while(false) NS_CC_BEGIN -class CC_DLL Array : public Object, public Clonable +class CC_DLL __Array : public Object, public Clonable { public: @@ -238,30 +238,30 @@ public: * @js NA * @lua NA */ - static Array* create(); + static __Array* create(); /** Create an array with objects * @js NA */ - static Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; + static __Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; /** Create an array with one object * @js NA */ - static Array* createWithObject(Object* object); + static __Array* createWithObject(Object* object); /** Create an array with a default capacity * @js NA */ - static Array* createWithCapacity(size_t capacity); + static __Array* createWithCapacity(int capacity); /** Create an array with from an existing array * @js NA */ - static Array* createWithArray(Array* otherArray); + static __Array* createWithArray(__Array* otherArray); /** @brief Generate a Array pointer by file @param pFileName The file name of *.plist file @return The Array pointer generated from the file * @js NA */ - static Array* createWithContentsOfFile(const char* pFileName); + static __Array* createWithContentsOfFile(const char* pFileName); /* @brief The same meaning as arrayWithContentsOfFile(), but it doesn't call autorelease, so the @@ -269,12 +269,12 @@ public: * @js NA * @lua NA */ - static Array* createWithContentsOfFileThreadSafe(const char* pFileName); + static __Array* createWithContentsOfFileThreadSafe(const char* pFileName); /** * @js NA * @lua NA */ - ~Array(); + ~__Array(); /** Initializes an array * @js NA @@ -295,19 +295,19 @@ public: * @js NA * @lua NA */ - bool initWithCapacity(size_t capacity); + bool initWithCapacity(int capacity); /** Initializes an array with an existing array * @js NA * @lua NA */ - bool initWithArray(Array* otherArray); + bool initWithArray(__Array* otherArray); // Querying an Array /** Returns element count of the array * @js NA */ - size_t count() const + int count() const { #if CC_USE_ARRAY_VECTOR return data.size(); @@ -318,7 +318,7 @@ public: /** Returns capacity of the array * @js NA */ - size_t capacity() const + int capacity() const { #if CC_USE_ARRAY_VECTOR return data.capacity(); @@ -330,17 +330,17 @@ public: * @js NA * @lua NA */ - size_t getIndexOfObject(Object* object) const; + int getIndexOfObject(Object* object) const; /** * @js NA */ - CC_DEPRECATED_ATTRIBUTE size_t indexOfObject(Object* object) const { return getIndexOfObject(object); } + CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); } /** Returns an element with a certain index * @js NA * @lua NA */ - Object* getObjectAtIndex(size_t index) + Object* getObjectAtIndex(int index) { CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); #if CC_USE_ARRAY_VECTOR @@ -349,7 +349,7 @@ public: return data->arr[index]; #endif } - CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(size_t index) { return getObjectAtIndex(index); } + CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); } /** Returns the last element of the array * @js NA */ @@ -384,7 +384,7 @@ public: /** @since 1.1 * @js NA */ - bool isEqualToArray(Array* otherArray); + bool isEqualToArray(__Array* otherArray); // Adding Objects /** Add a certain object @@ -397,21 +397,21 @@ public: /** Add all elements of an existing array * @js NA */ - void addObjectsFromArray(Array* otherArray); + void addObjectsFromArray(__Array* otherArray); /** Insert a certain object at a certain index * @js NA */ - void insertObject(Object* object, size_t index); + void insertObject(Object* object, int index); /** sets a certain object at a certain index * @js NA * @lua NA */ - void setObject(Object* object, size_t index); + void setObject(Object* object, int index); /** sets a certain object at a certain index without retaining. Use it with caution * @js NA * @lua NA */ - void fastSetObject(Object* object, size_t index) + void fastSetObject(Object* object, int index) { #if CC_USE_ARRAY_VECTOR setObject(object, index); @@ -424,7 +424,7 @@ public: * @js NA * @lua NA */ - void swap( size_t indexOne, size_t indexTwo ) + void swap( int indexOne, int indexTwo ) { CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices"); #if CC_USE_ARRAY_VECTOR @@ -447,11 +447,11 @@ public: /** Remove an element with a certain index * @js NA */ - void removeObjectAtIndex(size_t index, bool releaseObj = true); + void removeObjectAtIndex(int index, bool releaseObj = true); /** Remove all elements * @js NA */ - void removeObjectsInArray(Array* otherArray); + void removeObjectsInArray(__Array* otherArray); /** Remove all objects * @js NA */ @@ -463,7 +463,7 @@ public: /** Fast way to remove an element with a certain index * @js NA */ - void fastRemoveObjectAtIndex(size_t index); + void fastRemoveObjectAtIndex(int index); // Rearranging Content @@ -474,12 +474,12 @@ public: /** Swap two elements with certain indexes * @js NA */ - void exchangeObjectAtIndex(size_t index1, size_t index2); + void exchangeObjectAtIndex(int index1, int index2); /** Replace object at index with another object. * @js NA */ - void replaceObjectAtIndex(size_t index, Object* object, bool releaseObject = true); + void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true); /** Revers the array * @js NA @@ -498,7 +498,7 @@ public: * @js NA * @lua NA */ - virtual Array* clone() const; + virtual __Array* clone() const; // ------------------------------------------ // Iterators @@ -546,12 +546,15 @@ public: * @js NA * @lua NA */ - Array(); + __Array(); }; // end of data_structure group /// @} +CC_DEPRECATED_ATTRIBUTE typedef __Array CCArray; +CC_DEPRECATED_ATTRIBUTE typedef __Array Array; + NS_CC_END #endif // __CCARRAY_H__ diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 89a3528f73..e55c8c9b97 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -30,19 +30,17 @@ static PoolManager* s_pPoolManager = NULL; AutoreleasePool::AutoreleasePool() { - _managedObjectArray = new Array(); - _managedObjectArray->initWithCapacity(150); + _managedObjectArray.reserve(150); } AutoreleasePool::~AutoreleasePool() { CCLOGINFO("deallocing AutoreleasePool: %p", this); - CC_SAFE_DELETE(_managedObjectArray); } void AutoreleasePool::addObject(Object* object) { - _managedObjectArray->addObject(object); + _managedObjectArray.pushBack(object); CCASSERT(object->_reference > 1, "reference count should be greater than 1"); ++(object->_autoReleaseCount); @@ -53,34 +51,29 @@ void AutoreleasePool::removeObject(Object* object) { for (unsigned int i = 0; i < object->_autoReleaseCount; ++i) { - _managedObjectArray->removeObject(object, false); + _managedObjectArray.removeObject(object, false); } } void AutoreleasePool::clear() { - if(_managedObjectArray->count() > 0) + if (!_managedObjectArray.empty()) { //CCAutoreleasePool* pReleasePool; #ifdef _DEBUG - int nIndex = _managedObjectArray->count() - 1; + int nIndex = _managedObjectArray.size() - 1; #endif - Object* pObj = NULL; - CCARRAY_FOREACH_REVERSE(_managedObjectArray, pObj) - { - if(!pObj) - break; - - --(pObj->_autoReleaseCount); + _managedObjectArray.forEachReverse([](Object* obj){ + --(obj->_autoReleaseCount); //(*it)->release(); //delete (*it); #ifdef _DEBUG nIndex--; #endif - } + }); - _managedObjectArray->removeAllObjects(); + _managedObjectArray.clear(); } } @@ -107,8 +100,7 @@ void PoolManager::purgePoolManager() PoolManager::PoolManager() { - _releasePoolStack = new Array(); - _releasePoolStack->initWithCapacity(150); + _releasePoolStack.reserve(150); _curReleasePool = 0; } @@ -119,35 +111,27 @@ PoolManager::~PoolManager() // we only release the last autorelease pool here _curReleasePool = 0; - _releasePoolStack->removeObjectAtIndex(0); - - CC_SAFE_DELETE(_releasePoolStack); + _releasePoolStack.remove(0); } void PoolManager::finalize() { - if(_releasePoolStack->count() > 0) + if (!_releasePoolStack.empty()) { - //CCAutoreleasePool* pReleasePool; - Object* pObj = NULL; - CCARRAY_FOREACH(_releasePoolStack, pObj) - { - if(!pObj) - break; - AutoreleasePool* pPool = static_cast(pObj); - pPool->clear(); - } + _releasePoolStack.forEach([](AutoreleasePool* pool){ + pool->clear(); + }); } } void PoolManager::push() { - AutoreleasePool* pPool = new AutoreleasePool(); //ref = 1 - _curReleasePool = pPool; + AutoreleasePool* pool = new AutoreleasePool(); //ref = 1 + _curReleasePool = pool; - _releasePoolStack->addObject(pPool); //ref = 2 + _releasePoolStack.pushBack(pool); //ref = 2 - pPool->release(); //ref = 1 + pool->release(); //ref = 1 } void PoolManager::pop() @@ -157,20 +141,20 @@ void PoolManager::pop() return; } - int nCount = _releasePoolStack->count(); + int count = _releasePoolStack.size(); _curReleasePool->clear(); - if (nCount > 1) + if (count > 1) { - _releasePoolStack->removeObjectAtIndex(nCount-1); + _releasePoolStack.remove(count-1); // if(nCount > 1) // { -// _curReleasePool = _releasePoolStack->getObjectAtIndex(nCount - 2); +// _curReleasePool = _releasePoolStack.at(count - 2); // return; // } - _curReleasePool = (AutoreleasePool*)_releasePoolStack->getObjectAtIndex(nCount - 2); + _curReleasePool = _releasePoolStack.at(count - 2); } /*_curReleasePool = NULL;*/ diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index e446ceb402..67930173e2 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -25,7 +25,7 @@ THE SOFTWARE. #define __AUTORELEASEPOOL_H__ #include "CCObject.h" -#include "CCArray.h" +#include "CCVector.h" NS_CC_BEGIN @@ -45,7 +45,7 @@ class CC_DLL AutoreleasePool : public Object * be destructed properly by calling Object::release() even if the object * is in the pool. */ - Array *_managedObjectArray; + Vector _managedObjectArray; public: /** * @js NA @@ -93,7 +93,7 @@ public: class CC_DLL PoolManager { - Array *_releasePoolStack; + Vector _releasePoolStack; AutoreleasePool *_curReleasePool; AutoreleasePool *getCurReleasePool(); diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp new file mode 100644 index 0000000000..c15ba3383b --- /dev/null +++ b/cocos/base/CCConsole.cpp @@ -0,0 +1,431 @@ +/**************************************************************************** + 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 "CCConsole.h" + +#include +#include + +#include +#include +#include + +#if defined(_MSC_VER) +#include +#include + +#define bzero(a, b) memset(a, 0, b); + +#else +#include +#include +#include +#include +#include +#include +#endif + +#include "CCDirector.h" +#include "CCScheduler.h" +#include "CCScene.h" + +NS_CC_BEGIN + + +// helper free functions + +// dprintf() is not defined in Android +// so we add our own 'dpritnf' +static ssize_t mydprintf(int sock, const char *format, ...) +{ + va_list args; + char buf[1024]; + + va_start(args, format); + vsnprintf(buf, sizeof(buf), format, args); + va_end(args); + + return write(sock, buf, strlen(buf)); +} + +static void printSceneGraph(int fd, Node* node, int level) +{ + for(int i=0; idescription(), node->getZOrder(), node->getTag()); + + for(const auto& child: node->getChildren()) + printSceneGraph(fd, child, level+1); +} + +static void printSceneGraphBoot(int fd) +{ + write(fd,"\n",1); + auto scene = Director::getInstance()->getRunningScene(); + printSceneGraph(fd, scene, 0); + write(fd,"\n",1); +} + + +// +// Console code +// + +Console* Console::create() +{ + auto ret = new Console; + + ret->autorelease(); + return ret; +} + +Console::Console() +: _listenfd(-1) +, _running(false) +, _endThread(false) +, _maxCommands(5) +, _userCommands(nullptr) +, _maxUserCommands(0) +{ + // VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'. + Command commands[] = { + { "fps on", [](int fd, const char* command) { + Director *dir = Director::getInstance(); + Scheduler *sched = dir->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, true)); + } }, + { "fps off", [](int fd, const char* command) { + Director *dir = Director::getInstance(); + Scheduler *sched = dir->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, false)); + } }, + { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) }, + { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) }, + { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) } }; + + for (size_t i = 0; i < sizeof(commands)/sizeof(commands[0]) && i < sizeof(_commands)/sizeof(_commands[0]); ++i) + { + _commands[i] = commands[i]; + } +} + +Console::~Console() +{ + cancel(); +} + +bool Console::listenOnTCP(int port) +{ + int listenfd, n; + const int on = 1; + struct addrinfo hints, *res, *ressave; + char serv[30]; + + snprintf(serv, sizeof(serv)-1, "%d", port ); + serv[sizeof(serv)-1]=0; + + bzero(&hints, sizeof(struct addrinfo)); + hints.ai_flags = AI_PASSIVE; + hints.ai_family = AF_INET; // AF_UNSPEC: Do we need IPv6 ? + hints.ai_socktype = SOCK_STREAM; + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) + WSADATA wsaData; + n = WSAStartup(MAKEWORD(2, 2),&wsaData); +#endif + + if ( (n = getaddrinfo(NULL, serv, &hints, &res)) != 0) { + fprintf(stderr,"net_listen error for %s: %s", serv, gai_strerror(n)); + return false; + } + + ressave = res; + + do { + listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + if (listenfd < 0) + continue; /* error, try next one */ + + setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)); + if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0) + break; /* success */ + + close(listenfd); /* bind error, close and try next one */ + } while ( (res = res->ai_next) != NULL); + + if (res == NULL) { + perror("net_listen:"); + freeaddrinfo(ressave); + return false; + } + + listen(listenfd, 50); + + if (res->ai_family == AF_INET) { + char buf[INET_ADDRSTRLEN] = ""; + struct sockaddr_in *sin = (struct sockaddr_in*) res->ai_addr; + if( inet_ntop(res->ai_family, &sin->sin_addr, buf, sizeof(buf)) != NULL ) + log("Console: listening on %s : %d", buf, ntohs(sin->sin_port)); + else + perror("inet_ntop"); + } else if (res->ai_family == AF_INET6) { + char buf[INET6_ADDRSTRLEN] = ""; + struct sockaddr_in6 *sin = (struct sockaddr_in6*) res->ai_addr; + if( inet_ntop(res->ai_family, &sin->sin6_addr, buf, sizeof(buf)) != NULL ) + log("Console: listening on %s : %d", buf, ntohs(sin->sin6_port)); + else + perror("inet_ntop"); + } + + + freeaddrinfo(ressave); + + return listenOnFileDescriptor(listenfd); +} + +bool Console::listenOnFileDescriptor(int fd) +{ + CCASSERT(!_running, "already running"); + _listenfd = fd; + _thread = std::thread( std::bind( &Console::loop, this) ); + + return true; +} + +void Console::cancel() +{ + if( _running ) { + _endThread = true; + _thread.join(); + } +} + +void Console::setUserCommands(Command *commands, int numberOfCommands) +{ + _userCommands = commands; + _maxUserCommands = numberOfCommands; +} + + +// +// commands +// + +void Console::commandHelp(int fd, const char* command) +{ + const char help[] = "\nAvailable commands:\n"; + write(fd, help, sizeof(help)); + for(int i=0; i<_maxCommands; ++i) { + write(fd,"\t",1); + write(fd, _commands[i].name, strlen(_commands[i].name)); + write(fd,"\n",1); + } + + // User commands + for(int i=0; i<_maxUserCommands; ++i) { + write(fd,"\t",1); + write(fd, _userCommands[i].name, strlen(_userCommands[i].name)); + write(fd,"\n",1); + } + +} + +void Console::commandExit(int fd, const char *command) +{ + FD_CLR(fd, &_read_set); + _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); + close(fd); +} + +void Console::commandSceneGraph(int fd, const char *command) +{ + Scheduler *sched = Director::getInstance()->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) ); +} + +bool Console::parseCommand(int fd) +{ + auto r = readline(fd); + if(r < 1) + return false; + + bool found=false; + for(int i=0; i < _maxCommands; ++i) { + if( strncmp(_buffer, _commands[i].name,strlen(_commands[i].name)) == 0 ) { + // XXX TODO FIXME + // Ideally this loop should execute the function in the cocos2d according to a variable + // But clang crashes in runtime when doing that (bug in clang, not in the code). + // So, unfortunately, the only way to fix it was to move that logic to the callback itself + _commands[i].callback(fd, _buffer); + found = true; + break; + } + } + + // user commands + for(int i=0; i < _maxUserCommands && !found; ++i) { + if( strncmp(_buffer, _userCommands[i].name,strlen(_userCommands[i].name)) == 0 ) { + _userCommands[i].callback(fd, _buffer); + found = true; + break; + } + } + + if(!found) { + const char err[] = "Unknown command. Type 'help' for options\n"; + write(fd, err, sizeof(err)); + } + + sendPrompt(fd); + + return true; +} + +// +// Helpers +// +void Console::sendPrompt(int fd) +{ + const char prompt[] = "\n> "; + write(fd, prompt, sizeof(prompt)); +} + +ssize_t Console::readline(int fd) +{ + int maxlen = sizeof(_buffer)-1; + ssize_t n, rc; + char c, *ptr; + + ptr = _buffer; + + for( n=1; n to_remove; + for(const auto &fd: _fds) { + if(FD_ISSET(fd,©_set)) { + if( ! parseCommand(fd) ) { + to_remove.push_back(fd); + } + if(--nready <= 0) + break; + } + } + + // remove closed conections + for(int fd: to_remove) { + FD_CLR(fd, &_read_set); + _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); + } + } + + // clean up: ignore stdin, stdout and stderr + for(const auto &fd: _fds ) + close(fd); + close(_listenfd); + + _running = false; +} + +NS_CC_END diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h new file mode 100644 index 0000000000..d401991525 --- /dev/null +++ b/cocos/base/CCConsole.h @@ -0,0 +1,123 @@ +/**************************************************************************** + 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 __CCCONSOLE_H__ +#define __CCCONSOLE_H__ + +#if defined(_MSC_VER) +#include +//typedef SSIZE_T ssize_t; +// ssize_t was redefined as int in libwebsockets.h. +// Therefore, to avoid conflict, we needs the same definition. +typedef int ssize_t; +#else +#include +#endif + +#include +#include +#include + +#include "ccMacros.h" +#include "CCObject.h" + + +NS_CC_BEGIN + +/** Console is helper class that lets the developer control the game from TCP connection. + Console will spawn a new thread that will listen to a specified TCP port. + Console has a basic token parser. Each token is associated with an std::function. + If the std::function<> needs to use the cocos2d API, it needs to call + + ``` + scheduler->performFunctionInCocosThread( ... ); + ``` + */ +class CC_DLL Console : public Object +{ +public: + + struct Command { + const char *name; + std::function callback; + }; + + /** creates a new instnace of the Console */ + static Console* create(); + + /** starts listening to specifed TCP port */ + bool listenOnTCP(int port); + + /** starts listening to specifed file descriptor */ + bool listenOnFileDescriptor(int fd); + + /** cancels the Console. Cancel will be called at destruction time as well */ + void cancel(); + + /** sets user tokens */ + void setUserCommands( Command* commands, int numberOfCommands); + +protected: + Console(); + virtual ~Console(); + + void loop(); + + ssize_t readline(int fd); + bool parseCommand(int fd); + void sendPrompt(int fd); + void addClient(); + + // Add commands here + void commandHelp(int fd, const char *command); + void commandExit(int fd, const char *command); + void commandSceneGraph(int fd, const char *command); + + // file descriptor: socket, console, etc. + int _listenfd; + int _maxfd; + std::vector _fds; + std::thread _thread; + + fd_set _read_set; + + bool _running; + bool _endThread; + + char _buffer[512]; + + struct Command _commands[15]; + int _maxCommands; + struct Command *_userCommands; + int _maxUserCommands; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Console); +}; + + +NS_CC_END + +#endif /* defined(__CCCONSOLE_H__) */ diff --git a/cocos/base/CCData.cpp b/cocos/base/CCData.cpp index 1c42a12ee5..cd0af3adcf 100644 --- a/cocos/base/CCData.cpp +++ b/cocos/base/CCData.cpp @@ -28,7 +28,7 @@ NS_CC_BEGIN -Data::Data(unsigned char *pBytes, const unsigned long nSize) +Data::Data(unsigned char *pBytes, ssize_t nSize) { _size = nSize; _bytes = new unsigned char[_size]; @@ -53,7 +53,7 @@ unsigned char* Data::getBytes() const return _bytes; } -unsigned long Data::getSize() const +ssize_t Data::getSize() const { return _size; } diff --git a/cocos/base/CCData.h b/cocos/base/CCData.h index 27cb43da61..69313b31bc 100644 --- a/cocos/base/CCData.h +++ b/cocos/base/CCData.h @@ -37,7 +37,7 @@ public: * @js NA * @lua NA */ - Data(unsigned char *pBytes, const unsigned long nSize); + Data(unsigned char *pBytes, const ssize_t nSize); /** * @js NA * @lua NA @@ -52,7 +52,7 @@ public: * @js NA * @lua NA */ - static Data* create(unsigned char *pBytes, const unsigned long nSize) + static Data* create(unsigned char *pBytes, const ssize_t nSize) { Data* pRet = new Data(pBytes, nSize); if (pRet) @@ -70,7 +70,7 @@ public: * @js NA * @lua NA */ - unsigned long getSize() const; + ssize_t getSize() const; /** override functions * @js NA @@ -80,7 +80,7 @@ public: private: unsigned char* _bytes; - unsigned long _size; + ssize_t _size; }; NS_CC_END diff --git a/cocos/base/CCDataVisitor.cpp b/cocos/base/CCDataVisitor.cpp index 2d2a1f8121..5f7d95203c 100644 --- a/cocos/base/CCDataVisitor.cpp +++ b/cocos/base/CCDataVisitor.cpp @@ -60,7 +60,7 @@ void DataVisitor::visit(const String *value) visitObject(value); } -void DataVisitor::visit(const Array *value) +void DataVisitor::visit(const __Array *value) { visitObject(value); } @@ -70,7 +70,7 @@ void DataVisitor::visit(const Dictionary *value) visitObject(value); } -void DataVisitor::visit(const Set *value) +void DataVisitor::visit(const __Set *value) { visitObject(value); } @@ -136,7 +136,7 @@ void PrettyPrinter::visit(const String *p) _result += p->getCString(); } -void PrettyPrinter::visit(const Array *p) +void PrettyPrinter::visit(const __Array *p) { _result += "\n"; _result += _indentStr; @@ -194,7 +194,7 @@ void PrettyPrinter::visit(const Dictionary *p) _result += ""; } -void PrettyPrinter::visit(const Set *p) +void PrettyPrinter::visit(const __Set *p) { _result += "\n"; _result += _indentStr; @@ -203,8 +203,8 @@ void PrettyPrinter::visit(const Set *p) setIndentLevel(_indentLevel+1); int i = 0; - Set* tmp = const_cast(p); - SetIterator it = tmp->begin(); + __Set* tmp = const_cast<__Set*>(p); + __SetIterator it = tmp->begin(); for (; it != tmp->end(); ++it, ++i) { if (i > 0) { diff --git a/cocos/base/CCDataVisitor.h b/cocos/base/CCDataVisitor.h index 93d2463f29..9abb1f1424 100644 --- a/cocos/base/CCDataVisitor.h +++ b/cocos/base/CCDataVisitor.h @@ -36,9 +36,9 @@ class Integer; class Float; class Double; class String; -class Array; +class __Array; class Dictionary; -class Set; +class __Set; class Data; /** @@ -77,9 +77,9 @@ public: virtual void visit(const Float *p); virtual void visit(const Double *p); virtual void visit(const String *p); - virtual void visit(const Array *p); + virtual void visit(const __Array *p); virtual void visit(const Dictionary *p); - virtual void visit(const Set *p); + virtual void visit(const __Set *p); virtual void visit(const Data *p); }; @@ -98,9 +98,9 @@ public: virtual void visit(const Float *p); virtual void visit(const Double *p); virtual void visit(const String *p); - virtual void visit(const Array *p); + virtual void visit(const __Array *p); virtual void visit(const Dictionary *p); - virtual void visit(const Set *p); + virtual void visit(const __Set *p); virtual void visit(const Data *p); private: void setIndentLevel(int indentLevel); diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 6b8df0febf..ceb0333823 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -26,6 +26,7 @@ #include "CCString.h" #include "CCInteger.h" #include "platform/CCFileUtils.h" +#include // std::for_each using namespace std; @@ -87,12 +88,12 @@ unsigned int Dictionary::count() return HASH_COUNT(_elements); } -Array* Dictionary::allKeys() +__Array* Dictionary::allKeys() { int iKeyCount = this->count(); if (iKeyCount <= 0) return NULL; - Array* pArray = Array::createWithCapacity(iKeyCount); + __Array* array = __Array::createWithCapacity(iKeyCount); DictElement *pElement, *tmp; if (_dictType == kDictStr) @@ -100,7 +101,7 @@ Array* Dictionary::allKeys() HASH_ITER(hh, _elements, pElement, tmp) { String* pOneKey = new String(pElement->_strKey); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } @@ -108,20 +109,20 @@ Array* Dictionary::allKeys() { HASH_ITER(hh, _elements, pElement, tmp) { - Integer* pOneKey = new Integer(pElement->_intKey); - pArray->addObject(pOneKey); + Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } - return pArray; + return array; } -Array* Dictionary::allKeysForObject(Object* object) +__Array* Dictionary::allKeysForObject(Object* object) { int iKeyCount = this->count(); if (iKeyCount <= 0) return NULL; - Array* pArray = Array::create(); + __Array* array = __Array::create(); DictElement *pElement, *tmp; @@ -132,7 +133,7 @@ Array* Dictionary::allKeysForObject(Object* object) if (object == pElement->_object) { String* pOneKey = new String(pElement->_strKey); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } @@ -143,13 +144,13 @@ Array* Dictionary::allKeysForObject(Object* object) { if (object == pElement->_object) { - Integer* pOneKey = new Integer(pElement->_intKey); - pArray->addObject(pOneKey); + Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } } - return pArray; + return array; } Object* Dictionary::objectForKey(const std::string& key) @@ -302,10 +303,10 @@ void Dictionary::setObjectUnSafe(Object* pObject, const intptr_t key) HASH_ADD_PTR(_elements, _intKey, pElement); } -void Dictionary::removeObjectsForKeys(Array* pKeyArray) +void Dictionary::removeObjectsForKeys(__Array* pKey__Array) { Object* pObj = NULL; - CCARRAY_FOREACH(pKeyArray, pObj) + CCARRAY_FOREACH(pKey__Array, pObj) { String* pStr = static_cast(pObj); removeObjectForKey(pStr->getCString()); @@ -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(element->getObject())->getCString()); + } + + return FileUtils::getInstance()->writeToFile(dict, fullPath); } Dictionary* Dictionary::clone() const diff --git a/cocos/base/CCDictionary.h b/cocos/base/CCDictionary.h index 63082109b3..323241a19c 100644 --- a/cocos/base/CCDictionary.h +++ b/cocos/base/CCDictionary.h @@ -207,7 +207,7 @@ public: * @return The array contains all keys of elements. It's an autorelease object yet. * @js NA */ - Array* allKeys(); + __Array* allKeys(); /** * Get all keys according to the specified object. @@ -215,7 +215,7 @@ public: * @return The array contains all keys for the specified object. It's an autorelease object yet. * @js NA */ - Array* allKeysForObject(Object* object); + __Array* allKeysForObject(Object* object); /** * Get the object according to the specified string key. @@ -302,7 +302,7 @@ public: * Remove an object by the specified string key. * * @param key The string key for searching. - * @see removeObjectForKey(intptr_t), removeObjectsForKeys(Array*), + * @see removeObjectForKey(intptr_t), removeObjectsForKeys(__Array*), * removeObjectForElememt(DictElement*), removeAllObjects(). * @js NA */ @@ -312,7 +312,7 @@ public: * Remove an object by the specified integer key. * * @param key The integer key for searching. - * @see removeObjectForKey(const std::string&), removeObjectsForKeys(Array*), + * @see removeObjectForKey(const std::string&), removeObjectsForKeys(__Array*), * removeObjectForElememt(DictElement*), removeAllObjects(). * @js NA */ @@ -321,19 +321,19 @@ public: /** * Remove objects by an array of keys. * - * @param pKeyArray The array contains keys to be removed. + * @param pKey__Array The array contains keys to be removed. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), * removeObjectForElememt(DictElement*), removeAllObjects(). * @js NA */ - void removeObjectsForKeys(Array* pKeyArray); + void removeObjectsForKeys(__Array* pKey__Array); /** * Remove an object by an element. * * @param pElement The element need to be removed. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectsForKeys(Array*), removeAllObjects(). + * removeObjectsForKeys(__Array*), removeAllObjects(). * @js NA * @lua NA */ @@ -343,7 +343,7 @@ public: * Remove all objects in the dictionary. * * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectsForKeys(Array*), removeObjectForElememt(DictElement*). + * removeObjectsForKeys(__Array*), removeObjectForElememt(DictElement*). * @js NA */ void removeAllObjects(); diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h new file mode 100644 index 0000000000..df39fc80d0 --- /dev/null +++ b/cocos/base/CCMap.h @@ -0,0 +1,256 @@ +/**************************************************************************** +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 +#include +#include // std::for_each + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +template +class CC_DLL Map +{ +public: + Map() + : _data() + { + CCLOGINFO("In the default constructor of Map!"); + } + + explicit Map(int capacity) + : _data() + { + CCLOGINFO("In the constructor with capacity of Map!"); + _data.reserve(capacity); + } + + Map(const Map& other) + { + CCLOGINFO("In the copy constructor of Map!"); + _data = other; + addRefForAllObjects(); + } + + Map(Map&& other) + { + CCLOGINFO("In the move constructor of Map!"); + _data = other; + } + + ~Map() + { + CCLOGINFO("In the destructor of Map!"); + clear(); + } + + /** Sets capacity of current array */ + void reserve(int 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 keys() const + { + std::vector keys; + + if (!_data.empty()) + { + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) + { + keys.push_back(iter->first); + } + } + return std::move(keys); + } + + std::vector keys(V object) const + { + std::vector 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& 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 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& operator= ( const Map& other ) + { + CCLOGINFO("In the copy assignment operator of Map!"); + clear(); + _data = other._data; + addRefForAllObjects(); + return *this; + } + + Map& operator= ( Map&& other ) + { + CCLOGINFO("In the move assignment operator of Map!"); + _data = std::move(other._data); + return *this; + } + +protected: + + void addRefForAllObjects() + { + for (auto iter = _data.begin(); iter != _data.end(); ++iter) + { + iter->second->retain(); + } + } + + RefMap _data; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCMAP_H__ */ diff --git a/cocos/base/CCNS.cpp b/cocos/base/CCNS.cpp index 8cf496c0b1..aa19a7a0af 100644 --- a/cocos/base/CCNS.cpp +++ b/cocos/base/CCNS.cpp @@ -36,8 +36,8 @@ typedef std::vector strArray; // string toolkit static inline void split(std::string src, const char* token, strArray& vect) { - int nend=0; - int nbegin=0; + size_t nend=0; + size_t nbegin=0; while(nend != -1) { nend = src.find(token, nbegin); @@ -53,20 +53,20 @@ 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('{'); - int nPosRight = content.find('}'); + size_t nPosLeft = content.find('{'); + size_t nPosRight = content.find('}'); // don't have '{' and '}' CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); @@ -77,8 +77,8 @@ static bool splitWithForm(const char* pStr, strArray& strs) // nothing between '{' and '}' CC_BREAK_IF(pointStr.length() == 0); - int nPos1 = pointStr.find('{'); - int nPos2 = pointStr.find('}'); + size_t nPos1 = pointStr.find('{'); + size_t nPos2 = pointStr.find('}'); // contain '{' or '}' CC_BREAK_IF(nPos1 != (int)std::string::npos || nPos2 != (int)std::string::npos); @@ -97,18 +97,18 @@ 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('{'); - int nPosRight = content.find('}'); + size_t nPosLeft = content.find('{'); + size_t nPosRight = content.find('}'); for (int i = 1; i < 3; ++i) { if (nPosRight == (int)std::string::npos) @@ -120,7 +120,7 @@ Rect RectFromString(const char* pszContent) CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); content = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); - int nPointEnd = content.find('}'); + size_t nPointEnd = content.find('}'); CC_BREAK_IF(nPointEnd == (int)std::string::npos); nPointEnd = content.find(',', nPointEnd); CC_BREAK_IF(nPointEnd == (int)std::string::npos); @@ -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; diff --git a/cocos/base/CCNS.h b/cocos/base/CCNS.h index 8ce8e1dde6..c078e45225 100644 --- a/cocos/base/CCNS.h +++ b/cocos/base/CCNS.h @@ -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 /// @} diff --git a/cocos/base/CCPlatformConfig.h b/cocos/base/CCPlatformConfig.h index 5ba0757dac..3a74498d1a 100644 --- a/cocos/base/CCPlatformConfig.h +++ b/cocos/base/CCPlatformConfig.h @@ -133,7 +133,9 @@ Config of cocos2d-x project, per target platform. #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -#pragma warning (disable:4127) +#ifndef __MINGW32__ +#pragma warning (disable:4127) +#endif #endif // CC_PLATFORM_WIN32 #endif // __CC_PLATFORM_CONFIG_H__ diff --git a/cocos/base/CCSet.cpp b/cocos/base/CCSet.cpp index c3c24e0e5e..b3e565c6f4 100644 --- a/cocos/base/CCSet.cpp +++ b/cocos/base/CCSet.cpp @@ -28,17 +28,17 @@ using namespace std; NS_CC_BEGIN -Set::Set(void) +__Set::__Set(void) { _set = new set; } -Set::Set(const Set &rSetObject) +__Set::__Set(const __Set &r__SetObject) { - _set = new set(*rSetObject._set); + _set = new set(*r__SetObject._set); // call retain of members - SetIterator iter; + __SetIterator iter; for (iter = _set->begin(); iter != _set->end(); ++iter) { if (! (*iter)) @@ -50,20 +50,20 @@ Set::Set(const Set &rSetObject) } } -Set::~Set(void) +__Set::~__Set(void) { removeAllObjects(); CC_SAFE_DELETE(_set); } -void Set::acceptVisitor(DataVisitor &visitor) +void __Set::acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } -Set * Set::create() +__Set * __Set::create() { - Set * pRet = new Set(); + __Set * pRet = new __Set(); if (pRet != NULL) { @@ -73,24 +73,24 @@ Set * Set::create() return pRet; } -Set* Set::copy(void) +__Set* __Set::copy(void) { - Set *pSet = new Set(*this); + __Set *p__Set = new __Set(*this); - return pSet; + return p__Set; } -Set* Set::mutableCopy(void) +__Set* __Set::mutableCopy(void) { return copy(); } -int Set::count(void) +int __Set::count(void) { return (int)_set->size(); } -void Set::addObject(Object *pObject) +void __Set::addObject(Object *pObject) { if (_set->count(pObject) == 0) { @@ -99,7 +99,7 @@ void Set::addObject(Object *pObject) } } -void Set::removeObject(Object *pObject) +void __Set::removeObject(Object *pObject) { if (_set->erase(pObject) > 0) { @@ -107,10 +107,10 @@ void Set::removeObject(Object *pObject) } } -void Set::removeAllObjects() +void __Set::removeAllObjects() { - SetIterator it = _set->begin(); - SetIterator tmp; + __SetIterator it = _set->begin(); + __SetIterator tmp; while (it != _set->end()) { @@ -128,29 +128,29 @@ void Set::removeAllObjects() } } -bool Set::containsObject(Object *pObject) +bool __Set::containsObject(Object *pObject) { return _set->find(pObject) != _set->end(); } -SetIterator Set::begin(void) +__SetIterator __Set::begin(void) { return _set->begin(); } -SetIterator Set::end(void) +__SetIterator __Set::end(void) { return _set->end(); } -Object* Set::anyObject() +Object* __Set::anyObject() { if (!_set || _set->empty()) { return 0; } - SetIterator it; + __SetIterator it; for( it = _set->begin(); it != _set->end(); ++it) { diff --git a/cocos/base/CCSet.h b/cocos/base/CCSet.h index c748f0ada5..89ef7d0ac4 100644 --- a/cocos/base/CCSet.h +++ b/cocos/base/CCSet.h @@ -35,35 +35,35 @@ NS_CC_BEGIN * @{ */ -typedef std::set::iterator SetIterator; +typedef std::set::iterator __SetIterator; -class CC_DLL Set : public Object +class CC_DLL __Set : public Object { public: /** * @js ctor */ - Set(void); - Set(const Set &rSetObject); + __Set(void); + __Set(const __Set &rSetObject); /** * @js NA * @lua NA */ - virtual ~Set(void); + virtual ~__Set(void); /** * @brief Create and return a new empty set. */ - static Set * create(); + static __Set * create(); /** *@brief Return a copy of the Set, it will copy all the elements. */ - Set* copy(); + __Set* copy(); /** *@brief It is the same as copy(). */ - Set* mutableCopy(); + __Set* mutableCopy(); /** *@brief Return the number of elements the Set contains. */ @@ -89,13 +89,13 @@ public: * @js NA * @lua NA */ - SetIterator begin(); + __SetIterator begin(); /** *@brief Return the iterator that points to the position after the last element. * @js NA * @lua NA */ - SetIterator end(); + __SetIterator end(); /** *@brief Return the first element if it contains elements, or null if it doesn't contain any element. */ diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index 046e8f2e7a..97e1261f48 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -146,9 +146,9 @@ const char* String::getCString() const return _string.c_str(); } -unsigned int String::length() const +int String::length() const { - return _string.length(); + return static_cast(_string.length()); } int String::compare(const char * pStr) const @@ -178,11 +178,11 @@ void String::appendWithFormat(const char* format, ...) } -Array* String::componentsSeparatedByString(const char *delimiter) +__Array* String::componentsSeparatedByString(const char *delimiter) { - Array* result = Array::create(); + __Array* result = __Array::create(); - int cutAt; + size_t cutAt; while( (cutAt = _string.find_first_of(delimiter)) != _string.npos ) { if(cutAt > 0) @@ -221,7 +221,7 @@ String* String::create(const std::string& str) return ret; } -String* String::createWithData(const unsigned char* data, unsigned long nLen) +String* String::createWithData(const unsigned char* data, int nLen) { String* ret = NULL; if (data != NULL) @@ -255,11 +255,11 @@ String* String::createWithFormat(const char* format, ...) String* String::createWithContentsOfFile(const char* filename) { - long size = 0; + ssize_t size = 0; unsigned char* data = 0; String* ret = NULL; data = FileUtils::getInstance()->getFileData(filename, "rb", &size); - ret = String::createWithData(data, size); + ret = String::createWithData(data, static_cast(size)); free(data); return ret; } diff --git a/cocos/base/CCString.h b/cocos/base/CCString.h index a6f237a476..19af0302e2 100644 --- a/cocos/base/CCString.h +++ b/cocos/base/CCString.h @@ -114,7 +114,7 @@ public: /** get the length of string * @js NA */ - unsigned int length() const; + int length() const; /** compare to a c string * @js NA @@ -137,7 +137,7 @@ public: * @js NA * @lua NA */ - Array* componentsSeparatedByString(const char *delimiter); + __Array* componentsSeparatedByString(const char *delimiter); /* override functions * @js NA @@ -164,7 +164,7 @@ public: * it means that you needn't do a release operation unless you retain it. * @js NA */ - static String* createWithData(const unsigned char* pData, unsigned long nLen); + static String* createWithData(const unsigned char* pData, int nLen); /** create a string with a file, * @return A String pointer which is an autorelease object pointer, diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp new file mode 100644 index 0000000000..fa6e457425 --- /dev/null +++ b/cocos/base/CCValue.cpp @@ -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 + +NS_CC_BEGIN + +Value::Value() +: _vectorData(new ValueVector()) +, _mapData(new ValueMap()) +, _intKeyMapData(new IntValueMap()) +, _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 diff --git a/cocos/base/CCValue.h b/cocos/base/CCValue.h new file mode 100644 index 0000000000..498cf0f1f4 --- /dev/null +++ b/cocos/base/CCValue.h @@ -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 +#include +#include + +NS_CC_BEGIN + +class Value; + +typedef std::vector ValueVector; +typedef std::unordered_map ValueMap; +typedef std::unordered_map 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__) */ diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h new file mode 100644 index 0000000000..3ea40ccc8a --- /dev/null +++ b/cocos/base/CCVector.h @@ -0,0 +1,399 @@ +/**************************************************************************** +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 "ccMacros.h" + +#include +#include +#include // std::for_each + +NS_CC_BEGIN + +template +class CC_DLL Vector +{ +public: + Vector() + : _data() + { + + } + + /** creates an emptry Vector */ + explicit Vector(int capacity) + : _data() + { + CCLOGINFO("In the default constructor with capacity of Vector."); + reserve(capacity); + } + + virtual ~Vector() + { + CCLOGINFO("In the destructor of Vector."); + clear(); + } + + Vector(const Vector& other) + { + CCLOGINFO("In the copy constructor!"); + _data = other._data; + addRefForAllObjects(); + } + + /** Move constructor */ + Vector(Vector&& other) + { + CCLOGINFO("In the move constructor of Vector!"); + _data = other._data; + } + + Vector& operator=(const Vector& other) + { + CCLOGINFO("In the copy assignment operator!"); + clear(); + _data = other._data; + addRefForAllObjects(); + return *this; + } + + Vector& operator=(Vector&& 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[](int index) +// { +// return _data[index]; +// } +// +// const T& operator[](int index) const +// { +// return _data[index]; +// } + + /** Sets capacity of current array */ + void reserve(int capacity) + { + _data.reserve(capacity); + } + + /** Returns capacity of the array */ + int capacity() const + { + return _data.capacity(); + } + + // Querying an Array + + /** Returns element count of the array */ + int size() const + { + return static_cast(_data.size()); + } + + bool empty() const + { + return _data.empty(); + } + + /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ + int getIndex(T object) const + { + int 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(int 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 &other) + { + size_t s = this->size(); + if (s != other.size()) + return false; + + for (int 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& 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(int 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, bool toRelease = true) + { + 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); + if (toRelease) + object->release(); + } + + /** Removes an element with a certain index */ + void remove(int 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) + { + auto idx1 = getIndex(object1); + auto 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(int index1, int 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(int 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(const std::function& callback) + { + if (empty()) + return; + + std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){ + callback(obj); + }); + } + + void forEach(const std::function& callback) const + { + if (empty()) + return; + + std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){ + callback(obj); + }); + } + + void forEachReverse(const std::function& callback) + { + if (empty()) + return; + + std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){ + callback(obj); + }); + } + + void forEachReverse(const std::function& callback) const + { + if (empty()) + return; + + std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){ + callback(obj); + }); + } + + void sort(const std::function& callback) + { + if (empty()) + return; + + std::sort(_data.begin(), _data.end(), [&callback](T a, T b) -> bool{ + return callback(a, b); + }); + } + + // ------------------------------------------ + // Iterators + // ------------------------------------------ + typedef typename std::vector::iterator iterator; + typedef typename std::vector::const_iterator const_iterator; + + typedef typename std::vector::reverse_iterator reverse_iterator; + typedef typename std::vector::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 _data; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CCVECTOR_H__ diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index 3d37d21a2f..06d3e582c1 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -10,9 +10,11 @@ set(COCOS_BASE_SRC CCString.cpp CCDataVisitor.cpp CCData.cpp + CCValue.cpp etc1.cpp s3tc.cpp atitc.cpp + CCConsole.cpp ) add_library(cocosbase STATIC diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index df8721de0d..0db26201de 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp @@ -529,9 +529,9 @@ void CCBAnimationManager::setAnimatedProperty(const char *propName, Node *pNode, void CCBAnimationManager::setFirstFrame(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration) { - Array *keyframes = pSeqProp->getKeyframes(); + auto& keyframes = pSeqProp->getKeyframes(); - if (keyframes->count() == 0) + if (keyframes.empty()) { // Use base value (no animation) Object *baseValue = getBaseValue(pNode, pSeqProp->getName()); @@ -541,7 +541,7 @@ void CCBAnimationManager::setFirstFrame(Node *pNode, CCBSequenceProperty *pSeqPr else { // Use first keyframe - CCBKeyframe *keyframe = (CCBKeyframe*)keyframes->getObjectAtIndex(0); + CCBKeyframe *keyframe = keyframes.at(0); setAnimatedProperty(pSeqProp->getName(), pNode, keyframe->getValue(), fTweenDuration); } } @@ -620,18 +620,18 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann float lastKeyframeTime = 0; - Array *actions = Array::create(); - Array *keyframes = channel->getKeyframes(); - long numKeyframes = keyframes->count(); + Vector actions; + auto& keyframes = channel->getKeyframes(); + int numKeyframes = keyframes.size(); for (long i = 0; i < numKeyframes; ++i) { - CCBKeyframe *keyframe = (CCBKeyframe*)keyframes->getObjectAtIndex(i); + CCBKeyframe *keyframe = keyframes.at(i); 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(keyframe->getValue()); @@ -646,7 +646,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann CallFunc *callbackClone = (static_cast(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,17 +699,17 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) float lastKeyframeTime = 0; - Array *actions = Array::create(); - Array *keyframes = channel->getKeyframes(); - int numKeyframes = keyframes->count(); + Vector actions; + auto& keyframes = channel->getKeyframes(); + int numKeyframes = keyframes.size(); - for (int i = 0; i < numKeyframes; ++i) { - - CCBKeyframe *keyframe = (CCBKeyframe*)keyframes->getObjectAtIndex(i); + for (int i = 0; i < numKeyframes; ++i) + { + CCBKeyframe *keyframe = keyframes.at(i); 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,38 +729,38 @@ 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); } void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration) { - Array *keyframes = pSeqProp->getKeyframes(); - int numKeyframes = keyframes->count(); + auto& keyframes = pSeqProp->getKeyframes(); + int numKeyframes = keyframes.size(); if (numKeyframes > 1) { // Make an animation! - Array *actions = Array::create(); + Vector actions; - CCBKeyframe *keyframeFirst = (CCBKeyframe*)keyframes->getObjectAtIndex(0); + CCBKeyframe *keyframeFirst = keyframes.at(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) { - CCBKeyframe *kf0 = (CCBKeyframe*)keyframes->getObjectAtIndex(i); - CCBKeyframe *kf1 = (CCBKeyframe*)keyframes->getObjectAtIndex(i+1); + CCBKeyframe *kf0 = keyframes.at(i); + CCBKeyframe *kf1 = keyframes.at(i+1); ActionInterval *action = getAction(kf0, kf1, pSeqProp->getName(), pNode); if (action) @@ -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); } } diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index bf566770fe..2ab5ca1c79 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -24,7 +24,7 @@ namespace cocosbuilder {; Implementation of CCBFile *************************************************************************/ -CCBFile::CCBFile():_CCBFileNode(NULL) {} +CCBFile::CCBFile():_CCBFileNode(nullptr) {} CCBFile* CCBFile::create() { @@ -55,18 +55,13 @@ void CCBFile::setCCBFileNode(Node *pNode) *************************************************************************/ CCBReader::CCBReader(NodeLoaderLibrary * pNodeLoaderLibrary, CCBMemberVariableAssigner * pCCBMemberVariableAssigner, CCBSelectorResolver * pCCBSelectorResolver, NodeLoaderListener * pNodeLoaderListener) -: _data(NULL) -, _bytes(NULL) +: _data(nullptr) +, _bytes(nullptr) , _currentByte(-1) , _currentBit(-1) -, _owner(NULL) -, _actionManager(NULL) -, _actionManagers(NULL) -, _animatedProps(NULL) -, _ownerOutletNodes(NULL) -, _nodesWithAnimationManagers(NULL) -, _animationManagersForNodes(NULL) -, _ownerCallbackNodes(NULL) +, _owner(nullptr) +, _actionManager(nullptr) +, _animatedProps(nullptr) { this->_nodeLoaderLibrary = pNodeLoaderLibrary; this->_nodeLoaderLibrary->retain(); @@ -77,18 +72,13 @@ CCBReader::CCBReader(NodeLoaderLibrary * pNodeLoaderLibrary, CCBMemberVariableAs } CCBReader::CCBReader(CCBReader * ccbReader) -: _data(NULL) -, _bytes(NULL) +: _data(nullptr) +, _bytes(nullptr) , _currentByte(-1) , _currentBit(-1) -, _owner(NULL) -, _actionManager(NULL) -, _actionManagers(NULL) -, _animatedProps(NULL) -, _ownerOutletNodes(NULL) -, _nodesWithAnimationManagers(NULL) -, _animationManagersForNodes(NULL) -, _ownerCallbackNodes(NULL) +, _owner(nullptr) +, _actionManager(nullptr) +, _animatedProps(nullptr) { this->_loadedSpriteSheets = ccbReader->_loadedSpriteSheets; this->_nodeLoaderLibrary = ccbReader->_nodeLoaderLibrary; @@ -104,19 +94,16 @@ CCBReader::CCBReader(CCBReader * ccbReader) } CCBReader::CCBReader() -: _data(NULL) -, _bytes(NULL) +: _data(nullptr) +, _bytes(nullptr) , _currentByte(-1) , _currentBit(-1) -, _owner(NULL) -, _actionManager(NULL) -, _actionManagers(NULL) -, _nodeLoaderLibrary(NULL) -, _nodeLoaderListener(NULL) -, _CCBMemberVariableAssigner(NULL) -, _CCBSelectorResolver(NULL) -, _nodesWithAnimationManagers(NULL) -, _animationManagersForNodes(NULL) +, _owner(nullptr) +, _actionManager(nullptr) +, _nodeLoaderLibrary(nullptr) +, _nodeLoaderListener(nullptr) +, _CCBMemberVariableAssigner(nullptr) +, _CCBSelectorResolver(nullptr) { init(); } @@ -128,23 +115,18 @@ CCBReader::~CCBReader() this->_nodeLoaderLibrary->release(); - CC_SAFE_RELEASE(_ownerOutletNodes); _ownerOutletNames.clear(); - CC_SAFE_RELEASE(_ownerCallbackNodes); _ownerCallbackNames.clear(); - CC_SAFE_RELEASE(_ownerOwnerCallbackControlEvents); // Clear string cache. this->_stringCache.clear(); - CC_SAFE_RELEASE(_nodesWithAnimationManagers); - CC_SAFE_RELEASE(_animationManagersForNodes); - setAnimationManager(NULL); + setAnimationManager(nullptr); } void CCBReader::setCCBRootPath(const char* ccbRootPath) { - CCASSERT(ccbRootPath != NULL, ""); + CCASSERT(ccbRootPath != nullptr, ""); _CCBRootPath = ccbRootPath; } @@ -155,13 +137,6 @@ const std::string& CCBReader::getCCBRootPath() const bool CCBReader::init() { - _ownerOutletNodes = new Array(); - _ownerOutletNodes->init(); - _ownerCallbackNodes = new Array(); - _ownerCallbackNodes->init(); - _ownerOwnerCallbackControlEvents = new Array(); - _ownerOwnerCallbackControlEvents->init(); - // Setup action manager CCBAnimationManager *pActionManager = new CCBAnimationManager(); setAnimationManager(pActionManager); @@ -185,12 +160,12 @@ void CCBReader::setAnimationManager(CCBAnimationManager *pAnimationManager) CC_SAFE_RETAIN(_actionManager); } -Dictionary* CCBReader::getAnimationManagers() +Map& CCBReader::getAnimationManagers() { return _actionManagers; } -void CCBReader::setAnimationManagers(Dictionary* x) +void CCBReader::setAnimationManagers(const Map& x) { _actionManagers = x; } @@ -220,7 +195,7 @@ Object* CCBReader::getOwner() Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName) { - return this->readNodeGraphFromFile(pCCBFileName, NULL); + return this->readNodeGraphFromFile(pCCBFileName, nullptr); } Node* CCBReader::readNodeGraphFromFile(const char* pCCBFileName, Object* pOwner) @@ -230,9 +205,9 @@ Node* CCBReader::readNodeGraphFromFile(const char* pCCBFileName, Object* pOwner) Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, const Size &parentSize) { - if (NULL == pCCBFileName || strlen(pCCBFileName) == 0) + if (nullptr == pCCBFileName || strlen(pCCBFileName) == 0) { - return NULL; + return nullptr; } std::string strCCBFileName(pCCBFileName); @@ -270,7 +245,7 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & _actionManager->setRootContainerSize(parentSize); _actionManager->_owner = _owner; - Dictionary* animationManagers = Dictionary::create(); + Map animationManagers; Node *pNodeGraph = readFileWithCleanUp(true, animationManagers); if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1) @@ -280,25 +255,17 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & } // Assign actionManagers to userObject - if(_jsControlled) - { - _nodesWithAnimationManagers = new Array(); - _nodesWithAnimationManagers->init(); - _animationManagersForNodes = new Array(); - _animationManagersForNodes->init(); - } - DictElement* pElement = NULL; - CCDICT_FOREACH(animationManagers, pElement) + for (auto iter = _actionManagers.begin(); iter != _actionManagers.end(); ++iter) { - Node* pNode = (Node*)pElement->getIntKey(); - CCBAnimationManager* manager = static_cast(animationManagers->objectForKey((intptr_t)pNode)); + Node* pNode = iter->first; + CCBAnimationManager* manager = iter->second; pNode->setUserObject(manager); if (_jsControlled) { - _nodesWithAnimationManagers->addObject(pNode); - _animationManagersForNodes->addObject(manager); + _nodesWithAnimationManagers.pushBack(pNode); + _animationManagersForNodes.pushBack(manager); } } @@ -307,7 +274,7 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & Scene* CCBReader::createSceneWithNodeGraphFromFile(const char *pCCBFileName) { - return createSceneWithNodeGraphFromFile(pCCBFileName, NULL); + return createSceneWithNodeGraphFromFile(pCCBFileName, nullptr); } Scene* CCBReader::createSceneWithNodeGraphFromFile(const char *pCCBFileName, Object *pOwner) @@ -324,39 +291,37 @@ 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(pChild)); - } + node->getChildren().forEach([this](Node* obj){ + cleanUpNodeGraph(obj); + }); } -Node* CCBReader::readFileWithCleanUp(bool bCleanUp, Dictionary* am) +Node* CCBReader::readFileWithCleanUp(bool bCleanUp, const Map& am) { if (! readHeader()) { - return NULL; + return nullptr; } if (! readStringCache()) { - return NULL; + return nullptr; } if (! readSequences()) { - return NULL; + return nullptr; } setAnimationManagers(am); - Node *pNode = readNodeGraph(NULL); + Node *pNode = readNodeGraph(nullptr); - _actionManagers->setObject(_actionManager, intptr_t(pNode)); + _actionManagers.insert(pNode, _actionManager); if (bCleanUp) { @@ -379,7 +344,7 @@ bool CCBReader::readStringCache() { bool CCBReader::readHeader() { /* If no bytes loaded, don't crash about it. */ - if(this->_bytes == NULL) { + if(this->_bytes == nullptr) { return false; } @@ -569,7 +534,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) if (! ccNodeLoader) { log("no corresponding node loader for %s", className.c_str()); - return NULL; + return nullptr; } Node *node = ccNodeLoader->loadNode(pParent, this); @@ -613,7 +578,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { CCBKeyframe *keyframe = readKeyframe(static_cast(seqProp->getType())); - seqProp->getKeyframes()->addObject(keyframe); + seqProp->getKeyframes().pushBack(keyframe); } seqNodeProps->setObject(seqProp, seqProp->getName()); @@ -630,7 +595,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) // Read properties ccNodeLoader->parseProperties(node, pParent, this); - bool isCCBFileNode = (NULL == dynamic_cast(node)) ? false : true; + bool isCCBFileNode = (nullptr == dynamic_cast(node)) ? false : true; // Handle sub ccb files (remove middle node) if (isCCBFileNode) { @@ -647,7 +612,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) _actionManager->moveAnimationsFromNode(ccbFileNode, embeddedNode); - ccbFileNode->setCCBFileNode(NULL); + ccbFileNode->setCCBFileNode(nullptr); node = embeddedNode; } @@ -663,7 +628,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { if(!_jsControlled) { - Object * target = NULL; + Object * target = nullptr; if(memberVarAssignmentType == TargetType::DOCUMENT_ROOT) { target = _actionManager->getRootNode(); @@ -673,19 +638,19 @@ Node * CCBReader::readNodeGraph(Node * pParent) target = this->_owner; } - if(target != NULL) + if(target != nullptr) { CCBMemberVariableAssigner * targetAsCCBMemberVariableAssigner = dynamic_cast(target); bool assigned = false; if (memberVarAssignmentType != TargetType::NONE) { - if(targetAsCCBMemberVariableAssigner != NULL) + if(targetAsCCBMemberVariableAssigner != nullptr) { assigned = targetAsCCBMemberVariableAssigner->onAssignCCBMemberVariable(target, memberVarAssignmentName.c_str(), node); } - if(!assigned && this->_CCBMemberVariableAssigner != NULL) + if(!assigned && this->_CCBMemberVariableAssigner != nullptr) { assigned = this->_CCBMemberVariableAssigner->onAssignCCBMemberVariable(target, memberVarAssignmentName.c_str(), node); } @@ -702,7 +667,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) else { _ownerOutletNames.push_back(memberVarAssignmentName); - _ownerOutletNodes->addObject(node); + _ownerOutletNodes.pushBack(node); } } } @@ -715,10 +680,10 @@ Node * CCBReader::readNodeGraph(Node * pParent) if(!_jsControlled) { Object * target = node; - if(target != NULL) + if(target != nullptr) { CCBMemberVariableAssigner * targetAsCCBMemberVariableAssigner = dynamic_cast(target); - if(targetAsCCBMemberVariableAssigner != NULL) + if(targetAsCCBMemberVariableAssigner != nullptr) { Dictionary* pCustomPropeties = ccNodeLoader->getCustomProperties(); DictElement* pElement; @@ -726,7 +691,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { customAssigned = targetAsCCBMemberVariableAssigner->onAssignCCBCustomProperty(target, pElement->getStrKey(), static_cast(pElement->getObject())); - if(!customAssigned && this->_CCBMemberVariableAssigner != NULL) + if(!customAssigned && this->_CCBMemberVariableAssigner != nullptr) { customAssigned = this->_CCBMemberVariableAssigner->onAssignCCBCustomProperty(target, pElement->getStrKey(), static_cast(pElement->getObject())); } @@ -739,7 +704,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) #endif // CCB_ENABLE_JAVASCRIPT delete _animatedProps; - _animatedProps = NULL; + _animatedProps = nullptr; /* Read and add children. */ int numChildren = this->readInt(false); @@ -756,11 +721,11 @@ Node * CCBReader::readNodeGraph(Node * pParent) { // Call onNodeLoaded NodeLoaderListener * nodeAsNodeLoaderListener = dynamic_cast(node); - if(nodeAsNodeLoaderListener != NULL) + if(nodeAsNodeLoaderListener != nullptr) { nodeAsNodeLoaderListener->onNodeLoaded(node, ccNodeLoader); } - else if(this->_nodeLoaderListener != NULL) + else if(this->_nodeLoaderListener != nullptr) { this->_nodeLoaderListener->onNodeLoaded(node, ccNodeLoader); } @@ -777,7 +742,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) CCBKeyframe::EasingType easingType = static_cast(readInt(false)); float easingOpt = 0; - Object *value = NULL; + Object *value = nullptr; if (easingType == CCBKeyframe::EasingType::CUBIC_IN || easingType == CCBKeyframe::EasingType::CUBIC_OUT @@ -820,7 +785,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) value = Array::create(CCBValue::create(a), CCBValue::create(b), - NULL); + nullptr); } else if (type == PropertyType::SPRITEFRAME) { @@ -891,7 +856,7 @@ bool CCBReader::readCallbackKeyframesForSeq(CCBSequence* seq) _actionManager->getKeyframeCallbacks()->addObject(String::createWithFormat("%d:%s",callbackType, callbackName.c_str())); } - channel->getKeyframes()->addObject(keyframe); + channel->getKeyframes().pushBack(keyframe); } seq->setCallbackChannel(channel); @@ -924,7 +889,7 @@ bool CCBReader::readSoundKeyframesForSeq(CCBSequence* seq) { CCBKeyframe* keyframe = new CCBKeyframe(); keyframe->setTime(time); keyframe->setValue(value); - channel->getKeyframes()->addObject(keyframe); + channel->getKeyframes().pushBack(keyframe); keyframe->release(); } @@ -935,7 +900,7 @@ bool CCBReader::readSoundKeyframesForSeq(CCBSequence* seq) { Node * CCBReader::readNodeGraph() { - return this->readNodeGraph(NULL); + return this->readNodeGraph(nullptr); } bool CCBReader::readSequences() @@ -1010,12 +975,12 @@ void CCBReader::addOwnerCallbackName(const std::string& name) void CCBReader::addOwnerCallbackNode(Node *node) { - _ownerCallbackNodes->addObject(node); + _ownerCallbackNodes.pushBack(node); } void CCBReader::addOwnerCallbackControlEvents(Control::EventType type) { - _ownerOwnerCallbackControlEvents->addObject(Integer::create((int)type)); + _ownerOwnerCallbackControlEvents.push_back(Value((int)type)); } void CCBReader::addDocumentCallbackName(const std::string& name) @@ -1033,50 +998,53 @@ void CCBReader::addDocumentCallbackControlEvents(Control::EventType eventType) _actionManager->addDocumentCallbackControlEvents(eventType); } -Array* CCBReader::getOwnerCallbackNames() +ValueVector CCBReader::getOwnerCallbackNames() { - Array* pRet = Array::createWithCapacity(_ownerCallbackNames.size()); + ValueVector ret; + ret.reserve(_ownerCallbackNames.size()); + std::vector::iterator it = _ownerCallbackNames.begin(); for (; it != _ownerCallbackNames.end(); ++it) { - pRet->addObject(String::create(*it)); + ret.push_back(Value(*it)); } - return pRet; + return std::move(ret); } -Array* CCBReader::getOwnerCallbackNodes() +Vector& CCBReader::getOwnerCallbackNodes() { return _ownerCallbackNodes; } -Array* CCBReader::getOwnerCallbackControlEvents() +ValueVector& CCBReader::getOwnerCallbackControlEvents() { return _ownerOwnerCallbackControlEvents; } -Array* CCBReader::getOwnerOutletNames() +ValueVector CCBReader::getOwnerOutletNames() { - Array* pRet = Array::createWithCapacity(_ownerOutletNames.size()); + ValueVector ret; + ret.reserve(_ownerOutletNames.size()); std::vector::iterator it = _ownerOutletNames.begin(); for (; it != _ownerOutletNames.end(); ++it) { - pRet->addObject(String::create(*it)); + ret.push_back(Value(*it)); } - return pRet; + return std::move(ret); } -Array* CCBReader::getOwnerOutletNodes() +Vector& CCBReader::getOwnerOutletNodes() { return _ownerOutletNodes; } -Array* CCBReader::getNodesWithAnimationManagers() +Vector& CCBReader::getNodesWithAnimationManagers() { return _nodesWithAnimationManagers; } -Array* CCBReader::getAnimationManagersForNodes() +Vector& CCBReader::getAnimationManagersForNodes() { return _animationManagersForNodes; } @@ -1088,10 +1056,10 @@ void CCBReader::addOwnerOutletName(std::string name) void CCBReader::addOwnerOutletNode(Node *node) { - if (NULL == node) + if (nullptr == node) return; - _ownerOutletNodes->addObject(node); + _ownerOutletNodes.pushBack(node); } /************************************************************************ diff --git a/cocos/editor-support/cocosbuilder/CCBReader.h b/cocos/editor-support/cocosbuilder/CCBReader.h index 211ea18de4..5e3c2a963a 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.h +++ b/cocos/editor-support/cocosbuilder/CCBReader.h @@ -282,24 +282,24 @@ public: bool readCallbackKeyframesForSeq(CCBSequence* seq); bool readSoundKeyframesForSeq(CCBSequence* seq); - cocos2d::Array* getOwnerCallbackNames(); - cocos2d::Array* getOwnerCallbackNodes(); - cocos2d::Array* getOwnerCallbackControlEvents(); + cocos2d::ValueVector getOwnerCallbackNames(); + cocos2d::Vector& getOwnerCallbackNodes(); + cocos2d::ValueVector& getOwnerCallbackControlEvents(); - cocos2d::Array* getOwnerOutletNames(); - cocos2d::Array* getOwnerOutletNodes(); - cocos2d::Array* getNodesWithAnimationManagers(); - cocos2d::Array* getAnimationManagersForNodes(); + cocos2d::ValueVector getOwnerOutletNames(); + cocos2d::Vector& getOwnerOutletNodes(); + cocos2d::Vector& getNodesWithAnimationManagers(); + cocos2d::Vector& getAnimationManagersForNodes(); /** * @js NA * @lua NA */ - cocos2d::Dictionary* getAnimationManagers(); + cocos2d::Map& getAnimationManagers(); /** * @js NA * @lua NA */ - void setAnimationManagers(cocos2d::Dictionary* x); // weak reference + void setAnimationManagers(const cocos2d::Map& x); // weak reference /** * @js NA * @lua NA @@ -332,7 +332,7 @@ public: * @js NA * @lua NA */ - cocos2d::Node* readFileWithCleanUp(bool bCleanUp, cocos2d::Dictionary* am); + cocos2d::Node* readFileWithCleanUp(bool bCleanUp, const cocos2d::Map& am); void addOwnerOutletName(std::string name); void addOwnerOutletNode(cocos2d::Node *node); @@ -367,7 +367,7 @@ private: cocos2d::Object *_owner; CCBAnimationManager *_actionManager; //retain - cocos2d::Dictionary* _actionManagers; + cocos2d::Map _actionManagers; std::set *_animatedProps; @@ -377,13 +377,13 @@ private: CCBSelectorResolver *_CCBSelectorResolver; std::vector _ownerOutletNames; - cocos2d::Array* _ownerOutletNodes; - cocos2d::Array* _nodesWithAnimationManagers; - cocos2d::Array* _animationManagersForNodes; + cocos2d::Vector _ownerOutletNodes; + cocos2d::Vector _nodesWithAnimationManagers; + cocos2d::Vector _animationManagersForNodes; std::vector _ownerCallbackNames; - cocos2d::Array* _ownerCallbackNodes; - cocos2d::Array* _ownerOwnerCallbackControlEvents; + cocos2d::Vector _ownerCallbackNodes; + cocos2d::ValueVector _ownerOwnerCallbackControlEvents; std::string _CCBRootPath; bool _jsControlled; diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp index a091adaad1..fa74e33881 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp @@ -14,15 +14,11 @@ CCBSequenceProperty::CCBSequenceProperty() bool CCBSequenceProperty::init() { - _keyframes = new Array(); - _keyframes->init(); - return true; } CCBSequenceProperty::~CCBSequenceProperty() { - CC_SAFE_RELEASE_NULL(_keyframes); } const char* CCBSequenceProperty::getName() @@ -45,7 +41,7 @@ void CCBSequenceProperty::setType(int type) _type = type; } -Array* CCBSequenceProperty::getKeyframes() +cocos2d::Vector& CCBSequenceProperty::getKeyframes() { return _keyframes; } diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h index cd097c2356..03ca04799f 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h @@ -27,12 +27,12 @@ public: int getType(); void setType(int type); - cocos2d::Array* getKeyframes(); + cocos2d::Vector& getKeyframes(); private: std::string _name; int _type; - cocos2d::Array *_keyframes; + cocos2d::Vector _keyframes; }; } diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index bf4bd84106..742fa154c6 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -964,33 +964,31 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader { //set variables and callback to owner //set callback - Array *ownerCallbackNames = reader->getOwnerCallbackNames(); - Array *ownerCallbackNodes = reader->getOwnerCallbackNodes(); - if (NULL != ownerCallbackNames && ownerCallbackNames->count() > 0 && - NULL != ownerCallbackNodes && ownerCallbackNodes->count() > 0) + auto ownerCallbackNames = reader->getOwnerCallbackNames(); + auto& ownerCallbackNodes = reader->getOwnerCallbackNodes(); + if (!ownerCallbackNames.empty() && !ownerCallbackNodes.empty()) { - CCASSERT(ownerCallbackNames->count() == ownerCallbackNodes->count(), ""); - int nCount = ownerCallbackNames->count(); + CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(), ""); + int nCount = ownerCallbackNames.size(); for (int i = 0 ; i < nCount; i++) { - pCCBReader->addOwnerCallbackName((dynamic_cast(ownerCallbackNames->getObjectAtIndex(i)))->getCString()); - pCCBReader->addOwnerCallbackNode(dynamic_cast(ownerCallbackNodes->getObjectAtIndex(i)) ); + pCCBReader->addOwnerCallbackName(ownerCallbackNames[i].asString()); + pCCBReader->addOwnerCallbackNode(ownerCallbackNodes.at(i)); } } //set variables - Array *ownerOutletNames = reader->getOwnerOutletNames(); - Array *ownerOutletNodes = reader->getOwnerOutletNodes(); - if (NULL != ownerOutletNames && ownerOutletNames->count() > 0 && - NULL != ownerOutletNodes && ownerOutletNodes->count() > 0) + auto ownerOutletNames = reader->getOwnerOutletNames(); + auto ownerOutletNodes = reader->getOwnerOutletNodes(); + if (!ownerOutletNames.empty() && !ownerOutletNodes.empty()) { - CCASSERT(ownerOutletNames->count() == ownerOutletNodes->count(), ""); - int nCount = ownerOutletNames->count(); + CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(), ""); + int nCount = ownerOutletNames.size(); for (int i = 0 ; i < nCount; i++) { - pCCBReader->addOwnerOutletName((static_cast(ownerOutletNames->getObjectAtIndex(i)))->getCString()); - pCCBReader->addOwnerOutletNode(static_cast(ownerOutletNodes->getObjectAtIndex(i))); + pCCBReader->addOwnerOutletName(ownerOutletNames.at(i).asString()); + pCCBReader->addOwnerOutletNode(ownerOutletNodes.at(i)); } } } diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index 64a91744d0..1947eeb0bf 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -276,7 +276,8 @@ Spawn * ActionNode::refreshActionProperty() { return NULL; } - Array* cSpawnArray = Array::create(); + Vector 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 cSequenceArray; + auto 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(cAction)); } } Sequence* cSequence = Sequence::create(cSequenceArray); if (cSequence != NULL) { - cSpawnArray->addObject(cSequence); + cSpawnArray.pushBack(cSequence); } } diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index b09922ff70..2585f00bfb 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -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(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(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( _children->getObjectAtIndex(i) ); + bs = static_cast( _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(object)) { diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 0f00332265..844e25f286 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -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(object); if (armature) diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index e4f61a171f..18b14e40b2 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -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(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(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); } } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 35d1fe95f3..1a158c3734 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -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); diff --git a/cocos/editor-support/spine/Atlas.cpp b/cocos/editor-support/spine/Atlas.cpp index e3d6d799b4..05920d4693 100644 --- a/cocos/editor-support/spine/Atlas.cpp +++ b/cocos/editor-support/spine/Atlas.cpp @@ -136,7 +136,7 @@ static int readTuple (const char* end, Str tuple[]) { } static char* mallocString (Str* str) { - int length = str->end - str->begin; + size_t length = str->end - str->begin; char* string = MALLOC(char, length + 1); memcpy(string, str->begin, length); string[length] = '\0'; @@ -144,7 +144,7 @@ static char* mallocString (Str* str) { } static int indexOf (const char** array, int count, Str* str) { - int length = str->end - str->begin; + size_t length = str->end - str->begin; int i; for (i = count - 1; i >= 0; i--) if (strncmp(array[i], str->begin, length) == 0) return i; @@ -156,7 +156,7 @@ static int equals (Str* str, const char* other) { } static int toInt (Str* str) { - return strtol(str->begin, (char**)&str->end, 10); + return static_cast(strtol(str->begin, (char**)&str->end, 10)); } static Atlas* abortAtlas (Atlas* self) { @@ -171,7 +171,7 @@ static const char* textureFilterNames[] = {"Nearest", "Linear", "MipMap", "MipMa Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) { int count; const char* end = begin + length; - int dirLength = strlen(dir); + size_t dirLength = strlen(dir); int needsSlash = dirLength > 0 && dir[dirLength - 1] != '/' && dir[dirLength - 1] != '\\'; Atlas* self = NEW(Atlas); @@ -285,7 +285,7 @@ Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) { Atlas* Atlas_readAtlasFile (const char* path) { int dirLength; char *dir; - int length; + ssize_t length; const char* data; Atlas* atlas = 0; @@ -295,13 +295,13 @@ Atlas* Atlas_readAtlasFile (const char* path) { const char* lastBackwardSlash = strrchr(path, '\\'); const char* lastSlash = lastForwardSlash > lastBackwardSlash ? lastForwardSlash : lastBackwardSlash; if (lastSlash == path) lastSlash++; /* Never drop starting slash. */ - dirLength = lastSlash ? lastSlash - path : 0; + dirLength = static_cast(lastSlash ? lastSlash - path : 0); dir = MALLOC(char, dirLength + 1); memcpy(dir, path, dirLength); dir[dirLength] = '\0'; data = _Util_readFile(path, &length); - if (data) atlas = Atlas_readAtlas(data, length, dir); + if (data) atlas = Atlas_readAtlas(data, static_cast(length), dir); FREE(data); FREE(dir); diff --git a/cocos/editor-support/spine/SkeletonJson.cpp b/cocos/editor-support/spine/SkeletonJson.cpp index 6c1e039b10..9b391ef2db 100644 --- a/cocos/editor-support/spine/SkeletonJson.cpp +++ b/cocos/editor-support/spine/SkeletonJson.cpp @@ -232,7 +232,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S } SkeletonData* SkeletonJson_readSkeletonDataFile (SkeletonJson* self, const char* path) { - int length; + ssize_t length; SkeletonData* skeletonData; const char* json = _Util_readFile(path, &length); if (!json) { diff --git a/cocos/editor-support/spine/extension.h b/cocos/editor-support/spine/extension.h index 019b7350d7..f5d1a2ac9b 100644 --- a/cocos/editor-support/spine/extension.h +++ b/cocos/editor-support/spine/extension.h @@ -96,7 +96,7 @@ namespace spine { void _AtlasPage_createTexture (AtlasPage* self, const char* path); void _AtlasPage_disposeTexture (AtlasPage* self); -char* _Util_readFile (const char* path, int* length); +char* _Util_readFile (const char* path, ssize_t* length); /* * Internal API available for extension: diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index 298031aaab..81bc4adeb2 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -46,8 +46,8 @@ void _AtlasPage_disposeTexture (AtlasPage* self) { ((TextureAtlas*)self->rendererObject)->release(); } -char* _Util_readFile (const char* path, int* length) { - long size; +char* _Util_readFile (const char* path, ssize_t* length) { + ssize_t size; char* data = reinterpret_cast(FileUtils::getInstance()->getFileData( FileUtils::getInstance()->fullPathForFilename(path).c_str(), "r", &size)); *length = size; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 4f6be40d32..c2fcb7817d 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -105,7 +105,7 @@ bool UICCTextField::onTextFieldDetachWithIME(cocos2d::TextFieldTTF *pSender) void UICCTextField::insertText(const char * text, int len) { std::string str_text = text; - int str_len = cocos2d::TextFieldTTF::getString().size(); + size_t str_len = cocos2d::TextFieldTTF::getString().size(); if (strcmp(text, "\n") != 0) { diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index 05cf29cdf5..e53e54ffbb 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -42,7 +42,7 @@ static std::mutex s_responseQueueMutex; static std::mutex s_SleepMutex; static std::condition_variable s_SleepCondition; -static unsigned long s_asyncRequestCount = 0; +static int s_asyncRequestCount = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) typedef int int32_t; diff --git a/cocos/network/SocketIO.cpp b/cocos/network/SocketIO.cpp index d4d66ac137..cc2dedf802 100644 --- a/cocos/network/SocketIO.cpp +++ b/cocos/network/SocketIO.cpp @@ -182,24 +182,24 @@ void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response std::string res = s.str(); std::string sid; - int pos = 0; + size_t pos = 0; int heartbeat = 0, timeout = 0; pos = res.find(":"); - if(pos >= 0) + if(pos != std::string::npos) { sid = res.substr(0, pos); res.erase(0, pos+1); } pos = res.find(":"); - if(pos >= 0) + if(pos != std::string::npos) { heartbeat = atoi(res.substr(pos+1, res.size()).c_str()); } pos = res.find(":"); - if(pos >= 0) + if(pos != std::string::npos) { timeout = atoi(res.substr(pos+1, res.size()).c_str()); } @@ -381,21 +381,21 @@ void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) std::string payload, msgid, endpoint, s_data, eventname; payload = data.bytes; - int pos, pos2; + size_t pos, pos2; pos = payload.find(":"); - if(pos >=0 ) { + if(pos != std::string::npos ) { payload.erase(0, pos+1); } pos = payload.find(":"); - if(pos > 0 ) { + if(pos != std::string::npos ) { msgid = atoi(payload.substr(0, pos+1).c_str()); } payload.erase(0, pos+1); pos = payload.find(":"); - if(pos >= 0) + if(pos != std::string::npos) { endpoint = payload.substr(0, pos); payload.erase(0, pos+1); @@ -617,33 +617,33 @@ SIOClient* SocketIO::connect(SocketIO::SIODelegate& delegate, const std::string& { std::string host = uri; int port = 0; - int pos = 0; + size_t pos = 0; pos = host.find("//"); - if (pos >= 0) + if (pos != std::string::npos) { host.erase(0, pos+2); } pos = host.find(":"); - if (pos >= 0) + if (pos != std::string::npos) { port = atoi(host.substr(pos+1, host.size()).c_str()); } pos = host.find("/", 0); std::string path = "/"; - if (pos >= 0) + if (pos != std::string::npos) { path += host.substr(pos + 1, host.size()); } pos = host.find(":"); - if (pos >= 0) + if (pos != std::string::npos) { host.erase(pos, host.size()); } - else if ((pos = host.find("/"))>=0) + else if ((pos = host.find("/")) != std::string::npos) { host.erase(pos, host.size()); } diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 883c1d8554..2e91b54bc0 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -243,7 +243,7 @@ bool WebSocket::init(const Delegate& delegate, bool ret = false; bool useSSL = false; std::string host = url; - int pos = 0; + size_t pos = 0; int port = 80; _delegate = const_cast(&delegate); @@ -260,16 +260,16 @@ bool WebSocket::init(const Delegate& delegate, } pos = host.find(":"); - if (pos >= 0) port = atoi(host.substr(pos+1, host.size()).c_str()); + if (pos != std::string::npos) port = atoi(host.substr(pos+1, host.size()).c_str()); pos = host.find("/", 0); std::string path = "/"; - if (pos >= 0) path += host.substr(pos + 1, host.size()); + if (pos != std::string::npos) path += host.substr(pos + 1, host.size()); pos = host.find(":"); - if(pos >= 0){ + if(pos != std::string::npos){ host.erase(pos, host.size()); - }else if((pos = host.find("/"))>=0) { + }else if((pos = host.find("/")) != std::string::npos) { host.erase(pos, host.size()); } @@ -280,7 +280,7 @@ bool WebSocket::init(const Delegate& delegate, CCLOG("[WebSocket::init] _host: %s, _port: %d, _path: %s", _host.c_str(), _port, _path.c_str()); - int protocolCount = 0; + size_t protocolCount = 0; if (protocols && protocols->size() > 0) { protocolCount = protocols->size(); @@ -329,7 +329,7 @@ void WebSocket::send(const std::string& message) Data* data = new Data(); data->bytes = new char[message.length()+1]; strcpy(data->bytes, message.c_str()); - data->len = message.length(); + data->len = static_cast(message.length()); msg->obj = data; _wsHelper->sendMessageToSubThread(msg); } @@ -446,7 +446,7 @@ void WebSocket::onSubThreadEnded() int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, struct libwebsocket *wsi, int reason, - void *user, void *in, size_t len) + void *user, void *in, ssize_t len) { //CCLOG("socket callback for %d reason", reason); CCASSERT(_wsContext == nullptr || ctx == _wsContext, "Invalid context."); diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index da9a497b71..9a354d47a4 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -62,7 +62,7 @@ public: { Data():bytes(NULL), len(0), isBinary(false){} char* bytes; - int len; + ssize_t len; bool isBinary; }; @@ -143,7 +143,7 @@ private: int onSocketCallback(struct libwebsocket_context *ctx, struct libwebsocket *wsi, int reason, - void *user, void *in, size_t len); + void *user, void *in, ssize_t len); private: State _readyState; diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index d351444abd..69a197b9b7 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -51,7 +51,6 @@ namespace PhysicsBody::PhysicsBody() : _node(nullptr) -, _shapes(nullptr) , _world(nullptr) , _info(nullptr) , _dynamic(true) @@ -251,9 +250,6 @@ bool PhysicsBody::init() { _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); - _shapes = Array::create(); - CC_BREAK_IF(_shapes == nullptr); - _shapes->retain(); _info->setBody(cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment))); @@ -368,7 +364,7 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* if (shape == nullptr) return nullptr; // add shape to body - if (_shapes->getIndexOfObject(shape) == CC_INVALID_INDEX) + if (_shapes.getIndex(shape) == -1) { shape->setBody(this); @@ -386,7 +382,7 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* _world->addShape(shape); } - _shapes->addObject(shape); + _shapes.pushBack(shape); if (_group != CP_NO_GROUP && shape->getGroup() == CP_NO_GROUP) { @@ -631,9 +627,8 @@ void PhysicsBody::setMoment(float moment) PhysicsShape* PhysicsBody::getShape(int tag) const { - for (auto child : *_shapes) + for (auto& shape : _shapes) { - PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { return shape; @@ -645,9 +640,8 @@ PhysicsShape* PhysicsBody::getShape(int tag) const void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) { - for (auto child : *_shapes) + for (auto& shape : _shapes) { - PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { removeShape(shape, reduceMassAndMoment); @@ -658,7 +652,7 @@ void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = true*/) { - if (_shapes->getIndexOfObject(shape) != CC_INVALID_INDEX) + if (_shapes.getIndex(shape) != -1) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -678,13 +672,13 @@ void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. shape->_body = nullptr; shape->setBody(nullptr); - _shapes->removeObject(shape); + _shapes.removeObject(shape); } } void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/) { - for (auto child : *_shapes) + for (auto& child : _shapes) { PhysicsShape* shape = dynamic_cast(child); @@ -707,7 +701,7 @@ void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/) shape->setBody(nullptr); } - _shapes->removeAllObjects(); + _shapes.clear(); } void PhysicsBody::removeFromWorld() @@ -757,9 +751,9 @@ void PhysicsBody::setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setCategoryBitmask(bitmask); + shape->setCategoryBitmask(bitmask); } } @@ -767,9 +761,9 @@ void PhysicsBody::setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setContactTestBitmask(bitmask); + shape->setContactTestBitmask(bitmask); } } @@ -777,17 +771,17 @@ void PhysicsBody::setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setCollisionBitmask(bitmask); + shape->setCollisionBitmask(bitmask); } } void PhysicsBody::setGroup(int group) { - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setGroup(group); + shape->setGroup(group); } } diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index f6d2e91f71..8d31d82e61 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -25,15 +25,13 @@ #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" #include "CCGeometry.h" -#include "CCArray.h" - #include "CCPhysicsShape.h" - -#include +#include "CCVector.h" NS_CC_BEGIN class Sprite; @@ -102,9 +100,9 @@ public: /* remove all shapes */ void removeAllShapes(bool reduceMassAndMoment = true); /* get the body shapes. */ - inline Array* getShapes() const { return _shapes; } + inline const Vector& getShapes() const { return _shapes; } /* get the first shape of the body shapes. */ - inline PhysicsShape* getFirstShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + inline PhysicsShape* getFirstShape() const { return _shapes.size() >= 1 ? _shapes.at(0) : nullptr; } /* get the shape of the body. */ PhysicsShape* getShape(int tag) const; @@ -304,7 +302,7 @@ protected: protected: Node* _node; std::vector _joints; - Array* _shapes; + Vector _shapes; PhysicsWorld* _world; PhysicsBodyInfo* _info; bool _dynamic; diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 24eb0f4c69..f734574565 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_CONTACT_H__ #define __CCPHYSICS_CONTACT_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" @@ -44,7 +45,7 @@ typedef Point Vect; typedef struct PhysicsContactData { - static const long POINT_MAX = 4; + static const int POINT_MAX = 4; Point points[POINT_MAX]; int count; Point normal; diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index ad90a1a7a8..701950e6f8 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_JOINT_H__ #define __CCPHYSICS_JOINT_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index b045c433a6..a77072e9bd 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -597,7 +597,7 @@ void PhysicsShapePolygon::getPoints(Point* outPoints) const PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, outPoints, ((cpPolyShape*)shape)->numVerts); } -long PhysicsShapePolygon::getPointsCount() const +int PhysicsShapePolygon::getPointsCount() const { return ((cpPolyShape*)_info->getShapes().front())->numVerts; } @@ -712,9 +712,9 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -long PhysicsShapeEdgePolygon::getPointsCount() const +int PhysicsShapeEdgePolygon::getPointsCount() const { - return _info->getShapes().size() + 1; + return static_cast(_info->getShapes().size() + 1); } // PhysicsShapeEdgeChain @@ -773,9 +773,9 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -long PhysicsShapeEdgeChain::getPointsCount() const +int PhysicsShapeEdgeChain::getPointsCount() const { - return _info->getShapes().size() + 1; + return static_cast(_info->getShapes().size() + 1); } void PhysicsShape::setGroup(int group) diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index b97bb3cba6..1fb86e14d7 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_SHAPE_H__ #define __CCPHYSICS_SHAPE_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" @@ -206,7 +207,7 @@ public: Point getPoint(int i) const; void getPoints(Point* outPoints) const; - long getPointsCount() const; + int getPointsCount() const; virtual Point getCenter() override; protected: bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); @@ -249,7 +250,7 @@ public: static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Point& offset = Point::ZERO); virtual Point getOffset() override { return _offset; } void getPoints(const Point* outPoints) const; - long getPointsCount() const; + int getPointsCount() const; protected: bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); @@ -271,7 +272,7 @@ public: static PhysicsShapeEdgePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); virtual Point getCenter() override; void getPoints(Point* outPoints) const; - long getPointsCount() const; + int getPointsCount() const; protected: bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -293,7 +294,7 @@ public: static PhysicsShapeEdgeChain* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); virtual Point getCenter() override; void getPoints(Point* outPoints) const; - long getPointsCount() const; + int getPointsCount() const; protected: bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 70bae33eff..da07a5590b 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -55,6 +55,12 @@ NS_CC_BEGIN const float PHYSICS_INFINITY = INFINITY; extern const char* PHYSICSCONTACT_EVENT_NAME; +const int PhysicsWorld::DEBUGDRAW_NONE = 0x00; +const int PhysicsWorld::DEBUGDRAW_SHAPE = 0x01; +const int PhysicsWorld::DEBUGDRAW_JOINT = 0x02; +const int PhysicsWorld::DEBUGDRAW_CONTACT = 0x04; +const int PhysicsWorld::DEBUGDRAW_ALL = DEBUGDRAW_SHAPE | DEBUGDRAW_JOINT | DEBUGDRAW_CONTACT; + namespace { typedef struct RayCastCallbackInfo @@ -91,7 +97,7 @@ public: static void rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect n, RayCastCallbackInfo *info); static void queryRectCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info); static void queryPointFunc(cpShape *shape, cpFloat distance, cpVect point, PointQueryCallbackInfo *info); - static void getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr); + static void getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Vector* arr); public: static bool continues; @@ -170,13 +176,13 @@ void PhysicsWorldCallback::queryRectCallbackFunc(cpShape *shape, RectQueryCallba PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } -void PhysicsWorldCallback::getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) +void PhysicsWorldCallback::getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Vector* arr) { auto it = PhysicsShapeInfo::getMap().find(shape); CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - arr->addObject(it->second->getShape()); + arr->pushBack(it->second->getShape()); } void PhysicsWorldCallback::queryPointFunc(cpShape *shape, cpFloat distance, cpVect point, PointQueryCallbackInfo *info) @@ -195,17 +201,17 @@ void PhysicsWorld::debugDraw() _debugDraw = new PhysicsDebugDraw(*this); } - if (_debugDraw && _bodies != nullptr) + if (_debugDraw && !_bodies.empty()) { if (_debugDraw->begin()) { if (_debugDrawMask & DEBUGDRAW_SHAPE) { - for (Object* obj : *_bodies) + for (Object* obj : _bodies) { PhysicsBody* body = dynamic_cast(obj); - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { _debugDraw->drawShape(*dynamic_cast(shape)); } @@ -386,18 +392,18 @@ void PhysicsWorld::queryPoint(PhysicsPointQueryCallbackFunc func, const Point& p } } -Array* PhysicsWorld::getShapes(const Point& point) const +Vector PhysicsWorld::getShapes(const Point& point) const { - Array* arr = Array::create(); + Vector arr; cpSpaceNearestPointQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, CP_NO_GROUP, (cpSpaceNearestPointQueryFunc)PhysicsWorldCallback::getShapesAtPointFunc, - arr); + &arr); - return arr; + return std::move(arr); } PhysicsShape* PhysicsWorld::getShape(const Point& point) const @@ -556,17 +562,8 @@ bool PhysicsWorld::init(Scene& scene) { do { - _delayAddBodies = Array::create(); - _delayRemoveBodies = Array::create(); - CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); - _delayAddBodies->retain(); - _delayRemoveBodies->retain(); - _info = new PhysicsWorldInfo(); CC_BREAK_IF(_info == nullptr); - _bodies = Array::create(); - CC_BREAK_IF(_bodies == nullptr); - _bodies->retain(); _scene = &scene; @@ -600,7 +597,7 @@ void PhysicsWorld::addBody(PhysicsBody* body) } addBodyOrDelay(body); - _bodies->addObject(body); + _bodies.pushBack(body); body->_world = this; } @@ -621,7 +618,7 @@ void PhysicsWorld::doAddBody(PhysicsBody* body) } // add shapes to space - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { addShape(dynamic_cast(shape)); } @@ -631,17 +628,17 @@ void PhysicsWorld::doAddBody(PhysicsBody* body) void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) { - if (_delayRemoveBodies->getIndexOfObject(body) != CC_INVALID_INDEX) + if (_delayRemoveBodies.getIndex(body) != CC_INVALID_INDEX) { - _delayRemoveBodies->removeObject(body); + _delayRemoveBodies.removeObject(body); return; } if (_info->isLocked()) { - if (_delayAddBodies->getIndexOfObject(body) == CC_INVALID_INDEX) + if (_delayAddBodies.getIndex(body) == CC_INVALID_INDEX) { - _delayAddBodies->addObject(body); + _delayAddBodies.pushBack(body); _delayDirty = true; } }else @@ -657,25 +654,24 @@ void PhysicsWorld::updateBodies() return; } - for (auto body : *_delayAddBodies) + for (auto& body : _delayAddBodies) { - doAddBody(dynamic_cast(body)); + doAddBody(body); } - for (auto body : *_delayRemoveBodies) + for (auto& body : _delayRemoveBodies) { - doRemoveBody(dynamic_cast(body)); + doRemoveBody(body); } - _delayAddBodies->removeAllObjects(); - _delayRemoveBodies->removeAllObjects(); + _delayAddBodies.clear(); + _delayRemoveBodies.clear(); } void PhysicsWorld::removeBody(int tag) { - for (Object* obj : *_bodies) + for (auto& body : _bodies) { - PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == tag) { removeBody(body); @@ -716,24 +712,24 @@ void PhysicsWorld::removeBody(PhysicsBody* body) body->_joints.clear(); removeBodyOrDelay(body); - _bodies->removeObject(body); + _bodies.removeObject(body); body->_world = nullptr; } void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) { - if (_delayAddBodies->getIndexOfObject(body) != CC_INVALID_INDEX) + if (_delayAddBodies.getIndex(body) != CC_INVALID_INDEX) { - _delayAddBodies->removeObject(body); + _delayAddBodies.removeObject(body); return; } if (_info->isLocked()) { - if (_delayRemoveBodies->getIndexOfObject(body) == CC_INVALID_INDEX) + if (_delayRemoveBodies.getIndex(body) == CC_INVALID_INDEX) { - _delayRemoveBodies->addObject(body); + _delayRemoveBodies.pushBack(body); _delayDirty = true; } }else @@ -937,7 +933,7 @@ void PhysicsWorld::doRemoveBody(PhysicsBody* body) } // remove shaps - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { removeShape(dynamic_cast(shape)); } @@ -953,15 +949,14 @@ void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) void PhysicsWorld::removeAllBodies() { - for (Object* obj : *_bodies) + for (auto& obj : _bodies) { PhysicsBody* child = dynamic_cast(obj); removeBodyOrDelay(child); child->_world = nullptr; } - _bodies->removeAllObjects(); - CC_SAFE_RELEASE(_bodies); + _bodies.clear(); } void PhysicsWorld::setDebugDrawMask(int mask) @@ -974,18 +969,18 @@ void PhysicsWorld::setDebugDrawMask(int mask) _debugDrawMask = mask; } -Array* PhysicsWorld::getAllBodies() const +const Vector& PhysicsWorld::getAllBodies() const { return _bodies; } PhysicsBody* PhysicsWorld::getBody(int tag) const { - for (auto body : *_bodies) + for (auto& body : _bodies) { - if (((PhysicsBody*)body)->getTag() == tag) + if (body->getTag() == tag) { - return (PhysicsBody*)body; + return body; } } @@ -994,12 +989,10 @@ PhysicsBody* PhysicsWorld::getBody(int tag) const void PhysicsWorld::setGravity(const Vect& gravity) { - if (_bodies != nullptr) + if (!_bodies.empty()) { - for (auto child : *_bodies) + for (auto& body : _bodies) { - PhysicsBody* body = dynamic_cast(child); - // reset gravity for body if (!body->isGravityEnabled()) { @@ -1020,10 +1013,10 @@ void PhysicsWorld::update(float delta) // the updateJoints must run before the updateBodies. updateJoints(); updateBodies(); - _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); + _delayDirty = !(_delayAddBodies.size() == 0 && _delayRemoveBodies.size() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); } - for (auto body : *_bodies) + for (auto& body : _bodies) { body->update(delta); } @@ -1040,13 +1033,10 @@ PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) , _info(nullptr) -, _bodies(nullptr) , _scene(nullptr) , _delayDirty(false) , _debugDraw(nullptr) , _debugDrawMask(DEBUGDRAW_NONE) -, _delayAddBodies(nullptr) -, _delayRemoveBodies(nullptr) { } @@ -1055,8 +1045,6 @@ PhysicsWorld::~PhysicsWorld() { removeAllJoints(true); removeAllBodies(); - CC_SAFE_RELEASE(_delayRemoveBodies); - CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); CC_SAFE_DELETE(_debugDraw); } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 389cde4f2c..dfd85e5744 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -25,14 +25,15 @@ #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS -#include -#include - +#include "CCVector.h" #include "CCObject.h" #include "CCGeometry.h" +#include + NS_CC_BEGIN class PhysicsBody; @@ -40,7 +41,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class Array; typedef Point Vect; @@ -82,11 +82,11 @@ typedef PhysicsRectQueryCallbackFunc PhysicsPointQueryCallbackFunc; class PhysicsWorld { public: - static const long DEBUGDRAW_NONE = 0x00; - static const long DEBUGDRAW_SHAPE = 0x01; - static const long DEBUGDRAW_JOINT = 0x02; - static const long DEBUGDRAW_CONTACT = 0x04; - static const long DEBUGDRAW_ALL = DEBUGDRAW_SHAPE | DEBUGDRAW_JOINT | DEBUGDRAW_CONTACT; + static const int DEBUGDRAW_NONE; + static const int DEBUGDRAW_SHAPE; + static const int DEBUGDRAW_JOINT; + static const int DEBUGDRAW_CONTACT; + static const int DEBUGDRAW_ALL; public: /** Adds a joint to the physics world.*/ @@ -103,9 +103,9 @@ public: void rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data); void queryRect(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data); void queryPoint(PhysicsPointQueryCallbackFunc func, const Point& point, void* data); - Array* getShapes(const Point& point) const; + Vector getShapes(const Point& point) const; PhysicsShape* getShape(const Point& point) const; - Array* getAllBodies() const; + const Vector& getAllBodies() const; PhysicsBody* getBody(int tag) const; /** Register a listener to receive contact callbacks*/ @@ -155,7 +155,7 @@ protected: float _speed; PhysicsWorldInfo* _info; - Array* _bodies; + Vector _bodies; std::list _joints; Scene* _scene; @@ -164,8 +164,8 @@ protected: int _debugDrawMask; - Array* _delayAddBodies; - Array* _delayRemoveBodies; + Vector _delayAddBodies; + Vector _delayRemoveBodies; std::vector _delayAddJoints; std::vector _delayRemoveJoints; diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 6cda96c2e1..701783402c 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifdef CC_USE_PHYSICS #include "CCPhysicsBodyInfo_chipmunk.h" +#ifdef CC_USE_PHYSICS NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index 40509df692..7c695885b2 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -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" diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index e0e4cfd85a..bd0d46515e 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -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) diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 1ba81dbba7..78e377e434 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -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" diff --git a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index 7641a78cfa..eb420ce3b1 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_HELPER_CHIPMUNK_H__ #define __CCPHYSICS_HELPER_CHIPMUNK_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include "chipmunk.h" diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index f7c4b25f91..0df8c2a7c6 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifdef CC_USE_PHYSICS #include "CCPhysicsJointInfo_chipmunk.h" +#ifdef CC_USE_PHYSICS #include #include diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 0e57cbb445..e3d57eff32 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -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" diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index 6bc43b8262..3df70185ee 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#ifdef CC_USE_PHYSICS #include "CCPhysicsShapeInfo_chipmunk.h" +#ifdef CC_USE_PHYSICS #include #include diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 97402b9722..5ac25a2eb8 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -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 #include diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index fd218e1575..8b7f078215 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -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" diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 7eda879ec9..5554573101 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ #define __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 020c08e110..2a17a90f89 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -1480,21 +1480,21 @@ JSBool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret) js_proxy_t* jsb_new_proxy(void* nativeObj, JSObject* jsObj) { - js_proxy_t* p; + js_proxy_t* p = nullptr; JS_NEW_PROXY(p, nativeObj, jsObj); return p; } js_proxy_t* jsb_get_native_proxy(void* nativeObj) { - js_proxy_t* p; + js_proxy_t* p = nullptr; JS_GET_PROXY(p, nativeObj); return p; } js_proxy_t* jsb_get_js_proxy(JSObject* jsObj) { - js_proxy_t* p; + js_proxy_t* p = nullptr; JS_GET_NATIVE_PROXY(p, jsObj); return p; } diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 706f47b31d..29352b90d5 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -d725d2de77c275c86fc8739e13fdf31684cacf74 \ No newline at end of file +7a245db1098d7ced5947aca62f43e67f06d1492d \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp index 26c5a14009..9cfe63fec7 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp @@ -508,6 +508,71 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r return ok; } +JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, cocos2d::ValueVector* ret) +{ + + for (int i = 0; i < argc; i++) + { + jsval value = *vp; + if (value.isObject()) + { + JSObject* jsobj = JSVAL_TO_OBJECT(value); + CCASSERT(jsb_get_js_proxy(jsobj) == nullptr, "Native object should be added!"); + + if (!JS_IsArrayObject(cx, jsobj)) + { + // It's a normal js object. + ValueMap dictVal; + JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + if (ok) + { + ret->push_back(Value(dictVal)); + } + } + else { + // It's a js array object. + ValueVector arrVal; + JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + if (ok) + { + ret->push_back(Value(arrVal)); + } + } + } + else if (JSVAL_IS_STRING(value)) + { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + ret->push_back(Value(valueWapper.get())); + } + else if (JSVAL_IS_NUMBER(value)) + { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) + { + ret->push_back(Value(number)); + } + } + else if (JSVAL_IS_BOOLEAN(value)) + { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) + { + ret->push_back(Value(boolVal)); + } + } + else + { + CCASSERT(false, "not supported type"); + } + // next + vp++; + } + + return JS_TRUE; +} + JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { JSObject *tmp; JS::RootedValue jsx(cx); @@ -658,7 +723,8 @@ JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int * } -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { +JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) +{ JSObject *jsobj; JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); @@ -717,7 +783,7 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { arr->addObject(Bool::create(boolVal)); - // CCLOG("iterate object: value = %d", boolVal); + // CCLOG("iterate object: value = %d", boolVal); } } else { @@ -729,6 +795,317 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { return JS_TRUE; } +JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) +{ + if (v.isObject()) + { + JSObject* jsobj = JSVAL_TO_OBJECT(v); + CCASSERT(jsb_get_js_proxy(jsobj) == nullptr, "Native object should be added!"); + if (!JS_IsArrayObject(cx, jsobj)) + { + // It's a normal js object. + ValueMap dictVal; + JSBool ok = jsval_to_ccvaluemap(cx, v, &dictVal); + if (ok) + { + *ret = Value(dictVal); + } + } + else { + // It's a js array object. + ValueVector arrVal; + JSBool ok = jsval_to_ccvaluevector(cx, v, &arrVal); + if (ok) + { + *ret = Value(arrVal); + } + } + } + else if (JSVAL_IS_STRING(v)) + { + JSStringWrapper valueWapper(JSVAL_TO_STRING(v), cx); + *ret = Value(valueWapper.get()); + } + else if (JSVAL_IS_NUMBER(v)) + { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, v, &number); + if (ok) { + *ret = Value(number); + } + } + else if (JSVAL_IS_BOOLEAN(v)) + { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, v, &boolVal); + if (ok) { + *ret = Value(boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + + return JS_TRUE; +} + +JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) +{ + if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) + { + return JS_TRUE; + } + + JSObject* tmp = JSVAL_TO_OBJECT(v); + if (!tmp) { + CCLOG("%s", "jsval_to_ccvaluemap: the jsval is not an object."); + return JS_FALSE; + } + + JSObject* it = JS_NewPropertyIterator(cx, tmp); + + ValueMap& dict = *ret; + + while (true) + { + jsid idp; + jsval key; + if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { + return JS_FALSE; // error + } + + if (key == JSVAL_VOID) { + break; // end of iteration + } + + if (!JSVAL_IS_STRING(key)) { + continue; // ignore integer properties + } + + JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); + + JS::RootedValue value(cx); + JS_GetPropertyById(cx, tmp, idp, &value); + if (value.isObject()) + { + JSObject* jsobj = JSVAL_TO_OBJECT(value); + CCASSERT(jsb_get_js_proxy(jsobj) == nullptr, "Native object should be added!"); + if (!JS_IsArrayObject(cx, jsobj)) + { + // It's a normal js object. + ValueMap dictVal; + JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + if (ok) + { + dict[keyWrapper.get()] = Value(dictVal); + } + } + else { + // It's a js array object. + ValueVector arrVal; + JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + if (ok) + { + dict[keyWrapper.get()] = Value(arrVal); + } + } + } + else if (JSVAL_IS_STRING(value)) + { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + dict[keyWrapper.get()] = Value(valueWapper.get()); + // CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) + { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + dict[keyWrapper.get()] = Value(number); + // CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) + { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + dict[keyWrapper.get()] = Value(boolVal); + // CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + + return JS_TRUE; +} + +JSBool jsval_to_ccintvaluemap(JSContext* cx, jsval v, cocos2d::IntValueMap* ret) +{ + if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) + { + return JS_TRUE; + } + + JSObject* tmp = JSVAL_TO_OBJECT(v); + if (!tmp) { + CCLOG("%s", "jsval_to_ccvaluemap: the jsval is not an object."); + return JS_FALSE; + } + + JSObject* it = JS_NewPropertyIterator(cx, tmp); + + IntValueMap& dict = *ret; + + while (true) + { + jsid idp; + jsval key; + if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { + return JS_FALSE; // error + } + + if (key == JSVAL_VOID) { + break; // end of iteration + } + + if (!JSVAL_IS_STRING(key)) { + continue; // ignore integer properties + } + + int keyVal = JSVAL_TO_INT(key); + + JS::RootedValue value(cx); + JS_GetPropertyById(cx, tmp, idp, &value); + if (value.isObject()) + { + JSObject* jsobj = JSVAL_TO_OBJECT(value); + CCASSERT(jsb_get_js_proxy(jsobj) == nullptr, "Native object should be added!"); + if (!JS_IsArrayObject(cx, jsobj)) + { + // It's a normal js object. + ValueMap dictVal; + JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + if (ok) + { + dict[keyVal] = Value(dictVal); + } + } + else { + // It's a js array object. + ValueVector arrVal; + JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + if (ok) + { + dict[keyVal] = Value(arrVal); + } + } + } + else if (JSVAL_IS_STRING(value)) + { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + dict[keyVal] = Value(valueWapper.get()); + } + else if (JSVAL_IS_NUMBER(value)) + { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + dict[keyVal] = Value(number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) + { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + dict[keyVal] = Value(boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + + return JS_TRUE; +} + +JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) +{ + JSObject *jsobj; + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + + uint32_t len = 0; + JS_GetArrayLength(cx, jsobj, &len); + + for (uint32_t i=0; i < len; i++) + { + jsval value; + if (JS_GetElement(cx, jsobj, i, &value)) + { + if (value.isObject()) + { + JSObject* jsobj = JSVAL_TO_OBJECT(value); + CCASSERT(jsb_get_js_proxy(jsobj) == nullptr, "Native object should be added!"); + + if (!JS_IsArrayObject(cx, jsobj)) + { + // It's a normal js object. + ValueMap dictVal; + JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + if (ok) + { + ret->push_back(Value(dictVal)); + } + } + else { + // It's a js array object. + ValueVector arrVal; + JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + if (ok) + { + ret->push_back(Value(arrVal)); + } + } + } + else if (JSVAL_IS_STRING(value)) + { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + ret->push_back(Value(valueWapper.get())); + } + else if (JSVAL_IS_NUMBER(value)) + { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) + { + ret->push_back(Value(number)); + } + } + else if (JSVAL_IS_BOOLEAN(value)) + { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) + { + ret->push_back(Value(boolVal)); + } + } + else + { + CCASSERT(false, "not supported type"); + } + } + } + + return JS_TRUE; +} + +// native --> jsval jsval ccarray_to_jsval(JSContext* cx, Array *arr) { @@ -872,7 +1249,7 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) if (value.isObject()) { js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); + tmp = JSVAL_TO_OBJECT(value); proxy = jsb_get_js_proxy(tmp); cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); // Don't test it. @@ -1467,3 +1844,180 @@ jsval CGPoint_to_jsval( JSContext *cx, cpVect p) return OBJECT_TO_JSVAL(typedArray); #endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES } + +jsval ccvalue_to_jsval(JSContext* cx, const cocos2d::Value& v) +{ + jsval ret = JSVAL_NULL; + const Value& obj = v; + + switch (obj.getType()) + { + case Value::Type::BOOLEAN: + ret = BOOLEAN_TO_JSVAL(obj.asBool()); + break; + case Value::Type::FLOAT: + case Value::Type::DOUBLE: + ret = DOUBLE_TO_JSVAL(obj.asDouble()); + break; + case Value::Type::INTEGER: + ret = INT_TO_JSVAL(obj.asInt()); + break; + case Value::Type::STRING: + ret = std_string_to_jsval(cx, obj.asString()); + break; + case Value::Type::VECTOR: + ret = ccvaluevector_to_jsval(cx, obj.asValueVector()); + break; + case Value::Type::MAP: + ret = ccvaluemap_to_jsval(cx, obj.asValueMap()); + break; + case Value::Type::INT_KEY_MAP: + ret = ccintvaluemap_to_jsval(cx, obj.asIntKeyMap()); + break; + default: + break; + } + + return ret; +} + +jsval ccvaluemap_to_jsval(JSContext* cx, const cocos2d::ValueMap& v) +{ + JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); + + for (auto iter = v.begin(); iter != v.end(); ++iter) + { + JS::RootedValue dictElement(cx); + + std::string key = iter->first; + const Value& obj = iter->second; + + switch (obj.getType()) + { + case Value::Type::BOOLEAN: + dictElement = BOOLEAN_TO_JSVAL(obj.asBool()); + break; + case Value::Type::FLOAT: + case Value::Type::DOUBLE: + dictElement = DOUBLE_TO_JSVAL(obj.asDouble()); + break; + case Value::Type::INTEGER: + dictElement = INT_TO_JSVAL(obj.asInt()); + break; + case Value::Type::STRING: + dictElement = std_string_to_jsval(cx, obj.asString()); + break; + case Value::Type::VECTOR: + dictElement = ccvaluevector_to_jsval(cx, obj.asValueVector()); + break; + case Value::Type::MAP: + dictElement = ccvaluemap_to_jsval(cx, obj.asValueMap()); + break; + case Value::Type::INT_KEY_MAP: + dictElement = ccintvaluemap_to_jsval(cx, obj.asIntKeyMap()); + break; + default: + break; + } + + if (!key.empty()) + { + JS_SetProperty(cx, jsRet, key.c_str(), dictElement); + } + } + return OBJECT_TO_JSVAL(jsRet); +} + +jsval ccintvaluemap_to_jsval(JSContext* cx, const cocos2d::IntValueMap& v) +{ + JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); + + for (auto iter = v.begin(); iter != v.end(); ++iter) + { + JS::RootedValue dictElement(cx); + std::stringstream keyss; + keyss << iter->first; + std::string key = keyss.str(); + + const Value& obj = iter->second; + + switch (obj.getType()) + { + case Value::Type::BOOLEAN: + dictElement = BOOLEAN_TO_JSVAL(obj.asBool()); + break; + case Value::Type::FLOAT: + case Value::Type::DOUBLE: + dictElement = DOUBLE_TO_JSVAL(obj.asDouble()); + break; + case Value::Type::INTEGER: + dictElement = INT_TO_JSVAL(obj.asInt()); + break; + case Value::Type::STRING: + dictElement = std_string_to_jsval(cx, obj.asString()); + break; + case Value::Type::VECTOR: + dictElement = ccvaluevector_to_jsval(cx, obj.asValueVector()); + break; + case Value::Type::MAP: + dictElement = ccvaluemap_to_jsval(cx, obj.asValueMap()); + break; + case Value::Type::INT_KEY_MAP: + dictElement = ccintvaluemap_to_jsval(cx, obj.asIntKeyMap()); + break; + default: + break; + } + + if (!key.empty()) + { + JS_SetProperty(cx, jsRet, key.c_str(), dictElement); + } + } + return OBJECT_TO_JSVAL(jsRet); +} + +jsval ccvaluevector_to_jsval(JSContext* cx, const cocos2d::ValueVector& v) +{ + JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); + + int i = 0; + for (const auto& obj : v) + { + jsval arrElement; + + switch (obj.getType()) + { + case Value::Type::BOOLEAN: + arrElement = BOOLEAN_TO_JSVAL(obj.asBool()); + break; + case Value::Type::FLOAT: + case Value::Type::DOUBLE: + arrElement = DOUBLE_TO_JSVAL(obj.asDouble()); + break; + case Value::Type::INTEGER: + arrElement = INT_TO_JSVAL(obj.asInt()); + break; + case Value::Type::STRING: + arrElement = std_string_to_jsval(cx, obj.asString()); + break; + case Value::Type::VECTOR: + arrElement = ccvaluevector_to_jsval(cx, obj.asValueVector()); + break; + case Value::Type::MAP: + arrElement = ccvaluemap_to_jsval(cx, obj.asValueMap()); + break; + case Value::Type::INT_KEY_MAP: + arrElement = ccintvaluemap_to_jsval(cx, obj.asIntKeyMap()); + break; + default: + break; + } + + if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { + break; + } + ++i; + } + return OBJECT_TO_JSVAL(jsretArr); +} diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.h b/cocos/scripting/javascript/bindings/js_manual_conversions.h index b0a8e80684..57ad197ec7 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.h +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.h @@ -8,6 +8,7 @@ #include "jsapi.h" #include "js_bindings_core.h" #include "cocos2d.h" +#include "spidermonkey_specifics.h" JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); @@ -44,9 +45,75 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, cocos2d::Array** ret); JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, cocos2d::Dictionary** ret); JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, cocos2d::Acceleration* ret); JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, cocos2d::Array** ret); + +// forward declaration +js_proxy_t* jsb_get_js_proxy(JSObject* jsObj); + +template +JSBool jsvals_variadic_to_ccvector( JSContext *cx, jsval *vp, int argc, cocos2d::Vector* ret) +{ + JSBool ok = JS_TRUE; + + for (int i = 0; i < argc; i++) + { + js_proxy_t* p; + JSObject* obj = JSVAL_TO_OBJECT(*vp); + p = jsb_get_js_proxy(obj); + CCASSERT(p, "Native object not found!"); + if (p) { + ret->pushBack((T)p->ptr); + } + + // next + vp++; + } + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + return ok; +} + +JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, cocos2d::ValueVector* ret); + JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, cocos2d::AffineTransform* ret); JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition* ret ); +template +JSBool jsval_to_ccvector(JSContext* cx, jsval v, cocos2d::Vector* ret) +{ + JSObject *jsobj; + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + + uint32_t len = 0; + JS_GetArrayLength(cx, jsobj, &len); + + for (uint32_t i=0; i < len; i++) + { + jsval value; + if (JS_GetElement(cx, jsobj, i, &value)) + { + CCASSERT(value.isObject(), "the element in Vector isn't a native object."); + + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + T cobj = (T)(proxy ? proxy->ptr : nullptr); + if (cobj) + { + ret->pushBack(cobj); + } + } + } + + return JS_TRUE; +} + +JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret); +JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret); +JSBool jsval_to_ccintvaluemap(JSContext* cx, jsval v, cocos2d::IntValueMap* ret); +JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret); + // from native jsval int32_to_jsval( JSContext *cx, int32_t l); jsval uint32_to_jsval( JSContext *cx, uint32_t number ); @@ -73,5 +140,38 @@ jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); #define cpVect_to_jsval CGPoint_to_jsval #define jsval_to_cpVect jsval_to_CGPoint + +template +js_proxy_t *js_get_or_create_proxy(JSContext *cx, T *native_obj); + +template +jsval ccvector_to_jsval(JSContext* cx, const cocos2d::Vector& v) +{ + JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); + + int i = 0; + for (const auto& obj : v) + { + jsval arrElement; + + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + arrElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + + if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { + break; + } + ++i; + } + return OBJECT_TO_JSVAL(jsretArr); +} + +jsval ccvalue_to_jsval(JSContext* cx, const cocos2d::Value& v); +jsval ccvaluemap_to_jsval(JSContext* cx, const cocos2d::ValueMap& v); +jsval ccintvaluemap_to_jsval(JSContext* cx, const cocos2d::IntValueMap& v); +jsval ccvaluevector_to_jsval(JSContext* cx, const cocos2d::ValueVector& v); + #endif /* __JS_MANUAL_CONVERSIONS_H__ */ diff --git a/extensions/Android.mk b/extensions/Android.mk index a5f4fd051f..a06c09bc47 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -25,7 +25,6 @@ GUI/CCEditBox/CCEditBoxImplNone.cpp \ GUI/CCEditBox/CCEditBoxImplTizen.cpp \ GUI/CCEditBox/CCEditBoxImplWin.cpp \ GUI/CCScrollView/CCScrollView.cpp \ -GUI/CCScrollView/CCSorting.cpp \ GUI/CCScrollView/CCTableView.cpp \ GUI/CCScrollView/CCTableViewCell.cpp \ physics-nodes/CCPhysicsDebugNode.cpp \ diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt index 176cd831ce..f8083e1220 100644 --- a/extensions/CMakeLists.txt +++ b/extensions/CMakeLists.txt @@ -18,7 +18,6 @@ set(EXTENSIONS_SRC GUI/CCEditBox/CCEditBoxImplTizen.cpp GUI/CCEditBox/CCEditBoxImplWin.cpp GUI/CCScrollView/CCScrollView.cpp - GUI/CCScrollView/CCSorting.cpp GUI/CCScrollView/CCTableView.cpp GUI/CCScrollView/CCTableViewCell.cpp physics-nodes/CCPhysicsDebugNode.cpp diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 3557c9bb5c..184b8125b5 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -74,10 +74,6 @@ bool Control::init() setSelected(false); setHighlighted(false); - // Initialise the tables - _dispatchTable = new Dictionary(); - _dispatchTable->init(); - auto dispatcher = Director::getInstance()->getEventDispatcher(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); @@ -97,7 +93,12 @@ bool Control::init() Control::~Control() { - CC_SAFE_RELEASE(_dispatchTable); + for (auto iter = _dispatchTable.begin(); iter != _dispatchTable.end(); ++iter) + { + delete iter->second; + } + + _dispatchTable.clear(); } void Control::sendActionsForControlEvents(EventType controlEvents) @@ -109,14 +110,12 @@ void Control::sendActionsForControlEvents(EventType controlEvents) if (((int)controlEvents & (1 << i))) { // Call invocations - // - Array* invocationList = this->dispatchListforControlEvent((Control::EventType)(1<(pObj); + const auto& invocationList = this->dispatchListforControlEvent((Control::EventType)(1<invoke(this); - } + }); + //Call ScriptFunc if (kScriptTypeLua == _scriptType) { @@ -161,8 +160,8 @@ void Control::addTargetWithActionForControlEvent(Object* target, Handler action, Invocation *invocation = Invocation::create(target, action, controlEvent); // Add the invocation into the dispatch list for the given control event - Array* eventInvocationList = this->dispatchListforControlEvent(controlEvent); - eventInvocationList->addObject(invocation); + auto& eventInvocationList = this->dispatchListforControlEvent(controlEvent); + eventInvocationList.pushBack(invocation); } void Control::removeTargetWithActionForControlEvents(Object* target, Handler action, EventType controlEvents) @@ -182,7 +181,7 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti { // Retrieve all invocations for the given control event // - Array *eventInvocationList = this->dispatchListforControlEvent(controlEvent); + auto& eventInvocationList = this->dispatchListforControlEvent(controlEvent); //remove all invocations if the target and action are null //TODO: should the invocations be deleted, or just removed from the array? Won't that cause issues if you add a single invocation for multiple events? @@ -190,30 +189,27 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti if (!target && !action) { //remove objects - eventInvocationList->removeAllObjects(); + eventInvocationList.clear(); } else { //normally we would use a predicate, but this won't work here. Have to do it manually - Object* pObj = NULL; - CCARRAY_FOREACH(eventInvocationList, pObj) + eventInvocationList.forEach([&](Invocation* invocation){ + bool shouldBeRemoved=true; + if (target) { - Invocation *invocation = static_cast(pObj); - bool shouldBeRemoved=true; - if (target) - { - shouldBeRemoved=(target==invocation->getTarget()); - } - if (action) - { - shouldBeRemoved=(shouldBeRemoved && (action==invocation->getAction())); - } - // Remove the corresponding invocation object - if (shouldBeRemoved) - { - eventInvocationList->removeObject(invocation, bDeleteObjects); - } + shouldBeRemoved=(target==invocation->getTarget()); } + if (action) + { + shouldBeRemoved=(shouldBeRemoved && (action==invocation->getAction())); + } + // Remove the corresponding invocation object + if (shouldBeRemoved) + { + eventInvocationList.removeObject(invocation, bDeleteObjects); + } + }); } } @@ -222,16 +218,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(child); - if (pNode) + + _children.forEach([&](Node* obj){ + RGBAProtocol* rgba = dynamic_cast(obj); + if (rgba) { - pNode->setOpacityModifyRGB(bOpacityModifyRGB); + rgba->setOpacityModifyRGB(bOpacityModifyRGB); } - } + }); } bool Control::isOpacityModifyRGB() const @@ -256,17 +250,22 @@ bool Control::isTouchInside(Touch* touch) return bBox.containsPoint(touchLocation); } -Array* Control::dispatchListforControlEvent(EventType controlEvent) +Vector& Control::dispatchListforControlEvent(EventType controlEvent) { - Array* invocationList = static_cast(_dispatchTable->objectForKey((int)controlEvent)); - + Vector* invocationList = nullptr; + auto iter = _dispatchTable.find((int)controlEvent); + // If the invocation list does not exist for the dispatch table, we create it - if (invocationList == NULL) + if (iter == _dispatchTable.end()) { - invocationList = Array::createWithCapacity(1); - _dispatchTable->setObject(invocationList, (int)controlEvent); - } - return invocationList; + invocationList = new Vector(); + _dispatchTable[(int)controlEvent] = invocationList; + } + else + { + invocationList = iter->second; + } + return *invocationList; } void Control::needsLayout() diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index a86970e1d8..d5adfa5dc7 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -210,8 +210,7 @@ protected: * * @return the Invocation list for the given control event. */ - // - Array* dispatchListforControlEvent(EventType controlEvent); + Vector& dispatchListforControlEvent(EventType controlEvent); /** * Adds a target and action for a particular event to an internal dispatch @@ -254,7 +253,7 @@ protected: * target-actions pairs. For each ButtonEvents a list of NSInvocation * (which contains the target-action pair) is linked. */ - Dictionary* _dispatchTable; + std::unordered_map*> _dispatchTable; //CCRGBAProtocol bool _isOpacityModifyRGB; diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 8ad857fd7c..d46726ee07 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp @@ -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(child); - if (pNode) + + _scale9Image->getChildren().forEach([this](Node* child){ + RGBAProtocol* rgba = dynamic_cast(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(child); - if (pNode) + + _scale9Image->getChildren().forEach([&color](Node* child){ + RGBAProtocol* rgba = dynamic_cast(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(child); - if (pNode) + + _scale9Image->getChildren().forEach([&opacity](Node* child){ + RGBAProtocol* rgba = dynamic_cast(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(child); - if (pNode) + + _scale9Image->getChildren().forEach([&parentColor](Node* child){ + RGBAProtocol* rgba = dynamic_cast(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(child); - if (pNode) + + _scale9Image->getChildren().forEach([&parentOpacity](Node* child){ + RGBAProtocol* rgba = dynamic_cast(child); + if (rgba) { - pNode->updateDisplayedOpacity(parentOpacity); + rgba->updateDisplayedOpacity(parentOpacity); } - } + }); } NS_CC_EXT_END diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 664b868e2e..2a61d5223e 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -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(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(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( _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( _children->getObjectAtIndex(i) ); + Node *child = _children.at(i); child->visit(); } diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp deleted file mode 100644 index 6f42dbd175..0000000000 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/**************************************************************************** - Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2010 Sangwoo Im - - 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 "CCSorting.h" -#include "ccCArray.h" - - -NS_CC_EXT_BEGIN - -class SortedObject : public Object, public SortableObject -{ -public: - SortedObject() : objectID(0) {} - virtual void setObjectID(long id) { this->objectID = id; } - virtual long getObjectID() { return objectID; } -private: - long objectID; -}; - -#if 0 -static int _compareObject(const void * val1, const void * val2) -{ - SortableObject* operand1; - SortableObject* operand2; - - operand1 = (SortableObject*)val1; - operand2 = (SortableObject*)val2; - - if (operand1->getObjectID() > operand2->getObjectID()) - { - return 1; - } - else if (operand1->getObjectID() < operand2->getObjectID()) { - return -1; - } - return 0; -} -#endif - - -void ArrayForObjectSorting::insertSortedObject(SortableObject* object) -{ - Object* pObj = dynamic_cast(object); - CCASSERT(pObj, "Invalid parameter."); - long idx = this->indexOfSortedObject(object); - - this->insertObject(pObj, idx); -} - -void ArrayForObjectSorting::removeSortedObject(SortableObject* object) -{ - if (this->count() == 0) { - return; - } - - SortableObject* foundObj = nullptr; - long idx = this->indexOfSortedObject(object); - - if (idx < this->count() && idx != CC_INVALID_INDEX) { - foundObj = dynamic_cast(this->getObjectAtIndex(idx)); - - if(foundObj->getObjectID() == object->getObjectID()) { - this->removeObjectAtIndex(idx); - } - } -} - -void ArrayForObjectSorting::setObjectID_ofSortedObject(unsigned int tag, SortableObject* object) -{ - SortableObject* foundObj = nullptr; - - long idx = this->indexOfSortedObject(object); - - if (idx < this->count() && idx != CC_INVALID_INDEX) - { - foundObj = dynamic_cast(this->getObjectAtIndex(idx)); - Object* pObj = dynamic_cast(foundObj); - pObj->retain(); - - if(foundObj->getObjectID() == object->getObjectID()) { - this->removeObjectAtIndex(idx); - foundObj->setObjectID(tag); - this->insertSortedObject(foundObj); - pObj->release(); - } else { - pObj->release(); - } - } -} - -SortableObject* ArrayForObjectSorting::objectWithObjectID(long tag) -{ - if (this->count() == 0) { - return NULL; - } - - SortableObject* foundObj = new SortedObject(); - foundObj->setObjectID(tag); - - long idx = this->indexOfSortedObject(foundObj); - - ((SortedObject*)foundObj)->release(); - foundObj = NULL; - - if (idx < this->count() && idx != CC_INVALID_INDEX) - { - foundObj = dynamic_cast(this->getObjectAtIndex(idx)); - if (foundObj->getObjectID() != tag) { - foundObj = NULL; - } - } - - return foundObj; -} - -long ArrayForObjectSorting::indexOfSortedObject(SortableObject* object) -{ - long idx = 0; - if (object) - { - // Object* pObj = (Object*)bsearch((Object*)&object, data->arr, data->num, sizeof(Object*), _compareObject); - // FIXME: need to use binary search to improve performance - Object* obj = NULL; - long prevObjectID = 0; - long ofSortObjectID = object->getObjectID(); - - CCARRAY_FOREACH(this, obj) - { - SortableObject* sortableObj = dynamic_cast(obj); - long curObjectID = sortableObj->getObjectID(); - if ( (ofSortObjectID == curObjectID) - || (ofSortObjectID >= prevObjectID && ofSortObjectID < curObjectID)) - { - break; - } - - prevObjectID = curObjectID; - idx++; - } - } - else - { - idx = CC_INVALID_INDEX; - } - return idx; -} - -NS_CC_EXT_END diff --git a/extensions/GUI/CCScrollView/CCSorting.h b/extensions/GUI/CCScrollView/CCSorting.h deleted file mode 100644 index cafcb62ece..0000000000 --- a/extensions/GUI/CCScrollView/CCSorting.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** - Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2010 Sangwoo Im - - 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 __CCSORTING_H__ -#define __CCSORTING_H__ - -#include "CCArray.h" -#include "extensions/ExtensionMacros.h" - -NS_CC_EXT_BEGIN - -class SortableObject -{ -public: - /** - * @js NA - * @lua NA - */ - virtual ~SortableObject() {} - virtual void setObjectID(long objectID) = 0; - virtual long getObjectID() = 0; -}; - -class ArrayForObjectSorting : public Array -{ -public: - ArrayForObjectSorting() : Array() {} - /*! - * Inserts a given object into array. - * - * Inserts a given object into array with key and value that are used in - * sorting. "value" must respond to message, compare:, which returns - * (NSComparisonResult). If it does not respond to the message, it is appended. - * If the compare message does not result NSComparisonResult, sorting behavior - * is not defined. It ignores duplicate entries and inserts next to it. - * - * @param object The object to be inserted. - */ - void insertSortedObject(SortableObject* object); - - /*! - * Removes an object in array. - * - * Removes an object with given key and value. If no object is found in array - * with the key and value, no action is taken. - * - * @param object The object to be removed. - */ - void removeSortedObject(SortableObject* object); - /*! - * Sets a new value of the key for the given object. - * - * In case where sorting value must be changed, this message must be sent to - * keep consistency of being sorted. If it is changed externally, it must be - * sorted completely again. - * - * @param tag The value to be set to. - * @param object The object which has the value. - */ - void setObjectID_ofSortedObject(unsigned int tag, SortableObject* object); - - SortableObject* objectWithObjectID(long tag); - /*! - * Returns an object with given key and value. - * - * Returns an object with given key and value. If no object is found, - * it returns nil. - * - * @param tag The value to locate object - * @return object found or nil. - */ - SortableObject* getObjectWithObjectID(unsigned int tag); - - /*! - * Returns an index of the object with given key and value. - * - * Returns the index of an object with given key and value. - * If no object is found, it returns an index at which the given object value - * would have been located. If object must be located at the end of array, - * it returns the length of the array, which is out of bound. - * - * @param obj The object - * @return index of the object - */ - long indexOfSortedObject(SortableObject* obj); - -}; - -NS_CC_EXT_END - -#endif /* __CCSORTING_H__ */ - diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index 6bf8bcd67f..16d53aa68a 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -26,12 +26,10 @@ #include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" -#include "CCMenu.h" -#include "CCSorting.h" -#include "CCLayer.h" NS_CC_EXT_BEGIN + TableView* TableView::create(TableViewDataSource* dataSource, Size size) { return TableView::create(dataSource, size, NULL); @@ -53,10 +51,6 @@ bool TableView::initWithViewSize(Size size, Node* container/* = NULL*/) { if (ScrollView::initWithViewSize(size,container)) { - _cellsUsed = new ArrayForObjectSorting(); - _cellsUsed->init(); - _cellsFreed = new ArrayForObjectSorting(); - _cellsFreed->init(); _indices = new std::set(); _vordering = VerticalFillOrder::BOTTOM_UP; this->setDirection(Direction::VERTICAL); @@ -70,11 +64,10 @@ bool TableView::initWithViewSize(Size size, Node* container/* = NULL*/) TableView::TableView() : _touchedCell(nullptr) , _indices(nullptr) -, _cellsUsed(nullptr) -, _cellsFreed(nullptr) , _dataSource(nullptr) , _tableViewDelegate(nullptr) , _oldDirection(Direction::NONE) +, _isUsedCellsDirty(false) { } @@ -82,15 +75,15 @@ TableView::TableView() TableView::~TableView() { CC_SAFE_DELETE(_indices); - CC_SAFE_RELEASE(_cellsUsed); - CC_SAFE_RELEASE(_cellsFreed); } void TableView::setVerticalFillOrder(VerticalFillOrder fillOrder) { - if (_vordering != fillOrder) { + if (_vordering != fillOrder) + { _vordering = fillOrder; - if (_cellsUsed->count() > 0) { + if (!_cellsUsed.empty()) + { this->reloadData(); } } @@ -104,28 +97,24 @@ TableView::VerticalFillOrder TableView::getVerticalFillOrder() void TableView::reloadData() { _oldDirection = Direction::NONE; - Object* pObj = NULL; - CCARRAY_FOREACH(_cellsUsed, pObj) - { - TableViewCell* cell = static_cast(pObj); + _cellsUsed.forEach([this](TableViewCell* cell){ if(_tableViewDelegate != NULL) { _tableViewDelegate->tableCellWillRecycle(this, cell); } - _cellsFreed->addObject(cell); + _cellsFreed.pushBack(cell); + cell->reset(); if (cell->getParent() == this->getContainer()) { this->getContainer()->removeChild(cell, true); } - } + }); _indices->clear(); - _cellsUsed->release(); - _cellsUsed = new ArrayForObjectSorting(); - _cellsUsed->init(); - + _cellsUsed.clear(); + this->_updateCellPositions(); this->_updateContentSize(); if (_dataSource->numberOfCellsInTableView(this) > 0) @@ -136,14 +125,18 @@ void TableView::reloadData() TableViewCell *TableView::cellAtIndex(long idx) { - TableViewCell *found = NULL; - if (_indices->find(idx) != _indices->end()) { - found = (TableViewCell *)_cellsUsed->objectWithObjectID(idx); + for (const auto& cell : _cellsUsed) + { + if (cell->getIdx() == idx) + { + return cell; + } + } } - return found; + return nullptr; } void TableView::updateCellAtIndex(long idx) @@ -181,22 +174,20 @@ void TableView::insertCellAtIndex(long idx) return; } - TableViewCell* cell = NULL; long newIdx = 0; - cell = static_cast(_cellsUsed->objectWithObjectID(idx)); + auto cell = cellAtIndex(idx); if (cell) { - newIdx = _cellsUsed->indexOfSortedObject(cell); - for (long i = newIdx; i<_cellsUsed->count(); i++) + newIdx = _cellsUsed.getIndex(cell); + // Move all cells behind the inserted position + for (long i = newIdx; i < _cellsUsed.size(); i++) { - cell = static_cast(_cellsUsed->getObjectAtIndex(i)); + cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx()+1, cell); } } - // [_indices shiftIndexesStartingAtIndex:idx by:1]; - //insert a new cell cell = _dataSource->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); @@ -227,17 +218,17 @@ void TableView::removeCellAtIndex(long idx) return; } - newIdx = _cellsUsed->indexOfSortedObject(cell); + newIdx = _cellsUsed.getIndex(cell); //remove first this->_moveCellOutOfSight(cell); _indices->erase(idx); this->_updateCellPositions(); -// [_indices shiftIndexesStartingAtIndex:idx+1 by:-1]; - for (unsigned int i=_cellsUsed->count()-1; i > newIdx; i--) + + for (int i = _cellsUsed.size()-1; i > newIdx; i--) { - cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(i); + cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx()-1, cell); } } @@ -246,12 +237,12 @@ TableViewCell *TableView::dequeueCell() { TableViewCell *cell; - if (_cellsFreed->count() == 0) { + if (_cellsFreed.empty()) { cell = NULL; } else { - cell = (TableViewCell*)_cellsFreed->getObjectAtIndex(0); + cell = _cellsFreed.at(0); cell->retain(); - _cellsFreed->removeObjectAtIndex(0); + _cellsFreed.remove(0); cell->autorelease(); } return cell; @@ -263,9 +254,9 @@ void TableView::_addCellIfNecessary(TableViewCell * cell) { this->getContainer()->addChild(cell); } - _cellsUsed->insertSortedObject(cell); + _cellsUsed.pushBack(cell); _indices->insert(cell->getIdx()); - // [_indices addIndex:cell.idx]; + _isUsedCellsDirty = true; } void TableView::_updateContentSize() @@ -405,12 +396,15 @@ void TableView::_moveCellOutOfSight(TableViewCell *cell) _tableViewDelegate->tableCellWillRecycle(this, cell); } - _cellsFreed->addObject(cell); - _cellsUsed->removeSortedObject(cell); + _cellsFreed.pushBack(cell); + _cellsUsed.removeObject(cell); + _isUsedCellsDirty = true; + _indices->erase(cell->getIdx()); - // [_indices removeIndex:cell.idx]; cell->reset(); - if (cell->getParent() == this->getContainer()) { + + if (cell->getParent() == this->getContainer()) + { this->getContainer()->removeChild(cell, true);; } } @@ -422,8 +416,9 @@ void TableView::_setIndexForCell(long index, TableViewCell *cell) cell->setIdx(index); } -void TableView::_updateCellPositions() { - int cellsCount = _dataSource->numberOfCellsInTableView(this); +void TableView::_updateCellPositions() +{ + long cellsCount = _dataSource->numberOfCellsInTableView(this); _vCellsPositions.resize(cellsCount + 1, 0.0); if (cellsCount > 0) @@ -451,19 +446,27 @@ void TableView::_updateCellPositions() { void TableView::scrollViewDidScroll(ScrollView* view) { - unsigned int uCountOfItems = _dataSource->numberOfCellsInTableView(this); - if (0 == uCountOfItems) + long countOfItems = _dataSource->numberOfCellsInTableView(this); + if (0 == countOfItems) { return; } + if (_isUsedCellsDirty) + { + _isUsedCellsDirty = false; + _cellsUsed.sort([](TableViewCell *a, TableViewCell *b) -> bool{ + return a->getIdx() < b->getIdx(); + }); + } + if(_tableViewDelegate != NULL) { _tableViewDelegate->scrollViewDidScroll(this); } long startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; Point offset = this->getContentOffset() * -1; - maxIdx = MAX(uCountOfItems-1, 0); + maxIdx = MAX(countOfItems-1, 0); if (_vordering == VerticalFillOrder::TOP_DOWN) { @@ -472,7 +475,7 @@ void TableView::scrollViewDidScroll(ScrollView* view) startIdx = this->_indexFromOffset(offset); if (startIdx == CC_INVALID_INDEX) { - startIdx = uCountOfItems - 1; + startIdx = countOfItems - 1; } if (_vordering == VerticalFillOrder::TOP_DOWN) @@ -488,7 +491,7 @@ void TableView::scrollViewDidScroll(ScrollView* view) endIdx = this->_indexFromOffset(offset); if (endIdx == CC_INVALID_INDEX) { - endIdx = uCountOfItems - 1; + endIdx = countOfItems - 1; } #if 0 // For Testing. @@ -511,17 +514,17 @@ void TableView::scrollViewDidScroll(ScrollView* view) log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); #endif - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - TableViewCell* cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(0); - + auto cell = _cellsUsed.at(0); idx = cell->getIdx(); - while(idx _moveCellOutOfSight(cell); - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(0); + cell = _cellsUsed.at(0); idx = cell->getIdx(); } else @@ -530,19 +533,18 @@ void TableView::scrollViewDidScroll(ScrollView* view) } } } - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - TableViewCell *cell = (TableViewCell*)_cellsUsed->getLastObject(); + auto cell = _cellsUsed.back(); idx = cell->getIdx(); while(idx <= maxIdx && idx > endIdx) { this->_moveCellOutOfSight(cell); - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - cell = (TableViewCell*)_cellsUsed->getLastObject(); + cell = _cellsUsed.back(); idx = cell->getIdx(); - } else { @@ -553,7 +555,6 @@ void TableView::scrollViewDidScroll(ScrollView* view) for (long i = startIdx; i <= endIdx; i++) { - //if ([_indices containsIndex:i]) if (_indices->find(i) != _indices->end()) { continue; @@ -586,15 +587,17 @@ void TableView::onTouchEnded(Touch *pTouch, Event *pEvent) bool TableView::onTouchBegan(Touch *pTouch, Event *pEvent) { - if (!this->isVisible()) { + if (!this->isVisible()) + { return false; } bool touchResult = ScrollView::onTouchBegan(pTouch, pEvent); - if(_touches.size() == 1) { - unsigned int index; - Point point; + if(_touches.size() == 1) + { + long index; + Point point; point = this->getContainer()->convertTouchToNodeSpace(pTouch); @@ -608,12 +611,15 @@ bool TableView::onTouchBegan(Touch *pTouch, Event *pEvent) _touchedCell = this->cellAtIndex(index); } - if (_touchedCell && _tableViewDelegate != NULL) { + if (_touchedCell && _tableViewDelegate != NULL) + { _tableViewDelegate->tableCellHighlight(this, _touchedCell); } } - else if(_touchedCell) { - if(_tableViewDelegate != NULL) { + else if (_touchedCell) + { + if(_tableViewDelegate != NULL) + { _tableViewDelegate->tableCellUnhighlight(this, _touchedCell); } @@ -627,8 +633,10 @@ void TableView::onTouchMoved(Touch *pTouch, Event *pEvent) { ScrollView::onTouchMoved(pTouch, pEvent); - if (_touchedCell && isTouchMoved()) { - if(_tableViewDelegate != NULL) { + if (_touchedCell && isTouchMoved()) + { + if(_tableViewDelegate != NULL) + { _tableViewDelegate->tableCellUnhighlight(this, _touchedCell); } @@ -640,8 +648,10 @@ void TableView::onTouchCancelled(Touch *pTouch, Event *pEvent) { ScrollView::onTouchCancelled(pTouch, pEvent); - if (_touchedCell) { - if(_tableViewDelegate != NULL) { + if (_touchedCell) + { + if(_tableViewDelegate != NULL) + { _tableViewDelegate->tableCellUnhighlight(this, _touchedCell); } diff --git a/extensions/GUI/CCScrollView/CCTableView.h b/extensions/GUI/CCScrollView/CCTableView.h index 34c7f05939..4201a2c1a4 100644 --- a/extensions/GUI/CCScrollView/CCTableView.h +++ b/extensions/GUI/CCScrollView/CCTableView.h @@ -35,7 +35,6 @@ NS_CC_EXT_BEGIN class TableView; -class ArrayForObjectSorting; /** * Sole purpose of this delegate is to single touch event in this version. @@ -270,6 +269,17 @@ public: virtual void onTouchCancelled(Touch *pTouch, Event *pEvent) override; protected: + long __indexFromOffset(Point offset); + long _indexFromOffset(Point offset); + Point __offsetFromIndex(long index); + Point _offsetFromIndex(long index); + + void _moveCellOutOfSight(TableViewCell *cell); + void _setIndexForCell(long index, TableViewCell *cell); + void _addCellIfNecessary(TableViewCell * cell); + + void _updateCellPositions(); + TableViewCell *_touchedCell; /** @@ -290,11 +300,11 @@ protected: /** * cells that are currently in the table */ - ArrayForObjectSorting* _cellsUsed; + Vector _cellsUsed; /** * free list of cells */ - ArrayForObjectSorting* _cellsFreed; + Vector _cellsFreed; /** * weak link to the data source object */ @@ -304,18 +314,10 @@ protected: */ TableViewDelegate* _tableViewDelegate; - Direction _oldDirection; + Direction _oldDirection; - long __indexFromOffset(Point offset); - long _indexFromOffset(Point offset); - Point __offsetFromIndex(long index); - Point _offsetFromIndex(long index); + bool _isUsedCellsDirty; - void _moveCellOutOfSight(TableViewCell *cell); - void _setIndexForCell(long index, TableViewCell *cell); - void _addCellIfNecessary(TableViewCell * cell); - - void _updateCellPositions(); public: void _updateContentSize(); diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 95fab98a29..96ab28d67d 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -26,15 +26,15 @@ #ifndef __CCTABLEVIEWCELL_H__ #define __CCTABLEVIEWCELL_H__ -#include "CCNode.h" -#include "CCSorting.h" +#include "cocos2d.h" +#include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN /** * Abstract class for SWTableView cell node */ -class TableViewCell: public Node, public SortableObject +class TableViewCell: public Node { public: TableViewCell() {} diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index aefb9fc978..ef4bdc7a5b 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -156,7 +156,7 @@ bool AssetsManager::checkUpdate() if (res != 0) { - ThreadHelper::runOnGLThread([&, this]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{ if (this->_delegate) this->_delegate->onError(ErrorCode::NETWORK); }); @@ -168,7 +168,7 @@ bool AssetsManager::checkUpdate() string recordedVersion = UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str()); if (recordedVersion == _version) { - ThreadHelper::runOnGLThread([&, this]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{ if (this->_delegate) this->_delegate->onError(ErrorCode::NO_NEW_VERSION); }); @@ -191,7 +191,7 @@ void AssetsManager::downloadAndUncompress() { if (! downLoad()) break; - ThreadHelper::runOnGLThread([&, this]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{ UserDefault::getInstance()->setStringForKey(this->keyOfDownloadedVersion().c_str(), this->_version.c_str()); UserDefault::getInstance()->flush(); @@ -201,14 +201,14 @@ void AssetsManager::downloadAndUncompress() // Uncompress zip file. if (! uncompress()) { - ThreadHelper::runOnGLThread([&, this]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{ if (this->_delegate) this->_delegate->onError(ErrorCode::UNCOMPRESS); }); break; } - ThreadHelper::runOnGLThread([&, this] { + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this] { // Record new version code. UserDefault::getInstance()->setStringForKey(this->keyOfVersion().c_str(), this->_version.c_str()); @@ -479,7 +479,7 @@ int assetsManagerProgressFunc(void *ptr, double totalToDownload, double nowDownl if (percent != tmp) { percent = tmp; - ThreadHelper::runOnGLThread([=]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]{ auto manager = static_cast(ptr); if (manager->_delegate) manager->_delegate->onProgress(percent); @@ -498,7 +498,7 @@ bool AssetsManager::downLoad() FILE *fp = fopen(outFileName.c_str(), "wb"); if (! fp) { - ThreadHelper::runOnGLThread([&, this]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{ if (this->_delegate) this->_delegate->onError(ErrorCode::CREATE_FILE); }); @@ -518,7 +518,7 @@ bool AssetsManager::downLoad() curl_easy_cleanup(_curl); if (res != 0) { - ThreadHelper::runOnGLThread([&, this]{ + Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{ if (this->_delegate) this->_delegate->onError(ErrorCode::NETWORK); }); diff --git a/extensions/proj.win32/libExtensions.vcxproj b/extensions/proj.win32/libExtensions.vcxproj index 7a3615643f..1e00952529 100644 --- a/extensions/proj.win32/libExtensions.vcxproj +++ b/extensions/proj.win32/libExtensions.vcxproj @@ -110,7 +110,6 @@ - @@ -138,7 +137,6 @@ - diff --git a/extensions/proj.win32/libExtensions.vcxproj.filters b/extensions/proj.win32/libExtensions.vcxproj.filters index d43ac6197c..fe37d0def2 100644 --- a/extensions/proj.win32/libExtensions.vcxproj.filters +++ b/extensions/proj.win32/libExtensions.vcxproj.filters @@ -24,9 +24,6 @@ GUI\CCScrollView - - GUI\CCScrollView - GUI\CCScrollView @@ -94,9 +91,6 @@ - - GUI\CCScrollView - GUI\CCScrollView diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 4fd63763d1..42c2d338c7 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -38,6 +38,7 @@ Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ Classes/ClippingNodeTest/ClippingNodeTest.cpp \ Classes/CocosDenshionTest/CocosDenshionTest.cpp \ Classes/ConfigurationTest/ConfigurationTest.cpp \ +Classes/ConsoleTest/ConsoleTest.cpp \ Classes/CurlTest/CurlTest.cpp \ Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ Classes/DataVisitorTest/DataVisitorTest.cpp \ diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index e5493d194c..8d205fd236 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -125,6 +125,7 @@ set(SAMPLE_SRC Classes/SpineTest/SpineTest.cpp Classes/DataVisitorTest/DataVisitorTest.cpp Classes/ConfigurationTest/ConfigurationTest.cpp + Classes/ConsoleTest/ConsoleTest.cpp Classes/controller.cpp Classes/testBasic.cpp Classes/AppDelegate.cpp diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 66e8e6edb1..cde2c87f2c 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -2137,14 +2137,13 @@ string ActionCardinalSpline::subtitle() */ PauseResumeActions::PauseResumeActions() -: _pausedTargets(NULL) { } PauseResumeActions::~PauseResumeActions() { - CC_SAFE_RELEASE(_pausedTargets); + } void PauseResumeActions::onEnter() @@ -2176,9 +2175,7 @@ void PauseResumeActions::pause(float dt) log("Pausing"); auto director = Director::getInstance(); - CC_SAFE_RELEASE(_pausedTargets); _pausedTargets = director->getActionManager()->pauseAllRunningActions(); - CC_SAFE_RETAIN(_pausedTargets); } void PauseResumeActions::resume(float dt) @@ -2186,6 +2183,7 @@ void PauseResumeActions::resume(float dt) log("Resuming"); auto director = Director::getInstance(); director->getActionManager()->resumeTargets(_pausedTargets); + _pausedTargets.clear(); } //------------------------------------------------------------------ diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h index 9a601b5212..0cb8ce0f20 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h @@ -553,7 +553,7 @@ public: void pause(float dt); void resume(float dt); private: - Set *_pausedTargets; + Vector _pausedTargets; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp index 6f5f7eb542..07c0aef320 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp @@ -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(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) diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp new file mode 100644 index 0000000000..a2e4ce76bd --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -0,0 +1,192 @@ +/**************************************************************************** + 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 "ConsoleTest.h" +#include "../testResource.h" + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) +#include +#else +#include +#endif + +//------------------------------------------------------------------ +// +// EaseSpriteDemo +// +//------------------------------------------------------------------ + +static int sceneIdx = -1; + +static std::function createFunctions[] = +{ + CL(ConsoleTCP), + CL(ConsoleCustomCommand), +}; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +Layer* nextConsoleTest() +{ + sceneIdx++; + sceneIdx = sceneIdx % MAX_LAYER; + + auto layer = (createFunctions[sceneIdx])(); + return layer; +} + +Layer* backConsoleTest() +{ + sceneIdx--; + int total = MAX_LAYER; + if( sceneIdx < 0 ) + sceneIdx += total; + + auto layer = (createFunctions[sceneIdx])(); + return layer; +} + +Layer* restartConsoleTest() +{ + auto layer = (createFunctions[sceneIdx])(); + return layer; +} + + +BaseTestConsole::BaseTestConsole() +{ +} + +BaseTestConsole::~BaseTestConsole(void) +{ +} + +std::string BaseTestConsole::title() +{ + return "No title"; +} + +void BaseTestConsole::onEnter() +{ + BaseTest::onEnter(); +} + +void BaseTestConsole::restartCallback(Object* sender) +{ + auto s = new ConsoleTestScene(); + s->addChild(restartConsoleTest()); + + Director::getInstance()->replaceScene(s); + s->release(); +} + +void BaseTestConsole::nextCallback(Object* sender) +{ + auto s = new ConsoleTestScene(); + s->addChild( nextConsoleTest() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +void BaseTestConsole::backCallback(Object* sender) +{ + auto s = new ConsoleTestScene(); + s->addChild( backConsoleTest() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +void ConsoleTestScene::runThisTest() +{ + auto layer = nextConsoleTest(); + addChild(layer); + + Director::getInstance()->replaceScene(this); +} + +//------------------------------------------------------------------ +// +// ConsoleTCP +// +//------------------------------------------------------------------ + +ConsoleTCP::ConsoleTCP() +{ + _console = Console::create(); + _console->retain(); +} + +ConsoleTCP::~ConsoleTCP() +{ + _console->release(); +} + +void ConsoleTCP::onEnter() +{ + BaseTestConsole::onEnter(); + _console->listenOnTCP(5678); +} + +std::string ConsoleTCP::title() +{ + return "Console TCP"; +} + +//------------------------------------------------------------------ +// +// ConsoleCustomCommand +// +//------------------------------------------------------------------ + +ConsoleCustomCommand::ConsoleCustomCommand() +{ + _console = Console::create(); + _console->retain(); + + static struct Console::Command commands[] = { + {"hello", [](int fd, const char* command) { + const char msg[] = "how are you?\nYou typed: "; + write(fd, msg, sizeof(msg)); + write(fd, command, strlen(command)); + write(fd, "\n",1); + }}, + }; + _console->setUserCommands(&commands[0],1); +} + +ConsoleCustomCommand::~ConsoleCustomCommand() +{ + _console->release(); +} + +void ConsoleCustomCommand::onEnter() +{ + BaseTestConsole::onEnter(); + _console->listenOnTCP(5678); +} + +std::string ConsoleCustomCommand::title() +{ + return "Console Custom Commands"; +} diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h new file mode 100644 index 0000000000..e1c2801628 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h @@ -0,0 +1,89 @@ +/**************************************************************************** + 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 _CONSOLE_TEST_H_ +#define _CONSOLE_TEST_H_ + +////----#include "cocos2d.h" +#include "../testBasic.h" +#include "../BaseTest.h" + +USING_NS_CC; + +class BaseTestConsole : public BaseTest +{ +public: + BaseTestConsole(); + ~BaseTestConsole(); + + virtual std::string title(); + virtual void onEnter(); + + void restartCallback(Object* sender); + void nextCallback(Object* sender); + void backCallback(Object* sender); +}; + +class ConsoleTCP : public BaseTestConsole +{ +public: + CREATE_FUNC(ConsoleTCP); + + void onEnter() override; + virtual std::string title() override; + +protected: + ConsoleTCP(); + virtual ~ConsoleTCP(); + + cocos2d::Console *_console; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ConsoleTCP); +}; + +class ConsoleCustomCommand : public BaseTestConsole +{ +public: + CREATE_FUNC(ConsoleCustomCommand); + + void onEnter() override; + virtual std::string title() override; + +protected: + ConsoleCustomCommand(); + virtual ~ConsoleCustomCommand(); + + cocos2d::Console *_console; +private: + CC_DISALLOW_COPY_AND_ASSIGN(ConsoleCustomCommand); +}; + +class ConsoleTestScene : public TestScene +{ +public: + virtual void runThisTest(); +}; + +#endif // _CONSOLE_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp index bc2737edf6..0433711a73 100644 --- a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -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(); } diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp index 0d10234a62..dace8cbd86 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp @@ -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(obj); + node->getChildren().forEach([enable](Node* child){ setEnableRecursiveCascading(child, enable); - } + }); } // LayerTestCascadingOpacityA diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index 5069f049b9..eb8aaa9448 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -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(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 ); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index bab33d56c3..4425ef3974 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -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(pObj); + unsigned int count = 0; + + getChildren().forEach([&count](Node* child){ + auto item = dynamic_cast(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(pObj); + + batchNode->getChildren().forEach([&count](Node* child){ + auto item = dynamic_cast(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(pObj); + + batchNode->getChildren().forEach([&count](Node* child){ + auto item = dynamic_cast(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(_batchNode->getChildren().at(1)); + _batchNode->reorderChild(system, system->getZOrder() - 1); } void ReorderParticleSystems::update(float dt) { - auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount); + auto atlas = static_cast(getChildByTag(kTagParticleCount)); unsigned int count = 0; auto batchNode = getChildByTag(2); - Object* pObj = NULL; - CCARRAY_FOREACH(batchNode->getChildren(), pObj) - { - auto item = dynamic_cast(pObj); - if (item != NULL) + + batchNode->getChildren().forEach([&count](Node* child){ + auto item = dynamic_cast(child); + if (item != nullptr) { count += item->getParticleCount(); } - } + }); char str[100] = {0}; sprintf(str, "%4d", count); atlas->setString(str); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp index bb54a16f24..ee81b7d36b 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp @@ -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); auto sprite = static_cast(o); @@ -321,15 +321,15 @@ void IterateSpriteSheetCArray::update(float dt) { // iterate using fast enumeration protocol auto children = batchNode->getChildren(); - Object* object = NULL; +// Object* object = NULL; CC_PROFILER_START(this->profilerName()); - CCARRAY_FOREACH(children, object) - { - auto sprite = static_cast(object); - sprite->setVisible(false); - } +//FIXME: James CCARRAY_FOREACH(children, object) +// { +// auto sprite = static_cast(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(*it); - auto sprite = static_cast(obj); + auto sprite = static_cast(*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& obj) { + std::for_each(std::begin(children), std::end(children), [](const RCPtr& obj) { static_cast( static_cast(obj) )->getPosition(); }); #else - std::for_each(std::begin(*children), std::end(*children), [](Object* obj) { - static_cast(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()); } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index ed291dc5ff..4865b81352 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -360,14 +360,14 @@ Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial materi bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapes(location); + auto arr = _scene->getPhysicsWorld()->getShapes(location); PhysicsBody* body = nullptr; - for (Object* obj : *arr) + for (auto& obj : arr) { - if ((dynamic_cast(obj)->getBody()->getTag() & DRAG_BODYS_TAG) != 0) + if ((obj->getBody()->getTag() & DRAG_BODYS_TAG) != 0) { - body = dynamic_cast(obj)->getBody(); + body = obj->getBody(); break; } } @@ -1017,9 +1017,8 @@ void PhysicsDemoPump::onEnter() void PhysicsDemoPump::update(float delta) { - for (auto obj : *_scene->getPhysicsWorld()->getAllBodies()) + for (const auto& body : _scene->getPhysicsWorld()->getAllBodies()) { - PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) { body->getNode()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 1da50ad4ca..e03e7d7943 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -195,14 +195,13 @@ std::string SchedulerPauseResume::subtitle() //------------------------------------------------------------------ SchedulerPauseResumeAll::SchedulerPauseResumeAll() -: _pausedTargets(NULL) { } SchedulerPauseResumeAll::~SchedulerPauseResumeAll() { - CC_SAFE_RELEASE(_pausedTargets); + } void SchedulerPauseResumeAll::onEnter() @@ -227,7 +226,7 @@ void SchedulerPauseResumeAll::update(float delta) void SchedulerPauseResumeAll::onExit() { - if(_pausedTargets != NULL) + if (!_pausedTargets.empty()) { Director::getInstance()->getScheduler()->resumeTargets(_pausedTargets); } @@ -249,9 +248,8 @@ void SchedulerPauseResumeAll::pause(float dt) log("Pausing"); auto director = Director::getInstance(); _pausedTargets = director->getScheduler()->pauseAllTargets(); - CC_SAFE_RETAIN(_pausedTargets); - unsigned int c = _pausedTargets->count(); + int c = _pausedTargets.size(); if (c > 2) { @@ -265,7 +263,7 @@ void SchedulerPauseResumeAll::resume(float dt) log("Resuming"); auto director = Director::getInstance(); director->getScheduler()->resumeTargets(_pausedTargets); - CC_SAFE_RELEASE_NULL(_pausedTargets); + _pausedTargets.clear(); } std::string SchedulerPauseResumeAll::title() @@ -285,14 +283,13 @@ std::string SchedulerPauseResumeAll::subtitle() //------------------------------------------------------------------ SchedulerPauseResumeAllUser::SchedulerPauseResumeAllUser() -: _pausedTargets(NULL) { } SchedulerPauseResumeAllUser::~SchedulerPauseResumeAllUser() { - CC_SAFE_RELEASE(_pausedTargets); + } void SchedulerPauseResumeAllUser::onEnter() @@ -314,7 +311,7 @@ void SchedulerPauseResumeAllUser::onEnter() void SchedulerPauseResumeAllUser::onExit() { - if(_pausedTargets != NULL) + if (!_pausedTargets.empty()) { Director::getInstance()->getScheduler()->resumeTargets(_pausedTargets); } @@ -336,7 +333,6 @@ void SchedulerPauseResumeAllUser::pause(float dt) log("Pausing"); auto director = Director::getInstance(); _pausedTargets = director->getScheduler()->pauseAllTargetsWithMinPriority(Scheduler::PRIORITY_NON_SYSTEM_MIN); - CC_SAFE_RETAIN(_pausedTargets); } void SchedulerPauseResumeAllUser::resume(float dt) @@ -344,7 +340,7 @@ void SchedulerPauseResumeAllUser::resume(float dt) log("Resuming"); auto director = Director::getInstance(); director->getScheduler()->resumeTargets(_pausedTargets); - CC_SAFE_RELEASE_NULL(_pausedTargets); + _pausedTargets.clear(); } std::string SchedulerPauseResumeAllUser::title() @@ -672,9 +668,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(c); auto node = static_cast(obj); diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h index 226136cb9c..b77e798a83 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h @@ -79,7 +79,7 @@ public: void pause(float dt); void resume(float dt); private: - Set* _pausedTargets; + Vector _pausedTargets; }; class SchedulerPauseResumeAllUser : public SchedulerTestLayer @@ -99,7 +99,7 @@ public: void pause(float dt); void resume(float dt); private: - Set* _pausedTargets; + Vector _pausedTargets; }; class SchedulerUnscheduleAll : public SchedulerTestLayer diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp index 77682f7012..f2a6008766 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp @@ -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(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() diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 8786750620..73c4962d89 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -406ff5d69f664d6e2b597c4f54a0db775087fb65 \ No newline at end of file +e4cdac1cca25440803dbf150fc336b61c44edb93 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h index f09a9091f5..130e8484fa 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h @@ -1,3 +1,27 @@ +/**************************************************************************** + 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 _SPRITE_TEST_H_ #define _SPRITE_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index d0ac2cb6b6..6a75f45470 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp @@ -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); diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 8b18e2de4c..b1d455c7ea 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -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(pObject); - - if(!child) - break; + auto& pChildrenArray = map->getChildren(); + pChildrenArray.forEach([](Node* obj){ + auto child = static_cast(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(pObject); - - if(!child) - break; + pChildrenArray.forEach([&child](Node* obj){ + child = static_cast(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(pObject); - - if(!child) - break; + children.forEach([&child](Node* node){ + child = static_cast(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(pObject); - - if(!child) - break; + SpriteBatchNode* child = nullptr; + map->getChildren().forEach([&child](Node* node){ + child = static_cast(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(pObject); - - if(!layer) - break; - + map->getChildren().forEach([&layer](Node* node){ + layer= static_cast(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(pObj); - - if(!dict) - break; - + ValueMap& dict = obj.asValueMap(); ////----CCLOG("object: %x", dict); } @@ -639,30 +603,23 @@ void TMXOrthoObjectsTest::draw() auto map = static_cast( 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(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(dict->objectForKey("y"))->getNumber(); - key = "width"; - int width = ((String*)dict->objectForKey(key))->intValue();//dynamic_cast(dict->objectForKey("width"))->getNumber(); - key = "height"; - int height = ((String*)dict->objectForKey(key))->intValue();//dynamic_cast(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* dict; - Dictionary* dict; - Object* pObj = NULL; - CCARRAY_FOREACH(objects, pObj) + for (auto& obj : objects) { - dict = static_cast(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(pObj); - - if(!dict) - break; - const char* key = "x"; - int x = static_cast(dict->objectForKey(key))->intValue(); - key = "y"; - int y = static_cast(dict->objectForKey(key))->intValue(); - key = "width"; - int width = static_cast(dict->objectForKey(key))->intValue(); - key = "height"; - int height = static_cast(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(pObj); + map->getChildren().forEach([](Node* node){ + auto child = static_cast(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(pObj); + map->getChildren().forEach([](Node* node){ + auto child = static_cast(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(pObj); + map->getChildren().forEach([](Node* node){ + auto child = static_cast(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(pObject); - CC_BREAK_IF(!node); + map->getChildren().forEach([](Node* child){ + auto node = static_cast(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(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); diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index b767878e9e..f6236eda73 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -36,6 +36,7 @@ struct { #endif { "CocosDenshionTest", []() { return new CocosDenshionTestScene(); } }, { "ConfigurationTest", []() { return new ConfigurationTestScene(); } }, + { "ConsoleTest", []() { return new ConsoleTestScene(); } }, #if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) #if (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) #if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) diff --git a/samples/Cpp/TestCpp/Classes/tests.h b/samples/Cpp/TestCpp/Classes/tests.h index d613fe542e..ce4ff9cb97 100644 --- a/samples/Cpp/TestCpp/Classes/tests.h +++ b/samples/Cpp/TestCpp/Classes/tests.h @@ -1,6 +1,7 @@ #ifndef _TESTS_H_ #define _TESTS_H_ +#include "ConsoleTest/ConsoleTest.h" #include "NewEventDispatcherTest/NewEventDispatcherTest.h" #include "ActionsTest/ActionsTest.h" #include "TransitionsTest/TransitionsTest.h" diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index b1bc1a9b1b..cfd32fc8e8 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -70,7 +70,7 @@ Disabled ..\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) - 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) + 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) EnableFastChecks MultiThreadedDebugDLL @@ -103,7 +103,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ MaxSpeed true ..\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) - 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) + WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index b609c7cc43..89f66668a3 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -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 testjavascript # 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