From 2f1dffe46b0867f9907e6c6543e6e94f7b36152d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 26 Nov 2013 16:58:14 -0800 Subject: [PATCH 001/107] Adds performFunctionInCocos2dThread ... in Scheduler --- cocos/2d/CCScheduler.cpp | 70 +++++++++++++++++++++++++++++----------- cocos/2d/CCScheduler.h | 18 +++++++++-- 2 files changed, 67 insertions(+), 21 deletions(-) diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 59c6cdce65..69172607a9 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -258,7 +258,8 @@ Scheduler::Scheduler(void) , _updateHashLocked(false) , _scriptHandlerEntries(nullptr) { - + // I don't expect to have more than 30 functions to all per frame + _functionsToPerform.reserve(30); } Scheduler::~Scheduler(void) @@ -825,6 +826,15 @@ void Scheduler::resumeTargets(Set* targetsToResume) } } +void Scheduler::performFunctionInCocosThread(const std::function &function) +{ + _performMutex.lock(); + + _functionsToPerform.push_back(function); + + _performMutex.unlock(); +} + // main loop void Scheduler::update(float dt) { @@ -835,6 +845,10 @@ void Scheduler::update(float dt) dt *= _timeScale; } + // + // Selector callbacks + // + // Iterate over all the Updates' selectors tListEntry *entry, *tmp; @@ -904,23 +918,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 +947,43 @@ void Scheduler::update(float dt) } _updateHashLocked = false; - _currentTarget = nullptr; + + // + // Script callbacks + // + + // Iterate over all the script callbacks + if (_scriptHandlerEntries) + { + for (auto 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); + } + } + } + + // + // 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.size() > 0 ) { + _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..cfda2732d7 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -27,6 +27,10 @@ THE SOFTWARE. #ifndef __CCSCHEDULER_H__ #define __CCSCHEDULER_H__ +#include +#include +#include + #include "CCObject.h" #include "uthash.h" @@ -257,7 +261,13 @@ public: */ void resumeTargets(Set* 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 +276,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; // @@ -284,6 +294,10 @@ protected: // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. bool _updateHashLocked; Array* _scriptHandlerEntries; + + // Used for "perform Function" + std::vector> _functionsToPerform; + std::mutex _performMutex; }; // end of global group From 534fd9600e0c4b6c6b98a0b7406588415056dcd0 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 26 Nov 2013 18:58:36 -0800 Subject: [PATCH 002/107] Adds CCConsole. it doesn't work... just the skeleton --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/CCConsole.cpp | 80 +++++++++++++++++++ cocos/CCConsole.h | 58 ++++++++++++++ 3 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 cocos/CCConsole.cpp create mode 100644 cocos/CCConsole.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 507d392456..bb81649399 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -0d9ce76f7e63d75718c38b1137b2580e19d0db76 \ No newline at end of file +72ee3df00e7f690c7df7148ddc620aeaf8557041 \ No newline at end of file diff --git a/cocos/CCConsole.cpp b/cocos/CCConsole.cpp new file mode 100644 index 0000000000..5442b8ea6f --- /dev/null +++ b/cocos/CCConsole.cpp @@ -0,0 +1,80 @@ +// +// CCConsole.cpp +// cocos2d_libs +// +// Created by Ricardo Quesada on 11/26/13. +// +// + +#include "CCConsole.h" + +#include +#include +#include + +#include "CCDirector.h" + +using namespace cocos2d; + +Console* Console::createWithFileDescriptor(int fd) +{ + auto ret = new Console; + + ret->setFileDescriptor(fd); + ret->autorelease(); + return ret; +} + + +Console::Console() +: _fd(-1) +, _running(false) +, _endThread(false) +{ + _scheduler = Director::getInstance()->getScheduler(); +} + +Console::~Console() +{ +} + +void Console::run() +{ + CCASSERT(!_running, "already running"); + _thread = std::thread( std::bind( &Console::loop, this) ); +} + +void Console::cancel() +{ + CCASSERT(_running, "must be running"); + _endThread = true; + _thread.join(); +} + + +void Console::loop() +{ + fd_set read_set; + + FD_ZERO(&read_set); + FD_SET(_fd, &read_set); + + while(!_endThread) { + + int nready = select( _fd+1, &read_set, NULL, NULL, NULL ); + + /* error ?*/ + if( nready == -1 ) { + if(errno != EINTR) { + log("Abnormal error in select()\n"); + } + continue; + + } else if( nready == 0 ) { + /* timeout ? */ + continue; + } else { + + } + } +} diff --git a/cocos/CCConsole.h b/cocos/CCConsole.h new file mode 100644 index 0000000000..18d13f7252 --- /dev/null +++ b/cocos/CCConsole.h @@ -0,0 +1,58 @@ +// +// CCConsole.h +// cocos2d_libs +// +// Created by Ricardo Quesada on 11/26/13. +// +// + +#ifndef __cocos2d_libs__CCConsole__ +#define __cocos2d_libs__CCConsole__ + +#include + +#include "ccMacros.h" +#include "base/CCObject.h" + + +NS_CC_BEGIN + +class Scheduler; + +class CC_DLL Console : public Object +{ + +public: + static Console* createWithFileDescriptor(int fd); + + void run(); + void cancel(); + + int getFileDescriptor() const { return _fd; } + void setFileDescriptor(int fd) { _fd = fd; } + + +protected: + Console(); + virtual ~Console(); + + + void loop(); + + // weak ref + Scheduler *_scheduler; + + // file descriptor: socket, console, etc. + int _fd; + std::thread _thread; + bool _running; + bool _endThread; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Console); +}; + + +NS_CC_END + +#endif /* defined(__cocos2d_libs__CCConsole__) */ From eb834bce7f62b4aa60688b32213b16190f37696f Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 2 Dec 2013 09:57:16 -0800 Subject: [PATCH 003/107] Adds readline --- cocos/CCConsole.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/cocos/CCConsole.cpp b/cocos/CCConsole.cpp index 5442b8ea6f..63e2d17b6f 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/CCConsole.cpp @@ -52,6 +52,31 @@ void Console::cancel() } +ssize_t net_readline( int fd, void *vptr, size_t maxlen ) +{ + ssize_t n, rc; + char c, *ptr; + + ptr = (char*)vptr ; + + for( n=1; n Date: Tue, 3 Dec 2013 18:46:54 -0800 Subject: [PATCH 004/107] Console is working! --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/cocos2d.h | 1 + cocos/CCConsole.cpp | 162 ++++++++++++++-- cocos/CCConsole.h | 18 +- .../Classes/ConsoleTest/ConsoleTest.cpp | 178 ++++++++++++++++++ .../TestCpp/Classes/ConsoleTest/ConsoleTest.h | 89 +++++++++ samples/Cpp/TestCpp/Classes/controller.cpp | 3 + samples/Cpp/TestCpp/Classes/tests.h | 1 + 8 files changed, 429 insertions(+), 25 deletions(-) create mode 100644 samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp create mode 100644 samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 8f264968c7..5ab0cf7659 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 +edaf6572f44b700ec70e3122e91b48d728ebce7a \ No newline at end of file diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index b25bb7bee8..c33dddf82d 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -199,6 +199,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/CCConsole.cpp b/cocos/CCConsole.cpp index 63e2d17b6f..42ba70f8c4 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/CCConsole.cpp @@ -8,26 +8,35 @@ #include "CCConsole.h" -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include "CCDirector.h" +#include "CCScheduler.h" using namespace cocos2d; -Console* Console::createWithFileDescriptor(int fd) +Console* Console::create() { auto ret = new Console; - ret->setFileDescriptor(fd); ret->autorelease(); return ret; } Console::Console() -: _fd(-1) +: _listenfd(-1) , _running(false) , _endThread(false) { @@ -38,26 +47,107 @@ Console::~Console() { } -void Console::run() +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",(unsigned int) port ); + serv[sizeof(serv)-1]=0; + + bzero(&hints, sizeof(struct addrinfo)); + hints.ai_flags = AI_PASSIVE; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + 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, &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); + + freeaddrinfo(ressave); + + CCLOG("Console: listening on port %d", port); + return listenOnFileDescriptor(listenfd); +} + +bool Console::listenOnStdin() +{ + return listenOnFileDescriptor(STDIN_FILENO); +} + +bool Console::listenOnFileDescriptor(int fd) { CCASSERT(!_running, "already running"); + _running = true; + _listenfd = fd; _thread = std::thread( std::bind( &Console::loop, this) ); + + return true; } void Console::cancel() { - CCASSERT(_running, "must be running"); - _endThread = true; - _thread.join(); + if( _running ) { + _endThread = true; + if( _listenfd ) + write(_listenfd,"\n",1); + + _thread.join(); + } } - -ssize_t net_readline( int fd, void *vptr, size_t maxlen ) +void Console::parseToken() { + struct _tokens { + const char * func_name; + std::function callback; + } tokens[] { + { "fps on", []() { Director::getInstance()->setDisplayStats(true); } }, + { "fps off", []() { Director::getInstance()->setDisplayStats(false); } }, + }; + + const int max = sizeof(tokens) / sizeof(tokens[0]); + + Scheduler *sched = Director::getInstance()->getScheduler(); + for( int i=0; i < max; ++i) { + if( strncmp(_buffer, tokens[i].func_name,strlen(tokens[i].func_name)) == 0 ) + sched->performFunctionInCocosThread( tokens[i].callback ); + } + +} + +ssize_t Console::readline(int fd) +{ + int maxlen = 512; ssize_t n, rc; char c, *ptr; - ptr = (char*)vptr ; + ptr = _buffer; for( n=1; n _max_fd) + _max_fd = fd; + } + + if(--nready <= 0) + continue; + } + + /* input from client */ + for(fd=0; fd <= _max_fd; fd++) { + if( fd != _listenfd && FD_ISSET(fd,©_set) ) { + readline(fd); + parseToken(); + log("read: %s", _buffer); + if(--nready <= 0) + break; + } + } } } diff --git a/cocos/CCConsole.h b/cocos/CCConsole.h index 18d13f7252..acf674f6f1 100644 --- a/cocos/CCConsole.h +++ b/cocos/CCConsole.h @@ -23,31 +23,39 @@ class CC_DLL Console : public Object { public: - static Console* createWithFileDescriptor(int fd); + static Console* create(); + + bool listenOnTCP(int port); + bool listenOnStdin(); + bool listenOnFileDescriptor(int fd); - void run(); void cancel(); - int getFileDescriptor() const { return _fd; } - void setFileDescriptor(int fd) { _fd = fd; } + int getFileDescriptor() const { return _listenfd; } + void setFileDescriptor(int fd) { _listenfd = fd; } protected: Console(); virtual ~Console(); + ssize_t readline(int fd); void loop(); + void parseToken(); // weak ref Scheduler *_scheduler; // file descriptor: socket, console, etc. - int _fd; + int _listenfd; + int _max_fd; std::thread _thread; bool _running; bool _endThread; + char _buffer[512]; + private: CC_DISALLOW_COPY_AND_ASSIGN(Console); }; diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp new file mode 100644 index 0000000000..ec20c15d52 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -0,0 +1,178 @@ +/**************************************************************************** + 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" + +//------------------------------------------------------------------ +// +// EaseSpriteDemo +// +//------------------------------------------------------------------ + +static int sceneIdx = -1; + +static std::function createFunctions[] = +{ + CL(ConsoleTCP), + CL(ConsoleStdin), +}; + +#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->cancel(); + _console->release(); +} + +void ConsoleTCP::onEnter() +{ + BaseTestConsole::onEnter(); + _console->listenOnTCP(5678); +} + +std::string ConsoleTCP::title() +{ + return "Console TCP"; +} + +//------------------------------------------------------------------ +// +// ConsoleStdin +// +//------------------------------------------------------------------ + +ConsoleStdin::ConsoleStdin() +{ + _console = Console::create(); + _console->retain(); +} + +ConsoleStdin::~ConsoleStdin() +{ + _console->cancel(); + _console->release(); +} + +void ConsoleStdin::onEnter() +{ + BaseTestConsole::onEnter(); + _console->listenOnStdin(); +} + +std::string ConsoleStdin::title() +{ + return "Console STDIN"; +} diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h new file mode 100644 index 0000000000..e10bd12482 --- /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 ConsoleStdin : public BaseTestConsole +{ +public: + CREATE_FUNC(ConsoleStdin); + + void onEnter() override; + virtual std::string title() override; + +protected: + ConsoleStdin(); + virtual ~ConsoleStdin(); + + cocos2d::Console *_console; +private: + CC_DISALLOW_COPY_AND_ASSIGN(ConsoleStdin); +}; + +class ConsoleTestScene : public TestScene +{ +public: + virtual void runThisTest(); +}; + +#endif // _CONSOLE_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index b767878e9e..8cebe13e43 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -15,6 +15,8 @@ struct { std::function callback; } g_aTestNames[] = { + { "ConsoleTest", []() { return new ConsoleTestScene(); } }, + // // TESTS MUST BE ORDERED ALPHABETICALLY // violators will be prosecuted @@ -36,6 +38,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" From 98779b0a9fbfc868a3f318585e320fab2f57f17c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 4 Dec 2013 14:36:32 +0800 Subject: [PATCH 005/107] issue #2771: move CC_USE_PHYSICS from project definition to ccConfig.h --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- .../cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/ccConfig.h | 5 +++++ cocos/2d/cocos2d.vcxproj | 4 ++-- cocos/physics/CCPhysicsBody.h | 1 + cocos/physics/CCPhysicsContact.h | 1 + cocos/physics/CCPhysicsJoint.h | 1 + cocos/physics/CCPhysicsShape.h | 1 + cocos/physics/CCPhysicsWorld.h | 1 + cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp | 2 +- cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h | 1 + cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp | 2 +- cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h | 1 + cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h | 1 + cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp | 2 +- cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h | 1 + cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp | 2 +- cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h | 3 ++- cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 2 +- cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h | 1 + samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 4 ++-- 21 files changed, 28 insertions(+), 12 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 7240f25838..21eb70aa3b 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 +70579540615cf1d2f1ed86cc4789e1424144c616 \ 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..322bb27750 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 +d9ca56584f41cdc53df610c01b375de066b4844b \ No newline at end of file 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/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 72b52b3b97..62ea897c70 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 diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index f6d2e91f71..bc72aff57b 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 24eb0f4c69..5a05b02497 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" 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.h b/cocos/physics/CCPhysicsShape.h index b97bb3cba6..a72f155765 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" diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 389cde4f2c..d1433d97fc 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -25,6 +25,7 @@ #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ +#include "ccConfig.h" #ifdef CC_USE_PHYSICS #include 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/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 From 52af153a81a4d36329de0655906bde784dfd681a Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 16:58:33 +0800 Subject: [PATCH 006/107] =?UTF-8?q?issue=20#2790:=20Commit=20CCVector.h=20?= =?UTF-8?q?from=20Riq=E2=80=99s=20repo(https://github.com/ricardoquesada/c?= =?UTF-8?q?ocos2d-x/blob/template=5Fvector/cocos2dx/cocoa/CCVector.h).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCVector.h | 272 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 cocos/base/CCVector.h diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h new file mode 100644 index 0000000000..8a1efa5622 --- /dev/null +++ b/cocos/base/CCVector.h @@ -0,0 +1,272 @@ +/**************************************************************************** +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 +#include +#include "ccMacros.h" +//#include "platform/CCFileUtils.h" + +NS_CC_BEGIN + +template +class CC_DLL Vector +{ +public: + /** creates an emptry Vector */ + Vector(int capacity=7) + : _data() + { + init(capacity); + } + + virtual ~Vector() { + for( auto it=std::begin(_data); it != std::end(_data); ++it ) + (*it)->release(); + } + + /** Initializes an array with capacity */ + bool init(int capacity) + { + _data.reserve(capacity); + return true; + } + + // Querying an Array + + /** Returns element count of the array */ + int count() const + { + return _data.size(); + } + + /** Returns capacity of the array */ + int capacity() const + { + return _data.capacity(); + } + + /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ + int getIndexOfObject(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 getObjectAtIndex(int index) const + { + CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); + return _data[index]; + } + + /** Returns the last element of the array */ + T getLastObject() const + { + return _data.back(); + } + + /** Returns a random element */ + T getRandomObject() const + { + return *_data.begin(); + } + + /** Returns a Boolean value that indicates whether object is present in array. */ + bool containsObject(T object) const + { + return( std::find(_data.begin(), _data.end(), object) != _data.end() ); + } + + /** returns true if the the arrays are equal */ + bool isEqualToArray(const Vector &otherArray) + { + for (int i = 0; i< this->count(); i++) + { + if (!this->getObjectAtIndex(i)->isEqual(otherArray.getObjectAtIndex(i))) + { + return false; + } + } + return true; + } + + // Adding Objects + + /** Add a certain object */ + void addObject(T object) + { + _data.push_back( object ); + object->retain(); + } + + /** Add all elements of an existing array */ + void addObjectsFromArray(T otherArray) + { + for( auto it = std::begin(otherArray); it != std::end(otherArray); ++it ) { + _data.push_back( *it ); + (*it)->retain(); + } + } + + /** Insert a certain object at a certain index */ + void insertObject(T object, int index) + { + _data.insert( std::next( std::begin(_data, index), object ) ); + object->retain(); + } + + /** sets a certain object at a certain index */ + void setObject(T object, int index) + { + _data[index] = object; + object->retain(); + } + /** sets a certain object at a certain index without retaining. Use it with caution */ + void fastSetObject(T object, int index) + { + _data[index] = object; + } + + // Removing Objects + + /** Remove last object */ + void removeLastObject() + { + CCASSERT(_data.size(), "no objects added"); + auto last = _data.back(); + _data.pop_back(); + last->release(); + } + + /** Remove a certain object */ + void removeObject(T object) + { + _data.erase( std::remove( _data.begin(), _data.end(), object ) ); + object->release(); + } + + /** Removes an element with a certain index */ + void removeObjectAtIndex(int index) + { + auto it = std::next( begin(), index ); + _data.erase(it); + (*it)->release(); + } + + /** Removes all objects */ + void removeAllObjects() + { + for( auto it = std::begin(_data); it != std::end(_data); ++it ) { + _data.erase(it); + (*it)->release(); + } + } + + /** Fast way to remove a certain object */ + void fastRemoveObject(T object) { + removeObjectAtIndex(index); + } + + /** Fast way to remove an element with a certain index */ + void fastRemoveObjectAtIndex(int index) + { + removeObjectAtIndex(index); + } + + // Rearranging Content + + /** Swap two elements */ + void swapObjects(T object1, T object2) + { + int idx1 = getIndexOfObject(object1); + int idx2 = getIndexOfObject(object2); + + CCASSERT(idx1>=0 && idx2>=2, "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 < count() && index2 >= 0 && index2 < count(), "Invalid indices"); + + std::swap( _data[index1], _data[index2] ); + } + + /** Replace object at index with another object. */ + void replaceObjectAtIndex(int index, T object) + { + if( object != _data[index] ) { + object->retain(); + _data[index]->release(); + _data[index] = object; + } + } + + /** reverses the array */ + void reverseObjects() + { + std::reverse( std::begin(_data), std::end(_data) ); + } + + /** Shrinks the array so the memory footprint corresponds with the number of items */ + void reduceMemoryFootprint() + { + _data.shrink_to_fit(); + } + + // ------------------------------------------ + // Iterators + // ------------------------------------------ + typedef typename std::vector::iterator iterator; + typedef typename std::vector::const_iterator const_iterator; + + iterator begin() { return _data.begin(); } + iterator end() { return _data.end(); } + const_iterator cbegin() { return _data.cbegin(); } + const_iterator cend() { return _data.cend(); } + +protected: + std::vector _data; + +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CCVECTOR_H__ From 80004548c811377347bea99cf5540407092df48b Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 28 Nov 2013 09:30:40 +0800 Subject: [PATCH 007/107] =?UTF-8?q?issue=20#2790:=20Adds=20CCVector.h=20to?= =?UTF-8?q?=20Xcode=20project.=20int=20=E2=80=94>=20long?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/base/CCVector.h | 35 +++++++++---------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 7240f25838..f3eb0ecbbc 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 +0934e5b3cb72bb084c73b2cdc7dc70a5df006b44 \ No newline at end of file diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 8a1efa5622..cd75c94a26 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -28,7 +28,6 @@ THE SOFTWARE. #include #include #include "ccMacros.h" -//#include "platform/CCFileUtils.h" NS_CC_BEGIN @@ -37,7 +36,7 @@ class CC_DLL Vector { public: /** creates an emptry Vector */ - Vector(int capacity=7) + Vector(long capacity=7) : _data() { init(capacity); @@ -49,7 +48,7 @@ public: } /** Initializes an array with capacity */ - bool init(int capacity) + bool init(long capacity) { _data.reserve(capacity); return true; @@ -58,21 +57,21 @@ public: // Querying an Array /** Returns element count of the array */ - int count() const + long count() const { return _data.size(); } /** Returns capacity of the array */ - int capacity() const + long capacity() const { return _data.capacity(); } /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ - int getIndexOfObject(T object) const + long getIndexOfObject(T object) const { - int i=0; + long i=0; for (auto it = _data.begin(); it != _data.end(); ++it, ++i) { if (*it == object) @@ -85,7 +84,7 @@ public: } /** Returns an element with a certain index */ - T getObjectAtIndex(int index) const + T getObjectAtIndex(long index) const { CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); return _data[index]; @@ -112,7 +111,7 @@ public: /** returns true if the the arrays are equal */ bool isEqualToArray(const Vector &otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray.getObjectAtIndex(i))) { @@ -141,20 +140,20 @@ public: } /** Insert a certain object at a certain index */ - void insertObject(T object, int index) + void insertObject(T object, long index) { _data.insert( std::next( std::begin(_data, index), object ) ); object->retain(); } /** sets a certain object at a certain index */ - void setObject(T object, int index) + void setObject(T object, long index) { _data[index] = object; object->retain(); } /** sets a certain object at a certain index without retaining. Use it with caution */ - void fastSetObject(T object, int index) + void fastSetObject(T object, long index) { _data[index] = object; } @@ -178,7 +177,7 @@ public: } /** Removes an element with a certain index */ - void removeObjectAtIndex(int index) + void removeObjectAtIndex(long index) { auto it = std::next( begin(), index ); _data.erase(it); @@ -200,7 +199,7 @@ public: } /** Fast way to remove an element with a certain index */ - void fastRemoveObjectAtIndex(int index) + void fastRemoveObjectAtIndex(long index) { removeObjectAtIndex(index); } @@ -210,8 +209,8 @@ public: /** Swap two elements */ void swapObjects(T object1, T object2) { - int idx1 = getIndexOfObject(object1); - int idx2 = getIndexOfObject(object2); + long idx1 = getIndexOfObject(object1); + long idx2 = getIndexOfObject(object2); CCASSERT(idx1>=0 && idx2>=2, "invalid object index"); @@ -219,7 +218,7 @@ public: } /** Swap two elements with certain indexes */ - void swap(int index1, int index2) + void swap(long index1, long index2) { CCASSERT(index1 >=0 && index1 < count() && index2 >= 0 && index2 < count(), "Invalid indices"); @@ -227,7 +226,7 @@ public: } /** Replace object at index with another object. */ - void replaceObjectAtIndex(int index, T object) + void replaceObjectAtIndex(long index, T object) { if( object != _data[index] ) { object->retain(); From c152652c5b5fa6a7def43ec1b62d2b76bd049489 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 28 Nov 2013 11:04:39 +0800 Subject: [PATCH 008/107] issue #2790: Vector for Sequence::create(arr) and Spawn::create(arr). --- cocos/2d/CCActionInterval.cpp | 20 +++---- cocos/2d/CCActionInterval.h | 5 +- cocos/2d/cocos2d.h | 1 + cocos/base/CCVector.h | 54 +++++++++++++++---- .../cocosbuilder/CCBAnimationManager.cpp | 32 +++++------ .../cocostudio/CCActionNode.cpp | 11 ++-- 6 files changed, 81 insertions(+), 42 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index a2ae6b7824..655922be15 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(); + long count = arrayOfActions.count(); CC_BREAK_IF(count == 0); - FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); + auto prev = arrayOfActions[0]; if (count > 1) { for (long i = 1; i < count; ++i) { - prev = createWithTwoActions(prev, static_cast(arrayOfActions->getObjectAtIndex(i))); + prev = createWithTwoActions(prev, arrayOfActions[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(); + long count = arrayOfActions.count(); CC_BREAK_IF(count == 0); - FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); + auto prev = arrayOfActions[0]; if (count > 1) { - for (int i = 1; i < arrayOfActions->count(); ++i) + for (int i = 1; i < arrayOfActions.count(); ++i) { - prev = createWithTwoActions(prev, static_cast(arrayOfActions->getObjectAtIndex(i))); + prev = createWithTwoActions(prev, arrayOfActions[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; 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/cocos2d.h b/cocos/2d/cocos2d.h index b25bb7bee8..fa194c7fe0 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -60,6 +60,7 @@ THE SOFTWARE. #include "CCDictionary.h" #include "CCObject.h" #include "CCArray.h" +#include "CCVector.h" #include "CCGeometry.h" #include "CCSet.h" #include "CCAutoreleasePool.h" diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index cd75c94a26..8ffadcb4c5 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -39,21 +39,50 @@ public: Vector(long capacity=7) : _data() { + CCLOG("In the constructor of Vector."); init(capacity); } virtual ~Vector() { - for( auto it=std::begin(_data); it != std::end(_data); ++it ) - (*it)->release(); + CCLOG("In the destructor of Vector."); + removeAllObjects(); } + Vector(const Vector& other) + { + CCLOG("In the copy constructor!"); + copy(other); + } + + const Vector& operator=(const Vector& other) + { + CCLOG("In the assignment operator!"); + copy(other); + return *this; + } + + T operator[](long index) const + { + return getObjectAtIndex(index); + } + /** Initializes an array with capacity */ bool init(long capacity) { _data.reserve(capacity); return true; } - + + void copy(const Vector& other) + { + if (this == &other) + return; + + removeAllObjects(); + init(other.count()); + addObjectsFromArray(other); + } + // Querying an Array /** Returns element count of the array */ @@ -131,9 +160,9 @@ public: } /** Add all elements of an existing array */ - void addObjectsFromArray(T otherArray) + void addObjectsFromArray(const Vector& otherArray) { - for( auto it = std::begin(otherArray); it != std::end(otherArray); ++it ) { + for( auto it = otherArray.begin(); it != otherArray.end(); ++it ) { _data.push_back( *it ); (*it)->retain(); } @@ -180,17 +209,17 @@ public: void removeObjectAtIndex(long index) { auto it = std::next( begin(), index ); - _data.erase(it); (*it)->release(); + _data.erase(it); } /** Removes all objects */ void removeAllObjects() { for( auto it = std::begin(_data); it != std::end(_data); ++it ) { - _data.erase(it); (*it)->release(); } + _data.clear(); } /** Fast way to remove a certain object */ @@ -254,9 +283,16 @@ public: typedef typename std::vector::const_iterator const_iterator; iterator begin() { return _data.begin(); } + const_iterator begin() const { return _data.begin(); } + iterator end() { return _data.end(); } - const_iterator cbegin() { return _data.cbegin(); } - const_iterator cend() { return _data.cend(); } + const_iterator end() const { return _data.end(); } + + iterator cbegin() { return _data.cbegin(); } + const_iterator cbegin() const { return _data.cbegin(); } + + iterator cend() { return _data.cend(); } + const_iterator cend() const { return _data.cend(); } protected: std::vector _data; diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index df8721de0d..5fa169014f 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp @@ -620,7 +620,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann float lastKeyframeTime = 0; - Array *actions = Array::create(); + Vector actions; Array *keyframes = channel->getKeyframes(); long numKeyframes = keyframes->count(); @@ -631,7 +631,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime; lastKeyframeTime = keyframe->getTime(); if(timeSinceLastKeyframe > 0) { - actions->addObject(DelayTime::create(timeSinceLastKeyframe)); + actions.addObject(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.addObject(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.addObject(callback); } } else @@ -690,7 +690,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann } } } - if(actions->count() < 1) return NULL; + if(actions.count() < 1) return NULL; return (Object *) Sequence::create(actions); } @@ -699,9 +699,9 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) float lastKeyframeTime = 0; - Array *actions = Array::create(); + Vector actions; Array *keyframes = channel->getKeyframes(); - int numKeyframes = keyframes->count(); + long numKeyframes = keyframes->count(); for (int i = 0; i < numKeyframes; ++i) { @@ -709,7 +709,7 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime; lastKeyframeTime = keyframe->getTime(); if(timeSinceLastKeyframe > 0) { - actions->addObject(DelayTime::create(timeSinceLastKeyframe)); + actions.addObject(DelayTime::create(timeSinceLastKeyframe)); } stringstream ss (stringstream::in | stringstream::out); @@ -729,12 +729,12 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) ss >> gain; ss.flush(); - actions->addObject(CCBSoundEffect::actionWithSoundFile(soundFile, pitch, pan, gain)); + actions.addObject(CCBSoundEffect::actionWithSoundFile(soundFile, pitch, pan, gain)); } - if(actions->count() < 1) return NULL; + if(actions.count() < 1) return NULL; - return (Object *) Sequence::create(actions); + return Sequence::create(actions); } @@ -742,19 +742,19 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration) { Array *keyframes = pSeqProp->getKeyframes(); - int numKeyframes = keyframes->count(); + long numKeyframes = keyframes->count(); if (numKeyframes > 1) { // Make an animation! - Array *actions = Array::create(); + Vector actions; CCBKeyframe *keyframeFirst = (CCBKeyframe*)keyframes->getObjectAtIndex(0); float timeFirst = keyframeFirst->getTime() + fTweenDuration; if (timeFirst > 0) { - actions->addObject(DelayTime::create(timeFirst)); + actions.addObject(DelayTime::create(timeFirst)); } for (int i = 0; i < numKeyframes - 1; ++i) @@ -768,11 +768,11 @@ void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, // Apply easing action = getEaseAction(action, kf0->getEasingType(), kf0->getEasingOpt()); - actions->addObject(action); + actions.addObject(action); } } - FiniteTimeAction *seq = Sequence::create(actions); + auto seq = Sequence::create(actions); pNode->runAction(seq); } } diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index 64a91744d0..f094c10038 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; + long frameCount = cArray->count(); for (int i = 0; i < frameCount; i++) { ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i)); @@ -298,13 +299,13 @@ Spawn * ActionNode::refreshActionProperty() ActionFrame* srcFrame = (ActionFrame*)(cArray->getObjectAtIndex(i-1)); float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex()) * getUnitTime(); Action* cAction = frame->getAction(duration); - cSequenceArray->addObject(cAction); + cSequenceArray.addObject(static_cast(cAction)); } } Sequence* cSequence = Sequence::create(cSequenceArray); if (cSequence != NULL) { - cSpawnArray->addObject(cSequence); + cSpawnArray.addObject(cSequence); } } From 90062b656d2f8495437bbef1ef059c74ea1d80ae Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 28 Nov 2013 16:02:03 +0800 Subject: [PATCH 009/107] issue #2790: Node::_children is Vector now. --- cocos/2d/CCActionInterval.cpp | 46 ++- cocos/2d/CCAnimation.cpp | 65 ++--- cocos/2d/CCAnimation.h | 92 +++--- cocos/2d/CCAnimationCache.cpp | 30 +- cocos/2d/CCClippingNode.cpp | 9 +- cocos/2d/CCEventDispatcher.cpp | 11 +- cocos/2d/CCLabel.cpp | 55 ++-- cocos/2d/CCLabelBMFont.cpp | 68 ++--- cocos/2d/CCLayer.cpp | 12 +- cocos/2d/CCMenu.cpp | 268 +++++++----------- cocos/2d/CCMenu.h | 6 +- cocos/2d/CCNode.cpp | 139 ++++----- cocos/2d/CCNode.h | 22 +- cocos/2d/CCParticleBatchNode.cpp | 80 +++--- cocos/2d/CCParticleBatchNode.h | 8 +- cocos/2d/CCRenderTexture.cpp | 8 +- cocos/2d/CCScene.cpp | 24 +- cocos/2d/CCSprite.cpp | 34 ++- cocos/2d/CCSpriteBatchNode.cpp | 149 ++++------ cocos/2d/CCTMXLayer.cpp | 42 ++- cocos/2d/CCTMXTiledMap.cpp | 8 +- cocos/base/CCVector.h | 55 +++- .../editor-support/cocosbuilder/CCBReader.cpp | 12 +- .../editor-support/cocostudio/CCArmature.cpp | 14 +- .../editor-support/cocostudio/CCBatchNode.cpp | 4 +- cocos/editor-support/cocostudio/CCBone.cpp | 33 +-- 26 files changed, 585 insertions(+), 709 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 655922be15..649fa09d51 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -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().count()); 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,15 +2096,15 @@ void Animate::update(float t) t = fmodf(t, 1.0f); } - Array* frames = _animation->getFrames(); - long numberOfFrames = frames->count(); + auto frames = _animation->getFrames(); + long numberOfFrames = frames.count(); 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[i]; frameToDisplay = frame->getSpriteFrame(); static_cast(_target)->setDisplayFrame(frameToDisplay); @@ -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.count()); - CCARRAY_VERIFY_TYPE(pOldArray, AnimationFrame*); - - if (pOldArray->count() > 0) + if (oldArray.count() > 0) { - Object* pObj = NULL; - CCARRAY_FOREACH_REVERSE(pOldArray, pObj) + for (auto iter = oldArray.rcbegin(); iter != oldArray.rcend(); ++iter) { - AnimationFrame* pElement = static_cast(pObj); - if (! pElement) + AnimationFrame* animFrame = *iter; + if (!animFrame) { break; } - pNewArray->addObject(pElement->clone()); + newArray.addObject(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/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index fad60c6533..8a3df8d0e9 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -32,6 +32,20 @@ THE SOFTWARE. NS_CC_BEGIN +AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnits, Dictionary* 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) @@ -80,7 +94,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 +103,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 +113,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, nullptr); + _frames.addObject(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 +152,6 @@ Animation::Animation() : _totalDelayUnits(0.0f) , _delayPerUnit(0.0f) , _duration(0.0f) -, _frames(NULL) , _restoreOriginalFrame(false) , _loops(0) { @@ -161,15 +161,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, nullptr); + _frames.addObject(animFrame); // update duration _totalDelayUnits++; diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 13cf3b1fdc..2725314004 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -32,6 +32,8 @@ THE SOFTWARE. #include "CCDictionary.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, Dictionary* userInfo); SpriteFrame* getSpriteFrame() const { return _spriteFrame; }; @@ -100,6 +95,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, Dictionary* userInfo); + /** SpriteFrameName to be used */ SpriteFrame* _spriteFrame; @@ -108,6 +117,9 @@ protected: /** 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; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(AnimationFrame); }; @@ -135,34 +147,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 +190,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 +214,30 @@ public: virtual Animation *clone() const override; protected: + + /** + * @js ctor + */ + Animation(); + /** + * @js NA + * @lua NA + */ + 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 +248,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..e4cb5dc6b2 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -107,8 +107,7 @@ void AnimationCache::parseVersion1(Dictionary* animations) continue; } - Array* frames = Array::createWithCapacity(frameNames->count()); - frames->retain(); + Vector frames(frameNames->count()); Object* pObj = NULL; CCARRAY_FOREACH(frameNames, pObj) @@ -122,24 +121,21 @@ void AnimationCache::parseVersion1(Dictionary* animations) continue; } - AnimationFrame* animFrame = new AnimationFrame(); - animFrame->initWithSpriteFrame(spriteFrame, 1, NULL); - frames->addObject(animFrame); - animFrame->release(); + AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, nullptr); + frames.addObject(animFrame); } - if ( frames->count() == 0 ) { + 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()); continue; - } else if ( frames->count() != frameNames->count() ) { + } 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()); } animation = Animation::create(frames, delay, 1); AnimationCache::getInstance()->addAnimation(animation, element->getStrKey()); - frames->release(); - } + } } void AnimationCache::parseVersion2(Dictionary* animations) @@ -163,8 +159,7 @@ void AnimationCache::parseVersion2(Dictionary* animations) } // Array of AnimationFrames - Array* array = Array::createWithCapacity(frameArray->count()); - array->retain(); + Vector array(frameArray->count()); Object* pObj = NULL; CCARRAY_FOREACH(frameArray, pObj) @@ -183,22 +178,17 @@ void AnimationCache::parseVersion2(Dictionary* animations) float delayUnits = entry->valueForKey("delayUnits")->floatValue(); Dictionary* userInfo = (Dictionary*)entry->objectForKey("notification"); - AnimationFrame *animFrame = new AnimationFrame(); - animFrame->initWithSpriteFrame(spriteFrame, delayUnits, userInfo); + AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo); - array->addObject(animFrame); - animFrame->release(); + array.addObject(animFrame); } float delayPerUnit = animationDict->valueForKey("delayPerUnit")->floatValue(); - Animation *animation = new Animation(); - animation->initWithAnimationFrames(array, delayPerUnit, 0 != loops->length() ? loops->intValue() : 1); - array->release(); + Animation *animation = Animation::create(array, delayPerUnit, 0 != loops->length() ? loops->intValue() : 1); animation->setRestoreOriginalFrame(restoreOriginalFrame); AnimationCache::getInstance()->addAnimation(animation, name); - animation->release(); } } diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index d51fcc5002..a940cc1b6a 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().makeObjectsPerformCallback([p](Node* child){ + setProgram(child, p); + }); } ClippingNode::ClippingNode() diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 3387e8b3bf..ade48d38f3 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -189,18 +189,17 @@ EventDispatcher::~EventDispatcher() void EventDispatcher::visitTarget(Node* node) { - int i = 0; - Array* children = node->getChildren(); - int childrenCount = children ? children->count() : 0; + long i = 0; + auto children = node->getChildren(); + long childrenCount = children.count(); if(childrenCount > 0) { - Node* child = nullptr; // visit children zOrder < 0 for( ; i < childrenCount; i++ ) { - child = static_cast( children->getObjectAtIndex(i) ); + child = children[i]; if ( child && child->getZOrder() < 0 ) visitTarget(child); @@ -212,7 +211,7 @@ void EventDispatcher::visitTarget(Node* node) for( ; i < childrenCount; i++ ) { - child = static_cast( children->getObjectAtIndex(i) ); + child = children[i]; if (child) visitTarget(child); } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 07b652a897..7f9a4e2fa1 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.makeObjectsPerformCallback([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; @@ -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.makeObjectsPerformCallback([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.makeObjectsPerformCallback([this](Node* child){ Sprite *item = static_cast( child ); item->updateDisplayedOpacity(_displayedOpacity); - } + }); + V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - int count = _textureAtlas->getTotalQuads(); + long count = _textureAtlas->getTotalQuads(); Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); if (_isOpacityModifyRGB) { @@ -706,14 +700,13 @@ void Label::updateDisplayedColor(const Color3B& parentColor) _displayedColor.g = _realColor.g * parentColor.g/255.0; _displayedColor.b = _realColor.b * parentColor.b/255.0; - for (auto child: *_children) - { + _children.makeObjectsPerformCallback([this](Node* child){ Sprite *item = static_cast( child ); item->updateDisplayedColor(_displayedColor); - } + }); V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - int count = _textureAtlas->getTotalQuads(); + long count = _textureAtlas->getTotalQuads(); Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); // special opacity for premultiplied textures diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 88fb154770..7129d3f58e 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -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.makeObjectsPerformCallback([](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.makeObjectsPerformCallback([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.makeObjectsPerformCallback([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.makeObjectsPerformCallback([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.count(); j++) { Sprite* characterSprite; unsigned int justSkipped = 0; @@ -1068,7 +1050,7 @@ void LabelBMFont::updateLabel() multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - int size = multiline_string.size(); + size_t size = multiline_string.size(); unsigned short* str_new = new unsigned short[size + 1]; for (int j = 0; j < size; ++j) @@ -1096,7 +1078,7 @@ void LabelBMFont::updateLabel() if (_string[ctr] == '\n' || _string[ctr] == 0) { float lineWidth = 0.0f; - unsigned int line_length = last_line.size(); + size_t line_length = last_line.size(); // if last line is empty we must just increase lineNumber and work with next line if (line_length == 0) { diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index e7fe6f5342..2d9d263a15 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.makeObjectsPerformCallback([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.makeObjectsPerformCallback([this](Node* obj){ RGBAProtocol *item = dynamic_cast(obj); if (item) { item->updateDisplayedColor(_displayedColor); } - } + }); } } diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 6fef9d78a6..775ba5aaac 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -81,36 +81,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.addObject(item); MenuItem *i = va_arg(args, MenuItem*); while(i) { - pArray->addObject(i); + items.addObject(i); i = va_arg(args, MenuItem*); } } - return Menu::createWithArray(pArray); + return Menu::createWithArray(items); } Menu* Menu::createWithItem(MenuItem* item) @@ -120,10 +120,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 +137,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; @@ -306,33 +302,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.makeObjectsPerformCallback([&](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.makeObjectsPerformCallback([&](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 +328,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.makeObjectsPerformCallback([&](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.makeObjectsPerformCallback([&](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, ...) @@ -405,35 +379,29 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray) unsigned int columnsOccupied = 0; unsigned int rowColumns; - if (_children && _children->count() > 0) - { - Object* pObject = NULL; - CCARRAY_FOREACH(_children, pObject) + _children.makeObjectsPerformCallback([&](Node* child){ + if (child) { - Node* child = dynamic_cast(pObject); - if (child) + 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) { - 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,12 +415,9 @@ 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.makeObjectsPerformCallback([&](Node* child){ + if (child) { - Node* child = dynamic_cast(pObject); if (child) { if (rowColumns == 0) @@ -482,7 +447,7 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray) } } } - } + }); } void Menu::alignItemsInRows(int rows, ...) @@ -520,42 +485,36 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray) unsigned int rowsOccupied = 0; unsigned int columnRows; - if (_children && _children->count() > 0) - { - Object* pObject = NULL; - CCARRAY_FOREACH(_children, pObject) + _children.makeObjectsPerformCallback([&](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]; + // 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 +527,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.makeObjectsPerformCallback([&](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]; + 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) { Point touchLocation = touch->getLocation(); - if (_children && _children->count() > 0) + if (_children.count() > 0) { - Object* pObject = NULL; - CCARRAY_FOREACH_REVERSE(_children, pObject) + for (auto iter = _children.rcbegin(); iter != _children.rcend(); ++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..ad285fbadb 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -27,7 +27,7 @@ THE SOFTWARE. #include "CCMenuItem.h" #include "CCLayer.h" - +#include "CCVector.h" #include "CCEventTouch.h" NS_CC_BEGIN @@ -63,7 +63,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 @@ -129,7 +129,7 @@ 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; diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index bdff745edf..641a743ed4 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); @@ -406,7 +397,7 @@ void Node::setPositionY(float y) long Node::getChildrenCount() const { - return _children ? _children->count() : 0; + return _children.count(); } /// camera getter: lazy alloc @@ -584,7 +575,9 @@ void Node::cleanup() } // timers - arrayMakeObjectsPerformSelector(_children, cleanup, Node*); + _children.makeObjectsPerformCallback([](Node* child){ + child->cleanup(); + }); } @@ -593,28 +586,16 @@ const char* Node::description() const return String::createWithFormat("", _tag)->getCString(); } -// lazy allocs -void Node::childrenAlloc(void) -{ - _children = Array::createWithCapacity(4); - _children->retain(); -} - 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,11 +607,6 @@ 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 ) - { - this->childrenAlloc(); - } - this->insertChild(child, zOrder); #ifdef CC_USE_PHYSICS @@ -691,12 +667,12 @@ void Node::removeFromParentAndCleanup(bool cleanup) void Node::removeChild(Node* child, bool cleanup /* = true */) { // explicit nil handling - if (_children == NULL) + if (_children.count() == 0) { return; } - long index = _children->getIndexOfObject(child); + long index = _children.getIndexOfObject(child); if( index != CC_INVALID_INDEX ) this->detachChild( child, index, cleanup ); } @@ -725,33 +701,31 @@ void Node::removeAllChildren() void Node::removeAllChildrenWithCleanup(bool cleanup) { // not using detachChild improves speed here - if ( _children && _children->count() > 0 ) + if ( _children.count() > 0 ) { - 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.removeAllObjects(); } } @@ -783,9 +757,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.removeObjectAtIndex(childIndex); } @@ -793,7 +767,7 @@ void Node::detachChild(Node *child, long childIndex, bool doCleanup) void Node::insertChild(Node* child, int z) { _reorderChildDirty = true; - _children->addObject(child); + _children.addObject(child); child->_setZOrder(z); } @@ -810,24 +784,24 @@ void Node::sortAllChildren() #if 0 if (_reorderChildDirty) { - int i,j,length = _children->count(); + int i,j,length = _children.count(); // insertion sort for(i=1; i( _children->getObjectAtIndex(i) ); - auto tempJ = static_cast( _children->getObjectAtIndex(j) ); + auto tempI = static_cast( _children.getObjectAtIndex(i) ); + auto tempJ = static_cast( _children.getObjectAtIndex(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.getObjectAtIndex(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 +810,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 +843,13 @@ void Node::visit() this->transform(); int i = 0; - if(_children && _children->count() > 0) + if(_children.count() > 0) { sortAllChildren(); // draw children zOrder < 0 - for( ; i < _children->count(); i++ ) + for( ; i < _children.count(); i++ ) { - auto node = static_cast( _children->getObjectAtIndex(i) ); + auto node = _children[i]; if ( node && node->_ZOrder < 0 ) node->visit(); @@ -885,9 +859,9 @@ void Node::visit() // self draw this->draw(); - for( ; i < _children->count(); i++ ) + for( ; i < _children.count(); i++ ) { - auto node = static_cast( _children->getObjectAtIndex(i) ); + auto node = _children[i]; if (node) node->visit(); } @@ -955,7 +929,9 @@ void Node::onEnter() { _isTransitionFinished = false; - arrayMakeObjectsPerformSelector(_children, onEnter, Node*); + _children.makeObjectsPerformCallback([](Node* child){ + child->onEnter(); + }); this->resume(); @@ -974,8 +950,10 @@ void Node::onEnterTransitionDidFinish() { _isTransitionFinished = true; - arrayMakeObjectsPerformSelector(_children, onEnterTransitionDidFinish, Node*); - + _children.makeObjectsPerformCallback([](Node* child){ + child->onEnterTransitionDidFinish(); + }); + if (_scriptType != kScriptTypeNone) { int action = kNodeOnEnterTransitionDidFinish; @@ -987,7 +965,10 @@ void Node::onEnterTransitionDidFinish() void Node::onExitTransitionDidStart() { - arrayMakeObjectsPerformSelector(_children, onExitTransitionDidStart, Node*); + _children.makeObjectsPerformCallback([](Node* child){ + child->onExitTransitionDidStart(); + }); + if (_scriptType != kScriptTypeNone) { int action = kNodeOnExitTransitionDidStart; @@ -1010,7 +991,9 @@ void Node::onExit() ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); } - arrayMakeObjectsPerformSelector(_children, onExit, Node*); + _children.makeObjectsPerformCallback([](Node* child){ + child->onExit(); + }); } void Node::setEventDispatcher(EventDispatcher* dispatcher) @@ -1063,7 +1046,7 @@ Action * Node::getActionByTag(int tag) return _actionManager->getActionByTag(tag, this); } -unsigned int Node::getNumberOfRunningActions() const +long Node::getNumberOfRunningActions() const { return _actionManager->getNumberOfRunningActionsInTarget(this); } @@ -1358,7 +1341,9 @@ bool Node::updatePhysicsTransform() void Node::updateTransform() { // Recursively iterate over children - arrayMakeObjectsPerformSelector(_children, updateTransform, Node*); + _children.makeObjectsPerformCallback([](Node* child){ + child->updateTransform(); + }); } Component* Node::getComponent(const char *pName) @@ -1467,15 +1452,13 @@ void NodeRGBA::updateDisplayedOpacity(GLubyte parentOpacity) if (_cascadeOpacityEnabled) { - Object* pObj; - CCARRAY_FOREACH(_children, pObj) - { - RGBAProtocol* item = dynamic_cast(pObj); + _children.makeObjectsPerformCallback([this](Node* child){ + RGBAProtocol* item = dynamic_cast(child); if (item) { item->updateDisplayedOpacity(_displayedOpacity); } - } + }); } } @@ -1524,15 +1507,13 @@ void NodeRGBA::updateDisplayedColor(const Color3B& parentColor) if (_cascadeColorEnabled) { - Object *obj = NULL; - CCARRAY_FOREACH(_children, obj) - { - RGBAProtocol *item = dynamic_cast(obj); + _children.makeObjectsPerformCallback([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..37d28b0555 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,10 +613,10 @@ 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. @@ -1043,7 +1042,7 @@ public: * * @return The number of actions that are running plus the ones that are schedule to run */ - unsigned int getNumberOfRunningActions() const; + long getNumberOfRunningActions() const; /** @deprecated Use getNumberOfRunningActions() instead */ CC_DEPRECATED_ATTRIBUTE unsigned int numberOfRunningActions() const { return getNumberOfRunningActions(); }; @@ -1395,10 +1394,7 @@ protected: Node(); virtual ~Node(); virtual bool init(); - - /// lazy allocs - void childrenAlloc(void); - + /// helper that reorder a child void insertChild(Node* child, int z); @@ -1440,8 +1436,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..d396f29024 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -96,9 +96,11 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity) _textureAtlas->initWithTexture(tex, capacity); // no lazy alloc in this node - _children = new Array(); - _children->initWithCapacity(capacity); - + if (_children.count() == 0) + { + _children.init(capacity); + } + _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); @@ -171,7 +173,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.count() == 0 ) { setBlendFunc(child->getBlendFunc()); } @@ -186,9 +188,8 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag) if (pos != 0) { - ParticleSystem* p = (ParticleSystem*)_children->getObjectAtIndex(pos-1); + ParticleSystem* p = static_cast(_children[pos-1]); atlasIndex = p->getAtlasIndex() + p->getTotalParticles(); - } else { @@ -205,21 +206,20 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag) // XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster // XXX or possibly using vertexZ for reordering, that would be fastest // this helper is almost equivalent to Node's addChild, but doesn't make use of the lazy sorting -unsigned int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) +long ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) { CCASSERT( child != NULL, "Argument must be non-nil"); CCASSERT( child->getParent() == NULL, "child already added. It can't be added again"); - if( ! _children ) + if (_children.count() == 0 ) { - _children = new Array(); - _children->initWithCapacity(4); + _children.init(4); } //don't use a lazy insert - unsigned int pos = searchNewPositionInChildrenForZ(z); + long pos = searchNewPositionInChildrenForZ(z); - _children->insertObject(child, pos); + _children.insertObject(child, pos); child->setTag(aTag); child->_setZOrder(z); @@ -239,7 +239,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.containsObject(aChild), "Child doesn't belong to batch" ); ParticleSystem* child = static_cast(aChild); @@ -249,9 +249,9 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) } // no reordering if only 1 child - if( _children->count() > 1) + if( _children.count() > 1) { - unsigned int newIndex = 0, oldIndex = 0; + long newIndex = 0, oldIndex = 0; getCurrentIndex(&oldIndex, &newIndex, child, zOrder); @@ -260,8 +260,8 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) // reorder _children->array child->retain(); - _children->removeObjectAtIndex(oldIndex); - _children->insertObject(child, newIndex); + _children.removeObjectAtIndex(oldIndex); + _children.insertObject(child, newIndex); child->release(); // save old altasIndex @@ -272,10 +272,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.count();i++) { - ParticleSystem* pNode = (ParticleSystem*)_children->getObjectAtIndex(i); - if( pNode == child ) + ParticleSystem* node = static_cast(_children[i]); + if( node == child ) { newAtlasIndex = child->getAtlasIndex(); break; @@ -292,17 +292,17 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) child->_setZOrder(zOrder); } -void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, Node* child, int z) +void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* newIndex, Node* child, int z) { bool foundCurrentIdx = false; bool foundNewIdx = false; int minusOne = 0; - unsigned int count = _children->count(); + long count = _children.count(); - for( unsigned int i=0; i < count; i++ ) + for( long i=0; i < count; i++ ) { - Node* pNode = (Node *)_children->getObjectAtIndex(i); + Node* pNode = _children[i]; // new index if( pNode->getZOrder() > z && ! foundNewIdx ) @@ -343,13 +343,13 @@ void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* ne *newIndex += minusOne; } -unsigned int ParticleBatchNode::searchNewPositionInChildrenForZ(int z) +long ParticleBatchNode::searchNewPositionInChildrenForZ(int z) { - unsigned int count = _children->count(); + long count = _children.count(); - for( unsigned int i=0; i < count; i++ ) + for( long i=0; i < count; i++ ) { - Node *child = (Node *)_children->getObjectAtIndex(i); + Node *child = _children[i]; if (child->getZOrder() > z) { return i; @@ -366,7 +366,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.containsObject(aChild), "CCParticleBatchNode doesn't contain the sprite. Can't remove it"); ParticleSystem* child = static_cast(aChild); Node::removeChild(child, cleanup); @@ -385,12 +385,14 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup) void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) { - removeChild((ParticleSystem *)_children->getObjectAtIndex(index),doCleanup); + removeChild(_children[index],doCleanup); } void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup) { - arrayMakeObjectsPerformSelectorWithObject(_children, setBatchNode, NULL, ParticleSystem*); + _children.makeObjectsPerformCallback([](Node* child){ + static_cast(child)->setBatchNode(nullptr); + }); Node::removeAllChildrenWithCleanup(doCleanup); @@ -417,7 +419,7 @@ void ParticleBatchNode::draw(void) -void ParticleBatchNode::increaseAtlasCapacityTo(unsigned int quantity) +void ParticleBatchNode::increaseAtlasCapacityTo(long quantity) { CCLOG("cocos2d: ParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", (long)_textureAtlas->getCapacity(), @@ -467,15 +469,13 @@ void ParticleBatchNode::insertChild(ParticleSystem* system, int index) //rebuild atlas indexes void ParticleBatchNode::updateAllAtlasIndexes() { - Object *pObj = NULL; unsigned int index = 0; - - CCARRAY_FOREACH(_children,pObj) - { - ParticleSystem* child = static_cast(pObj); - child->setAtlasIndex(index); - index += child->getTotalParticles(); - } + + _children.makeObjectsPerformCallback([&index](Node* child){ + ParticleSystem* partiSys = static_cast(child); + partiSys->setAtlasIndex(index); + index += partiSys->getTotalParticles(); + }); } // ParticleBatchNode - CocosNodeTexture protocol diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index 937c348500..d7b6b93e42 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -129,10 +129,10 @@ public: private: void updateAllAtlasIndexes(); - void increaseAtlasCapacityTo(unsigned int quantity); - unsigned int searchNewPositionInChildrenForZ(int z); - void getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, Node* child, int z); - unsigned int addChildHelper(ParticleSystem* child, int z, int aTag); + void increaseAtlasCapacityTo(long quantity); + long searchNewPositionInChildrenForZ(int z); + void getCurrentIndex(long* oldIndex, long* newIndex, Node* child, int z); + long addChildHelper(ParticleSystem* child, int z, int aTag); void updateBlendFunc(void); /** the texture atlas used for drawing the quads */ TextureAtlas* _textureAtlas; diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index a35a564f85..fb87756191 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -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.makeObjectsPerformCallback([this](Node* child){ if (child != _sprite) { child->visit(); } - } + }); end(); } diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 97d4fbec65..0711839c0a 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().makeObjectsPerformCallback([addToPhysicsWorldFunc](Node* n){ + addToPhysicsWorldFunc(n); + }); }; addToPhysicsWorldFunc(child); diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 36577238b0..3a03a5d39c 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -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.containsObject(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.makeObjectsPerformCallback([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.makeObjectsPerformCallback([](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.makeObjectsPerformCallback([](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()[frameIndex]; CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 03a71abf1c..05c3e2a415 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -93,9 +93,10 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) updateBlendFunc(); // no lazy alloc in this node - _children = new Array(); - _children->initWithCapacity(capacity); - + if (_children.count() == 0) + { + _children.init(capacity); + } _descendants.reserve(capacity); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); @@ -187,7 +188,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.containsObject(child), "Child doesn't belong to Sprite"); if (zOrder == child->getZOrder()) { @@ -209,7 +210,7 @@ void SpriteBatchNode::removeChild(Node *child, bool cleanup) return; } - CCASSERT(_children->containsObject(sprite), "sprite batch node should contain the child"); + CCASSERT(_children.containsObject(sprite), "sprite batch node should contain the child"); // cleanup before removing removeSpriteFromAtlas(sprite); @@ -219,8 +220,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.count(), "Invalid index"); + removeChild(_children[index], doCleanup); } void SpriteBatchNode::removeAllChildrenWithCleanup(bool doCleanup) @@ -265,25 +266,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.count() > 0) { //first sort all children recursively based on zOrder - arrayMakeObjectsPerformSelector(_children, sortAllChildren, Sprite*); + _children.makeObjectsPerformCallback([](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.makeObjectsPerformCallback([this, &index](Node* child){ + Sprite* sp = static_cast(child); + updateAtlasIndex(sp, &index); + }); } _reorderChildDirty=false; @@ -292,12 +293,8 @@ void SpriteBatchNode::sortAllChildren() void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { - int count = 0; - Array* array = sprite->getChildren(); - if (array != NULL) - { - count = array->count(); - } + auto array = sprite->getChildren(); + long count = array.count(); int oldIndex = 0; @@ -315,7 +312,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { bool needNewIndex=true; - if (static_cast(array->getObjectAtIndex(0) )->getZOrder() >= 0) + if (array[0]->getZOrder() >= 0) { //all children are in front of the parent oldIndex = sprite->getAtlasIndex(); @@ -330,11 +327,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.makeObjectsPerformCallback([&](Node* child){ + Sprite* sp = static_cast(child); + if (needNewIndex && sp->getZOrder() >= 0) { oldIndex = sprite->getAtlasIndex(); sprite->setAtlasIndex(*curIndex); @@ -344,11 +339,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 +393,9 @@ void SpriteBatchNode::draw(void) CC_NODE_DRAW_SETUP(); - arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*); + _children.makeObjectsPerformCallback([](Node* child){ + child->updateTransform(); + }); GL::blendFunc( _blendFunc.src, _blendFunc.dst ); @@ -413,11 +409,11 @@ void SpriteBatchNode::increaseAtlasCapacity(void) // if we're going beyond the current TextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive - int quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; + long quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", - (long)_textureAtlas->getCapacity(), - (long)quantity); + _textureAtlas->getCapacity(), + quantity); if (! _textureAtlas->resizeCapacity(quantity)) { @@ -429,22 +425,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.count(), "Invalid index"); - Array *children = parent->getChildren(); + auto children = parent->getChildren(); - if (children && children->count() > 0) - { - Object* object = NULL; - CCARRAY_FOREACH(children, object) + children.makeObjectsPerformCallback([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 +444,56 @@ int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index) index++; } - if (children && children->count() > 0) - { - Object* object = NULL; - CCARRAY_FOREACH(children, object) + children.makeObjectsPerformCallback([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.count() == 0) { return sprite->getAtlasIndex(); } else { - return highestAtlasIndexInChild( static_cast(children->getLastObject())); + return highestAtlasIndexInChild( static_cast(children.getLastObject())); } } int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite) { - Array *children = sprite->getChildren(); + auto children = sprite->getChildren(); - if (! children || children->count() == 0) + if (children.count() == 0) { return sprite->getAtlasIndex(); } else { - return lowestAtlasIndexInChild(static_cast(children->getObjectAtIndex(0))); + return lowestAtlasIndexInChild(static_cast(children[0])); } } int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) { - Array *siblings = sprite->getParent()->getChildren(); - int childIndex = siblings->getIndexOfObject(sprite); + auto siblings = sprite->getParent()->getChildren(); + long childIndex = siblings.getIndexOfObject(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[childIndex - 1]); } // first child of the sprite sheet @@ -568,7 +554,7 @@ void SpriteBatchNode::appendChild(Sprite* sprite) } _descendants.push_back(sprite); - int index = _descendants.size()-1; + long index = _descendants.size()-1; sprite->setAtlasIndex(index); @@ -576,13 +562,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().makeObjectsPerformCallback([this](Node* child){ + appendChild(static_cast(child)); + }); } void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) @@ -606,19 +588,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.makeObjectsPerformCallback([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/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 87a9893126..41d8cd961d 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -390,22 +390,19 @@ 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.makeObjectsPerformCallback([&indexForZ](Node* child){ + Sprite* sp = static_cast(child); + if (child) { - Sprite* child = static_cast(pObject); - if (child) + unsigned 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; } @@ -558,7 +555,7 @@ void TMXLayer::removeChild(Node* node, bool cleanup) return; } - CCASSERT(_children->containsObject(sprite), "Tile does not belong to TMXLayer"); + CCASSERT(_children.containsObject(sprite), "Tile does not belong to TMXLayer"); unsigned int atlasIndex = sprite->getAtlasIndex(); unsigned int zz = (size_t)_atlasIndexArray->arr[atlasIndex]; @@ -596,22 +593,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.makeObjectsPerformCallback([&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/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 7ab6da363b..c21fc8666c 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -210,10 +210,10 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) 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,7 +224,7 @@ TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const } // layer not found - return NULL; + return nullptr; } TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 8ffadcb4c5..9b9c307b96 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -35,11 +35,14 @@ template class CC_DLL Vector { public: + + static const long DEFAULT_CAPACTIY = 7; + /** creates an emptry Vector */ - Vector(long capacity=7) + explicit Vector(long capacity=DEFAULT_CAPACTIY) : _data() { - CCLOG("In the constructor of Vector."); + CCLOG("In the default constructor of Vector."); init(capacity); } @@ -54,13 +57,27 @@ public: copy(other); } - const Vector& operator=(const Vector& other) + /** Move constructor */ + Vector(Vector&& other) { - CCLOG("In the assignment operator!"); + CCLOG("In the move constructor of Vector!"); + _data = std::move(other._data); + } + + Vector& operator=(const Vector& other) + { + CCLOG("In the copy assignment operator!"); copy(other); return *this; } + Vector& operator=(Vector&& other) + { + CCLOG("In the move assignment operator!"); + _data = std::move(other._data); + return *this; + } + T operator[](long index) const { return getObjectAtIndex(index); @@ -171,7 +188,8 @@ public: /** Insert a certain object at a certain index */ void insertObject(T object, long index) { - _data.insert( std::next( std::begin(_data, index), object ) ); + CCASSERT(index >= 0 && index < count(), "Invalid index!"); + _data.insert((std::begin(_data) + index), object); object->retain(); } @@ -220,6 +238,7 @@ public: (*it)->release(); } _data.clear(); + _data.reserve(DEFAULT_CAPACTIY); } /** Fast way to remove a certain object */ @@ -275,6 +294,16 @@ public: { _data.shrink_to_fit(); } + + void makeObjectsPerformCallback(std::function callback) + { + if (count() <= 0) + return; + + std::for_each(_data.begin(), _data.end(), [&callback](T obj){ + callback(obj); + }); + } // ------------------------------------------ // Iterators @@ -282,18 +311,26 @@ public: 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(); } - iterator cbegin() { return _data.cbegin(); } const_iterator cbegin() const { return _data.cbegin(); } - - iterator cend() { return _data.cend(); } 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 rcbegin() const { return _data.crbegin(); } + const_reverse_iterator rcend() const { return _data.crend(); } protected: std::vector _data; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index bf566770fe..5ee2b8a229 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -324,15 +324,13 @@ Scene* CCBReader::createSceneWithNodeGraphFromFile(const char *pCCBFileName, Obj return pScene; } -void CCBReader::cleanUpNodeGraph(Node *pNode) +void CCBReader::cleanUpNodeGraph(Node *node) { - pNode->setUserObject(NULL); + node->setUserObject(nullptr); - Object *pChild = NULL; - CCARRAY_FOREACH(pNode->getChildren(), pChild) - { - cleanUpNodeGraph(static_cast(pChild)); - } + node->getChildren().makeObjectsPerformCallback([this](Node* obj){ + cleanUpNodeGraph(obj); + }); } Node* CCBReader::readFileWithCleanUp(bool bCleanUp, Dictionary* am) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index b09922ff70..65c965276f 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.count(); 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[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..a18a9022c1 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.count() == 0) { 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..1e0e87bc94 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.makeObjectsPerformCallback([&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.count() == 0) { - _children = Array::createWithCapacity(4); - _children->retain(); + _children.init(4); } - if (_children->getIndexOfObject(child) == CC_INVALID_INDEX) + if (_children.getIndexOfObject(child) == CC_INVALID_INDEX) { - _children->addObject(child); + _children.addObject(child); child->setParentBone(this); } } void Bone::removeChildBone(Bone *bone, bool recursion) { - if (_children && _children->getIndexOfObject(bone) != CC_INVALID_INDEX ) + if (_children.count() > 0 && _children.getIndexOfObject(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); } } From d4d864216bca38e0ad5a92dbd995f0210e0850db Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 28 Nov 2013 17:57:13 +0800 Subject: [PATCH 010/107] issue #2790: Deletes Vector::init, adds Vector::setCapacity. --- cocos/2d/CCEventDispatcher.cpp | 3 +- cocos/2d/CCNode.cpp | 11 +++++++ cocos/2d/CCNode.h | 3 ++ cocos/2d/CCParticleBatchNode.cpp | 11 ++----- cocos/2d/CCSpriteBatchNode.cpp | 7 ++-- cocos/base/CCVector.h | 38 ++++++++++++---------- cocos/editor-support/cocostudio/CCBone.cpp | 2 +- 7 files changed, 41 insertions(+), 34 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index ade48d38f3..01b4606f75 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -190,7 +190,8 @@ EventDispatcher::~EventDispatcher() void EventDispatcher::visitTarget(Node* node) { long i = 0; - auto children = node->getChildren(); + const Vector& children = node->getChildren(); + long childrenCount = children.count(); if(childrenCount > 0) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 641a743ed4..df4ade5cf9 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -586,6 +586,12 @@ const char* Node::description() const return String::createWithFormat("", _tag)->getCString(); } +// lazy allocs +void Node::childrenAlloc(void) +{ + _children.setCapacity(4); +} + Node* Node::getChildByTag(int aTag) { CCASSERT( aTag != Node::INVALID_TAG, "Invalid tag"); @@ -607,6 +613,11 @@ 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.count() == 0) + { + this->childrenAlloc(); + } + this->insertChild(child, zOrder); #ifdef CC_USE_PHYSICS diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 37d28b0555..c1fa60b23c 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1394,6 +1394,9 @@ protected: Node(); virtual ~Node(); virtual bool init(); + + /// lazy allocs + void childrenAlloc(void); /// helper that reorder a child void insertChild(Node* child, int z); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index d396f29024..e5e1ef2033 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -95,11 +95,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity) _textureAtlas = new TextureAtlas(); _textureAtlas->initWithTexture(tex, capacity); - // no lazy alloc in this node - if (_children.count() == 0) - { - _children.init(capacity); - } + _children.setCapacity(capacity); _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; @@ -211,10 +207,7 @@ long ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) CCASSERT( child != NULL, "Argument must be non-nil"); CCASSERT( child->getParent() == NULL, "child already added. It can't be added again"); - if (_children.count() == 0 ) - { - _children.init(4); - } + _children.setCapacity(4); //don't use a lazy insert long pos = searchNewPositionInChildrenForZ(z); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 05c3e2a415..820224a234 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -92,11 +92,8 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) updateBlendFunc(); - // no lazy alloc in this node - if (_children.count() == 0) - { - _children.init(capacity); - } + _children.setCapacity(capacity); + _descendants.reserve(capacity); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 9b9c307b96..c0f69c55b5 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -35,15 +35,19 @@ template class CC_DLL Vector { public: - - static const long DEFAULT_CAPACTIY = 7; - - /** creates an emptry Vector */ - explicit Vector(long capacity=DEFAULT_CAPACTIY) + + Vector() : _data() { - CCLOG("In the default constructor of Vector."); - init(capacity); + + } + + /** creates an emptry Vector */ + explicit Vector(long capacity) + : _data() + { + CCLOG("In the default constructor with capacity of Vector."); + setCapacity(capacity); } virtual ~Vector() { @@ -83,11 +87,16 @@ public: return getObjectAtIndex(index); } - /** Initializes an array with capacity */ - bool init(long capacity) + /** Sets capacity of current array */ + void setCapacity(long capacity) { _data.reserve(capacity); - return true; + } + + /** Returns capacity of the array */ + long getCapacity() const + { + return _data.capacity(); } void copy(const Vector& other) @@ -96,7 +105,7 @@ public: return; removeAllObjects(); - init(other.count()); + setCapacity(other.count()); addObjectsFromArray(other); } @@ -108,12 +117,6 @@ public: return _data.size(); } - /** Returns capacity of the array */ - long capacity() const - { - return _data.capacity(); - } - /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ long getIndexOfObject(T object) const { @@ -238,7 +241,6 @@ public: (*it)->release(); } _data.clear(); - _data.reserve(DEFAULT_CAPACTIY); } /** Fast way to remove a certain object */ diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 1e0e87bc94..01392ad560 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -305,7 +305,7 @@ void Bone::addChildBone(Bone *child) if(_children.count() == 0) { - _children.init(4); + _children.setCapacity(4); } if (_children.getIndexOfObject(child) == CC_INVALID_INDEX) From 1d5984b29a4362485917d3406cbbd8b14e9f92d2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 28 Nov 2013 18:23:06 +0800 Subject: [PATCH 011/107] =?UTF-8?q?issue=20#2790:=20Vector::makeObjectsPer?= =?UTF-8?q?formCallback=20=E2=80=94>=20Vector::forEach?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCClippingNode.cpp | 2 +- cocos/2d/CCLabel.cpp | 8 +-- cocos/2d/CCLabelBMFont.cpp | 8 +-- cocos/2d/CCLayer.cpp | 4 +- cocos/2d/CCMenu.cpp | 18 ++--- cocos/2d/CCNode.cpp | 24 +++---- cocos/2d/CCParticleBatchNode.cpp | 8 +-- cocos/2d/CCRenderTexture.cpp | 2 +- cocos/2d/CCScene.cpp | 2 +- cocos/2d/CCSprite.cpp | 6 +- cocos/2d/CCSpriteBatchNode.cpp | 18 ++--- cocos/2d/CCTMXLayer.cpp | 4 +- cocos/base/CCVector.h | 7 +- .../editor-support/cocosbuilder/CCBReader.cpp | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 2 +- cocos/editor-support/cocostudio/CCBone.cpp | 6 +- .../GUI/CCControlExtension/CCControl.cpp | 14 ++-- .../GUI/CCControlExtension/CCScale9Sprite.cpp | 71 ++++++++----------- extensions/GUI/CCScrollView/CCScrollView.cpp | 32 +++------ .../Cpp/HelloCpp/Classes/HelloWorldScene.cpp | 58 ++++++++++++++- .../Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp | 13 ++-- .../TestCpp/Classes/LayerTest/LayerTest.cpp | 8 +-- .../Classes/ParticleTest/ParticleTest.cpp | 13 ++-- 23 files changed, 180 insertions(+), 150 deletions(-) diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index a940cc1b6a..710eb3003f 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -40,7 +40,7 @@ static void setProgram(Node *n, GLProgram *p) { n->setShaderProgram(p); - n->getChildren().makeObjectsPerformCallback([p](Node* child){ + n->getChildren().forEach([p](Node* child){ setProgram(child, p); }); } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 7f9a4e2fa1..f6e980d719 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -250,7 +250,7 @@ void Label::alignText() int strLen = cc_wcslen(_currentUTF16String); - _children.makeObjectsPerformCallback([this, &strLen](Node* child){ + _children.forEach([this, &strLen](Node* child){ if (child) { int tag = child->getTag(); @@ -592,7 +592,7 @@ void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) { _isOpacityModifyRGB = isOpacityModifyRGB; - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ if (child) { RGBAProtocol *pRGBAProtocol = dynamic_cast(child); @@ -634,7 +634,7 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity) { _displayedOpacity = _realOpacity * parentOpacity/255.0; - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ Sprite *item = static_cast( child ); item->updateDisplayedOpacity(_displayedOpacity); }); @@ -700,7 +700,7 @@ void Label::updateDisplayedColor(const Color3B& parentColor) _displayedColor.g = _realColor.g * parentColor.g/255.0; _displayedColor.b = _realColor.b * parentColor.b/255.0; - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ Sprite *item = static_cast( child ); item->updateDisplayedColor(_displayedColor); }); diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 7129d3f58e..64faa442e8 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -746,7 +746,7 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel) CC_SAFE_DELETE_ARRAY(tmp); } - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->setVisible(false); }); @@ -822,7 +822,7 @@ void LabelBMFont::setOpacity(GLubyte opacity) void LabelBMFont::setOpacityModifyRGB(bool var) { _isOpacityModifyRGB = var; - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ if (child) { RGBAProtocol *pRGBAProtocol = dynamic_cast(child); @@ -842,7 +842,7 @@ void LabelBMFont::updateDisplayedOpacity(GLubyte parentOpacity) { _displayedOpacity = _realOpacity * parentOpacity/255.0f; - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ Sprite *item = static_cast( child ); item->updateDisplayedOpacity(_displayedOpacity); }); @@ -854,7 +854,7 @@ void LabelBMFont::updateDisplayedColor(const Color3B& parentColor) _displayedColor.g = _realColor.g * parentColor.g/255.0f; _displayedColor.b = _realColor.b * parentColor.b/255.0f; - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ Sprite *item = static_cast( child ); item->updateDisplayedColor(_displayedColor); }); diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 2d9d263a15..c7c7c6d20d 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -499,7 +499,7 @@ void LayerRGBA::updateDisplayedOpacity(GLubyte parentOpacity) if (_cascadeOpacityEnabled) { - _children.makeObjectsPerformCallback([this](Node* obj){ + _children.forEach([this](Node* obj){ RGBAProtocol *item = dynamic_cast(obj); if (item) { @@ -517,7 +517,7 @@ void LayerRGBA::updateDisplayedColor(const Color3B& parentColor) if (_cascadeColorEnabled) { - _children.makeObjectsPerformCallback([this](Node* obj){ + _children.forEach([this](Node* obj){ RGBAProtocol *item = dynamic_cast(obj); if (item) { diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 775ba5aaac..4906702f35 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -303,7 +303,7 @@ void Menu::alignItemsVerticallyWithPadding(float padding) { float height = -padding; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { height += child->getContentSize().height * child->getScaleY() + padding; @@ -312,7 +312,7 @@ void Menu::alignItemsVerticallyWithPadding(float padding) float y = height / 2.0f; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f)); @@ -329,7 +329,7 @@ void Menu::alignItemsHorizontally(void) void Menu::alignItemsHorizontallyWithPadding(float padding) { float width = -padding; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { width += child->getContentSize().width * child->getScaleX() + padding; @@ -338,7 +338,7 @@ void Menu::alignItemsHorizontallyWithPadding(float padding) float x = -width / 2.0f; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0)); @@ -379,7 +379,7 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray) unsigned int columnsOccupied = 0; unsigned int rowColumns; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { CCASSERT(row < rows.size(), ""); @@ -415,7 +415,7 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray) float x = 0.0; float y = (float)(height / 2); - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { if (child) @@ -485,7 +485,7 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray) unsigned int rowsOccupied = 0; unsigned int columnRows; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { // check if too many menu items for the amount of rows/columns @@ -527,7 +527,7 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray) float x = (float)(-width / 2); float y = 0.0; - _children.makeObjectsPerformCallback([&](Node* child){ + _children.forEach([&](Node* child){ if (child) { if (columnRows == 0) @@ -562,7 +562,7 @@ MenuItem* Menu::itemForTouch(Touch *touch) { Point touchLocation = touch->getLocation(); - if (_children.count() > 0) + if (!_children.empty()) { for (auto iter = _children.rcbegin(); iter != _children.rcend(); ++iter) { diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index df4ade5cf9..fbba0e5df7 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -575,7 +575,7 @@ void Node::cleanup() } // timers - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->cleanup(); }); } @@ -613,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.count() == 0) + if (_children.empty()) { this->childrenAlloc(); } @@ -678,7 +678,7 @@ void Node::removeFromParentAndCleanup(bool cleanup) void Node::removeChild(Node* child, bool cleanup /* = true */) { // explicit nil handling - if (_children.count() == 0) + if (_children.empty()) { return; } @@ -712,7 +712,7 @@ void Node::removeAllChildren() void Node::removeAllChildrenWithCleanup(bool cleanup) { // not using detachChild improves speed here - if ( _children.count() > 0 ) + if (!_children.empty()) { for (auto& child : _children) { @@ -854,7 +854,7 @@ void Node::visit() this->transform(); int i = 0; - if(_children.count() > 0) + if(!_children.empty()) { sortAllChildren(); // draw children zOrder < 0 @@ -940,7 +940,7 @@ void Node::onEnter() { _isTransitionFinished = false; - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->onEnter(); }); @@ -961,7 +961,7 @@ void Node::onEnterTransitionDidFinish() { _isTransitionFinished = true; - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->onEnterTransitionDidFinish(); }); @@ -976,7 +976,7 @@ void Node::onEnterTransitionDidFinish() void Node::onExitTransitionDidStart() { - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->onExitTransitionDidStart(); }); @@ -1002,7 +1002,7 @@ void Node::onExit() ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); } - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->onExit(); }); } @@ -1352,7 +1352,7 @@ bool Node::updatePhysicsTransform() void Node::updateTransform() { // Recursively iterate over children - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->updateTransform(); }); } @@ -1463,7 +1463,7 @@ void NodeRGBA::updateDisplayedOpacity(GLubyte parentOpacity) if (_cascadeOpacityEnabled) { - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ RGBAProtocol* item = dynamic_cast(child); if (item) { @@ -1518,7 +1518,7 @@ void NodeRGBA::updateDisplayedColor(const Color3B& parentColor) if (_cascadeColorEnabled) { - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ RGBAProtocol *item = dynamic_cast(child); if (item) { diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index e5e1ef2033..2d5b54c248 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -169,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()); } @@ -242,7 +242,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) } // no reordering if only 1 child - if( _children.count() > 1) + if (!_children.empty()) { long newIndex = 0, oldIndex = 0; @@ -383,7 +383,7 @@ void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup) { - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ static_cast(child)->setBatchNode(nullptr); }); @@ -464,7 +464,7 @@ void ParticleBatchNode::updateAllAtlasIndexes() { unsigned int index = 0; - _children.makeObjectsPerformCallback([&index](Node* child){ + _children.forEach([&index](Node* child){ ParticleSystem* partiSys = static_cast(child); partiSys->setAtlasIndex(index); index += partiSys->getTotalParticles(); diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index fb87756191..3a2e0be1e4 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -528,7 +528,7 @@ void RenderTexture::draw() //! make sure all children are drawn sortAllChildren(); - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ if (child != _sprite) { child->visit(); diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 0711839c0a..86e8def996 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -140,7 +140,7 @@ void Scene::addChildToPhysicsWorld(Node* child) _physicsWorld->addBody(node->getPhysicsBody()); } - node->getChildren().makeObjectsPerformCallback([addToPhysicsWorldFunc](Node* n){ + node->getChildren().forEach([addToPhysicsWorldFunc](Node* n){ addToPhysicsWorldFunc(n); }); }; diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 3a03a5d39c..867cc07d71 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -726,7 +726,7 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup) { if (_batchNode) { - _children.makeObjectsPerformCallback([this](Node* child){ + _children.forEach([this](Node* child){ Sprite* sprite = dynamic_cast(child); if (sprite) { @@ -772,7 +772,7 @@ void Sprite::sortAllChildren() if ( _batchNode) { - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->sortAllChildren(); }); } @@ -809,7 +809,7 @@ void Sprite::setDirtyRecursively(bool bValue) // recursively set dirty if (_hasChildren) { - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ Sprite* sp = dynamic_cast(child); if (sp) { diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 820224a234..6b20d889e0 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -267,10 +267,10 @@ void SpriteBatchNode::sortAllChildren() #endif //sorted now check all children - if (_children.count() > 0) + if (!_children.empty()) { //first sort all children recursively based on zOrder - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->sortAllChildren(); }); @@ -278,7 +278,7 @@ void SpriteBatchNode::sortAllChildren() //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 - _children.makeObjectsPerformCallback([this, &index](Node* child){ + _children.forEach([this, &index](Node* child){ Sprite* sp = static_cast(child); updateAtlasIndex(sp, &index); }); @@ -324,7 +324,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) needNewIndex = false; } - array.makeObjectsPerformCallback([&](Node* child){ + array.forEach([&](Node* child){ Sprite* sp = static_cast(child); if (needNewIndex && sp->getZOrder() >= 0) { @@ -390,7 +390,7 @@ void SpriteBatchNode::draw(void) CC_NODE_DRAW_SETUP(); - _children.makeObjectsPerformCallback([](Node* child){ + _children.forEach([](Node* child){ child->updateTransform(); }); @@ -426,7 +426,7 @@ int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index) auto children = parent->getChildren(); - children.makeObjectsPerformCallback([this, &index](Node* child){ + children.forEach([this, &index](Node* child){ Sprite* sp = static_cast(child); if (sp && (sp->getZOrder() < 0)) { @@ -441,7 +441,7 @@ int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index) index++; } - children.makeObjectsPerformCallback([this, &index](Node* child){ + children.forEach([this, &index](Node* child){ Sprite* sp = static_cast(child); if (sp && (sp->getZOrder() >= 0)) { @@ -559,7 +559,7 @@ void SpriteBatchNode::appendChild(Sprite* sprite) _textureAtlas->insertQuad(&quad, index); // add children recursively - sprite->getChildren().makeObjectsPerformCallback([this](Node* child){ + sprite->getChildren().forEach([this](Node* child){ appendChild(static_cast(child)); }); } @@ -586,7 +586,7 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) // remove children recursively auto children = sprite->getChildren(); - children.makeObjectsPerformCallback([this](Node* obj){ + children.forEach([this](Node* obj){ Sprite* child = static_cast(obj); if (child) { diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 41d8cd961d..cfb6edbaf9 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -391,7 +391,7 @@ Sprite * TMXLayer::insertTileForGID(unsigned int gid, const Point& pos) // update possible children - _children.makeObjectsPerformCallback([&indexForZ](Node* child){ + _children.forEach([&indexForZ](Node* child){ Sprite* sp = static_cast(child); if (child) { @@ -593,7 +593,7 @@ void TMXLayer::removeTileAt(const Point& pos) _textureAtlas->removeQuadAtIndex(atlasIndex); // update possible children - _children.makeObjectsPerformCallback([&atlasIndex](Node* obj){ + _children.forEach([&atlasIndex](Node* obj){ Sprite* child = static_cast(obj); if (child) { diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index c0f69c55b5..a6b9065efb 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -117,6 +117,11 @@ public: return _data.size(); } + bool empty() const + { + return _data.empty(); + } + /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ long getIndexOfObject(T object) const { @@ -297,7 +302,7 @@ public: _data.shrink_to_fit(); } - void makeObjectsPerformCallback(std::function callback) + void forEach(std::function callback) { if (count() <= 0) return; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 5ee2b8a229..1f778248f2 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -328,7 +328,7 @@ void CCBReader::cleanUpNodeGraph(Node *node) { node->setUserObject(nullptr); - node->getChildren().makeObjectsPerformCallback([this](Node* obj){ + node->getChildren().forEach([this](Node* obj){ cleanUpNodeGraph(obj); }); } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index a18a9022c1..844e25f286 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -163,7 +163,7 @@ void BatchNode::visit() void BatchNode::draw() { - if (_children.count() == 0) + if (_children.empty()) { return; } diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 01392ad560..c25089b6bf 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -227,7 +227,7 @@ void Bone::update(float delta) DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - _children.makeObjectsPerformCallback([&delta](Node* obj){ + _children.forEach([&delta](Node* obj){ Bone *childBone = static_cast(obj); childBone->update(delta); }); @@ -303,7 +303,7 @@ 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.count() == 0) + if(_children.empty()) { _children.setCapacity(4); } @@ -317,7 +317,7 @@ void Bone::addChildBone(Bone *child) void Bone::removeChildBone(Bone *bone, bool recursion) { - if (_children.count() > 0 && _children.getIndexOfObject(bone) != CC_INVALID_INDEX ) + if (!_children.empty() && _children.getIndexOfObject(bone) != CC_INVALID_INDEX ) { if(recursion) { diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 3557c9bb5c..4b3edfa1f9 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -222,16 +222,14 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti void Control::setOpacityModifyRGB(bool bOpacityModifyRGB) { _isOpacityModifyRGB=bOpacityModifyRGB; - Object* child; - Array* children=getChildren(); - CCARRAY_FOREACH(children, child) - { - RGBAProtocol* pNode = dynamic_cast(child); - if (pNode) + + _children.forEach([&](Node* obj){ + RGBAProtocol* rgba = dynamic_cast(obj); + if (rgba) { - pNode->setOpacityModifyRGB(bOpacityModifyRGB); + rgba->setOpacityModifyRGB(bOpacityModifyRGB); } - } + }); } bool Control::isOpacityModifyRGB() const diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 8ad857fd7c..ecb67a4798 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp @@ -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..a7dd273e87 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.count(); i++ ) { - Node *child = static_cast( _children->getObjectAtIndex(i) ); + Node *child = _children[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.count(); i++ ) { - Node *child = static_cast( _children->getObjectAtIndex(i) ); + Node *child = _children[i]; child->visit(); } diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp index 077a92aa11..718743e010 100644 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp +++ b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp @@ -2,10 +2,10 @@ #include "AppMacros.h" #include "CCEventListenerTouch.h" +#include "CCVector.h" USING_NS_CC; - Scene* HelloWorld::scene() { // 'scene' is an autorelease object @@ -21,9 +21,61 @@ Scene* HelloWorld::scene() return scene; } +void showSprites(const Vector& sprites) +{ + log("container size = %ld", sprites.count()); + for (auto& sp : sprites) + { + log("sp tag: %d, ref count = %d", sp->getTag(), sp->retainCount()); + } +} + +Vector createAllSprites() +{ + Vector ret; + ret.addObject(Sprite::create()); + ret.addObject(Sprite::create()); + return ret; +} + // on "init" you need to initialize your instance bool HelloWorld::init() { + +// Vector container; +// +// for (int i = 0; i < 10; ++i) +// { +// auto sp = Sprite::create(); +// sp->setTag(i); +// container.addObject(sp); +// } +// +// showSprites(container); +// +// Vector containerCopy = container; +// +// showSprites(containerCopy); +// +// containerCopy = container; +// +// showSprites(containerCopy); + +// Vector moveVector(createAllSprites()); +// showSprites(moveVector); +// +// CCLOG("------------- 2 ----------"); +// moveVector = createAllSprites(); +// showSprites(moveVector); +// +// CCLOG("------------- 3 ----------"); +// Vector aaa; +// aaa.addObject(Sprite::create()); +// moveVector = aaa; +// showSprites(moveVector); + + log("size of Vector = %ld", sizeof(Vector)); + ////////////////////////////// // 1. super init first if ( !Layer::init() ) @@ -75,6 +127,10 @@ bool HelloWorld::init() // add the sprite as a child to this layer this->addChild(sprite); + this->getChildren().forEach([](Node* node){ + log("node = %p, name = %s", node, typeid(*node).name()); + }); + return true; } 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/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/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index bab33d56c3..ac915edbd6 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); From 8aef092005603e63a8a0706546f91e40c83cc5a7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 10:37:40 +0800 Subject: [PATCH 012/107] issue #2790: TestCpp with new Vector<>. --- cocos/2d/CCEventDispatcher.cpp | 2 +- cocos/2d/CCSpriteBatchNode.cpp | 12 +- cocos/base/CCVector.h | 12 +- .../Cpp/HelloCpp/Classes/HelloWorldScene.cpp | 2 + .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 19 +--- .../Classes/ParticleTest/ParticleTest.cpp | 41 ++++--- .../PerformanceNodeChildrenTest.cpp | 29 +++-- .../Classes/SchedulerTest/SchedulerTest.cpp | 4 +- .../TestCpp/Classes/ShaderTest/ShaderTest.cpp | 13 +-- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/TextInputTest/TextInputTest.cpp | 6 +- .../Classes/TileMapTest/TileMapTest.cpp | 107 ++++++------------ 12 files changed, 102 insertions(+), 147 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 01b4606f75..285ead66ea 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -190,7 +190,7 @@ EventDispatcher::~EventDispatcher() void EventDispatcher::visitTarget(Node* node) { long i = 0; - const Vector& children = node->getChildren(); + auto& children = node->getChildren(); long childrenCount = children.count(); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 6b20d889e0..b7bbab495f 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -290,7 +290,7 @@ void SpriteBatchNode::sortAllChildren() void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { - auto array = sprite->getChildren(); + auto& array = sprite->getChildren(); long count = array.count(); int oldIndex = 0; @@ -424,7 +424,7 @@ int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index) { CCASSERT(index>=0 && index < _children.count(), "Invalid index"); - auto children = parent->getChildren(); + auto& children = parent->getChildren(); children.forEach([this, &index](Node* child){ Sprite* sp = static_cast(child); @@ -454,7 +454,7 @@ int SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, int index) int SpriteBatchNode::highestAtlasIndexInChild(Sprite *sprite) { - auto children = sprite->getChildren(); + auto& children = sprite->getChildren(); if (children.count() == 0) { @@ -468,7 +468,7 @@ int SpriteBatchNode::highestAtlasIndexInChild(Sprite *sprite) int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite) { - auto children = sprite->getChildren(); + auto& children = sprite->getChildren(); if (children.count() == 0) { @@ -482,7 +482,7 @@ int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite) int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) { - auto siblings = sprite->getParent()->getChildren(); + auto& siblings = sprite->getParent()->getChildren(); long childIndex = siblings.getIndexOfObject(sprite); // ignore parent Z if parent is spriteSheet @@ -585,7 +585,7 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) } // remove children recursively - auto children = sprite->getChildren(); + auto& children = sprite->getChildren(); children.forEach([this](Node* obj){ Sprite* child = static_cast(obj); if (child) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index a6b9065efb..6ddd3b9f97 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -307,11 +307,21 @@ public: if (count() <= 0) return; - std::for_each(_data.begin(), _data.end(), [&callback](T obj){ + std::for_each(_data.cbegin(), _data.cend(), [&callback](T obj){ callback(obj); }); } + void forEachReverse(std::function callback) + { + if (count() <= 0) + return; + + std::for_each(_data.crbegin(), _data.crend(), [&callback](T obj){ + callback(obj); + }); + } + // ------------------------------------------ // Iterators // ------------------------------------------ diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp index 718743e010..7b9a58bd4c 100644 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp +++ b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp @@ -76,6 +76,8 @@ bool HelloWorld::init() log("size of Vector = %ld", sizeof(Vector)); + + ////////////////////////////// // 1. super init first if ( !Layer::init() ) diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index 5069f049b9..d962496595 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 ); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index ac915edbd6..16ac9680e7 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1581,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); @@ -1642,12 +1642,12 @@ void AddAndDeleteParticleSystems::onEnter() void AddAndDeleteParticleSystems::removeSystem(float dt) { - int nChildrenCount = _batchNode->getChildren()->count(); - if (nChildrenCount > 0) + int nChildrenCount = _batchNode->getChildren().count(); + 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()[uRand], true); auto particleSystem = ParticleSystemQuad::create("Particles/Spiral.plist"); //add new @@ -1670,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,26 +1795,25 @@ void ReorderParticleSystems::onEnter() void ReorderParticleSystems::reorderSystem(float time) { auto system = (ParticleSystem*)_batchNode->getChildren()->getObjectAtIndex(1); - _batchNode->reorderChild(system, system->getZOrder() - 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..127a0e8dc8 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); @@ -325,11 +325,11 @@ void IterateSpriteSheetCArray::update(float dt) 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/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 1da50ad4ca..867f58f98e 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -672,9 +672,9 @@ void SchedulerUpdate::onEnter() void SchedulerUpdate::removeUpdates(float dt) { - auto children = getChildren(); + auto& children = getChildren(); - for (auto c : *children) + for (auto& c : children) { auto obj = static_cast(c); auto node = static_cast(obj); 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..1fb53b3142 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 +49c7ab76862a3db1b3f4d1ce08c3017f99dc9ed4 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index d0ac2cb6b6..60f2581a55 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.count(); Point pos; for (int i = 0; i < count; ++i) { - node = (Node*)children->getObjectAtIndex(i); + node = children[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..df3f3b522b 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(); - } + }); } @@ -809,7 +779,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().count() ); _tamara->retain(); int mapWidth = map->getMapSize().width * map->getTileSize().width; _tamara->setPosition(CC_POINT_PIXELS_TO_POINTS(Point( mapWidth/2,0))); @@ -877,7 +847,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().count()); _tamara->retain(); _tamara->setAnchorPoint(Point(0.5f,0)); @@ -1154,12 +1124,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 +1152,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 +1229,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 +1256,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"); From 0d581a15d855f5b80e51b265450e7282774f3f73 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 11:02:50 +0800 Subject: [PATCH 013/107] issue #2790: MenuItemToggle::setSubItems() uses Vector now. --- cocos/2d/CCMenuItem.cpp | 53 +++++++------------ cocos/2d/CCMenuItem.h | 10 ++-- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 11 ++-- 3 files changed, 25 insertions(+), 49 deletions(-) diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 89aa7eaba6..6e0b507e85 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -810,13 +810,11 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle { MenuItemToggle *ret = new MenuItemToggle(); ret->MenuItem::initWithTarget(target, selector); - ret->_subItems = Array::create(); - ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems->addObject(menuItem); + ret->_subItems.addObject(menuItem); } ret->_selectedIndex = UINT_MAX; @@ -828,13 +826,11 @@ MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callba { MenuItemToggle *ret = new MenuItemToggle(); ret->MenuItem::initWithCallback(callback); - ret->_subItems = Array::create(); - ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems->addObject(menuItem); + ret->_subItems.addObject(menuItem); } ret->_selectedIndex = UINT_MAX; @@ -884,14 +880,13 @@ bool MenuItemToggle::initWithTarget(Object* target, SEL_MenuHandler selector, Me bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem *item, va_list args) { MenuItem::initWithCallback(callback); - this->_subItems = Array::create(); - this->_subItems->retain(); + int z = 0; MenuItem *i = item; while(i) { z++; - _subItems->addObject(i); + _subItems.addObject(i); i = va_arg(args, MenuItem*); } _selectedIndex = UINT_MAX; @@ -910,11 +905,10 @@ MenuItemToggle* MenuItemToggle::create(MenuItem *item) bool MenuItemToggle::initWithItem(MenuItem *item) { MenuItem::initWithCallback((const ccMenuCallback&)nullptr); - setSubItems(Array::create()); if (item) { - _subItems->addObject(item); + _subItems.addObject(item); } _selectedIndex = UINT_MAX; this->setSelectedIndex(0); @@ -927,24 +921,19 @@ bool MenuItemToggle::initWithItem(MenuItem *item) void MenuItemToggle::addSubItem(MenuItem *item) { - _subItems->addObject(item); + _subItems.addObject(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.count() > 0 ) { _selectedIndex = index; MenuItem *currentItem = (MenuItem*)getChildByTag(kCurrentItem); @@ -953,7 +942,7 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) currentItem->removeFromParentAndCleanup(false); } - MenuItem* item = (MenuItem*)_subItems->getObjectAtIndex(_selectedIndex); + MenuItem* item = _subItems[_selectedIndex]; this->addChild(item, 0, kCurrentItem); Size s = item->getContentSize(); this->setContentSize(s); @@ -964,13 +953,13 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::selected() { MenuItem::selected(); - static_cast(_subItems->getObjectAtIndex(_selectedIndex))->selected(); + _subItems[_selectedIndex]->selected(); } void MenuItemToggle::unselected() { MenuItem::unselected(); - static_cast(_subItems->getObjectAtIndex(_selectedIndex))->unselected(); + _subItems[_selectedIndex]->unselected(); } void MenuItemToggle::activate() @@ -978,7 +967,7 @@ void MenuItemToggle::activate() // update index if( _enabled ) { - unsigned int newIndex = (_selectedIndex + 1) % _subItems->count(); + unsigned int newIndex = (_selectedIndex + 1) % _subItems.count(); this->setSelectedIndex(newIndex); } MenuItem::activate(); @@ -989,21 +978,15 @@ void MenuItemToggle::setEnabled(bool enabled) { MenuItem::setEnabled(enabled); - if(_subItems && _subItems->count() > 0) - { - Object* pObj = NULL; - CCARRAY_FOREACH(_subItems, pObj) - { - MenuItem* pItem = static_cast(pObj); - pItem->setEnabled(enabled); - } - } + _subItems.forEach([&enabled](MenuItem* item){ + item->setEnabled(enabled); + }); } } MenuItem* MenuItemToggle::getSelectedItem() { - return static_cast(_subItems->getObjectAtIndex(_selectedIndex)); + return _subItems[_selectedIndex]; } NS_CC_END diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 09de7fe399..006cb3d0a7 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -481,13 +481,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; } @@ -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/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index d962496595..352e2f4db2 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -397,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().addObject( MenuItemFont::create( "33%" ) ); + item4->getSubItems().addObject( MenuItemFont::create( "66%" ) ); + item4->getSubItems().addObject( MenuItemFont::create( "100%" ) ); // you can change the one of the items by doing this item4->setSelectedIndex( 2 ); From cb215bc931d33b40eee2cd6147a714efae350eea Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 11:36:42 +0800 Subject: [PATCH 014/107] issue #2790: Vector replaces Array* finished. --- cocos/2d/CCActionInterval.cpp | 2 +- cocos/2d/CCLayer.cpp | 54 +++++++++------------- cocos/2d/CCLayer.h | 50 +++++++++++--------- cocos/2d/CCMenu.cpp | 2 +- cocos/2d/CCTMXTiledMap.cpp | 76 +++++++++++++------------------ cocos/2d/CCTMXTiledMap.h | 9 ++-- cocos/2d/CCTMXXMLParser.cpp | 61 ++++++++++--------------- cocos/2d/CCTMXXMLParser.h | 30 ++++++------ cocos/2d/platform/CCSAXParser.cpp | 2 +- cocos/2d/platform/CCSAXParser.h | 2 +- cocos/base/CCVector.h | 4 +- 11 files changed, 129 insertions(+), 163 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 649fa09d51..936c94823a 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -2129,7 +2129,7 @@ Animate* Animate::reverse() const if (oldArray.count() > 0) { - for (auto iter = oldArray.rcbegin(); iter != oldArray.rcend(); ++iter) + for (auto iter = oldArray.crbegin(); iter != oldArray.crend(); ++iter) { AnimationFrame* animFrame = *iter; if (!animFrame) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index c7c7c6d20d..bd04800a57 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -916,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, ...) @@ -967,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)) @@ -983,17 +978,13 @@ LayerMultiplex* LayerMultiplex::createWithArray(Array* arrayOfLayers) void LayerMultiplex::addLayer(Layer* layer) { - CCASSERT(_layers, ""); - _layers->addObject(layer); + _layers.addObject(layer); } bool LayerMultiplex::init() { if (Layer::init()) { - _layers = Array::create(); - _layers->retain(); - _enabledLayer = 0; return true; } @@ -1004,34 +995,32 @@ bool LayerMultiplex::initWithLayers(Layer *layer, va_list params) { if (Layer::init()) { - _layers = Array::createWithCapacity(5); - _layers->retain(); - _layers->addObject(layer); + _layers.setCapacity(5); + _layers.addObject(layer); Layer *l = va_arg(params,Layer*); while( l ) { - _layers->addObject(l); + _layers.addObject(l); l = va_arg(params,Layer*); } _enabledLayer = 0; - this->addChild((Node*)_layers->getObjectAtIndex(_enabledLayer)); + this->addChild(_layers[_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.setCapacity(arrayOfLayers.count()); + _layers.addObjectsFromArray(arrayOfLayers); _enabledLayer = 0; - this->addChild((Node*)_layers->getObjectAtIndex(_enabledLayer)); + this->addChild(_layers[_enabledLayer]); return true; } return false; @@ -1039,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.count(), "Invalid index in MultiplexLayer switchTo message" ); - this->removeChild((Node*)_layers->getObjectAtIndex(_enabledLayer), true); + this->removeChild(_layers[_enabledLayer], true); _enabledLayer = n; - this->addChild((Node*)_layers->getObjectAtIndex(n)); + this->addChild(_layers[n]); } void LayerMultiplex::switchToAndReleaseMe(int n) { - CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" ); + CCASSERT( n < _layers.count(), "Invalid index in MultiplexLayer switchTo message" ); - this->removeChild((Node*)_layers->getObjectAtIndex(_enabledLayer), true); + this->removeChild(_layers[_enabledLayer], true); - //[layers replaceObjectAtIndex:enabledLayer withObject:[NSNull null]]; - _layers->replaceObjectAtIndex(_enabledLayer, NULL); + _layers.replaceObjectAtIndex(_enabledLayer, nullptr); _enabledLayer = n; - this->addChild((Node*)_layers->getObjectAtIndex(n)); + this->addChild(_layers[n]); } NS_CC_END diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index fe96a5d40a..2284e7bf46 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -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 4906702f35..fa44b28630 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -564,7 +564,7 @@ MenuItem* Menu::itemForTouch(Touch *touch) if (!_children.empty()) { - for (auto iter = _children.rcbegin(); iter != _children.rcend(); ++iter) + for (auto iter = _children.crbegin(); iter != _children.crend(); ++iter) { MenuItem* child = dynamic_cast(*iter); if (child && child->isVisible() && child->isEnabled()) diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index c21fc8666c..4980093eb7 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,15 +90,13 @@ 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) + ,_properties(nullptr) + ,_tileProperties(nullptr) { } TMXTiledMap::~TMXTiledMap() { CC_SAFE_RELEASE(_properties); - CC_SAFE_RELEASE(_objectGroups); CC_SAFE_RELEASE(_tileProperties); } @@ -118,14 +116,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.count()>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 +154,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,9 +163,7 @@ 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(); @@ -180,30 +175,22 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) 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 @@ -231,13 +218,12 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const { CCASSERT(groupName.size() > 0, "Invalid group name!"); - if (_objectGroups && _objectGroups->count()>0) + if (_objectGroups.count()>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,7 +232,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const } // objectGroup not found - return NULL; + return nullptr; } String* TMXTiledMap::getProperty(const std::string& propertyName) const diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index 7148711e56..ac3c3c964a 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -156,10 +156,9 @@ 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; }; @@ -199,7 +198,7 @@ protected: /** map orientation */ int _mapOrientation; /** object groups */ - Array* _objectGroups; + Vector _objectGroups; /** properties */ Dictionary* _properties; diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 06a25e3e37..1c273325dd 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -50,7 +50,7 @@ static const char* valueForKey(const char *key, std::unordered_mapretain(); - - _layers = Array::create(); - _layers->retain(); - if (tmxFileName.size() > 0) { _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName); @@ -154,8 +148,7 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& _resources = resourcePath; } - _objectGroups = Array::createWithCapacity(4); - _objectGroups->retain(); + _objectGroups.setCapacity(4); _properties = new Dictionary(); _properties->init(); @@ -184,13 +177,10 @@ 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) +, _properties(nullptr) +, _tileProperties(nullptr) , _currentFirstGID(0) { } @@ -198,16 +188,13 @@ 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; @@ -325,7 +312,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) s.height = (float)atof(valueForKey("tileheight", attributeDict)); tileset->_tileSize = s; - pTMXMapInfo->getTilesets()->addObject(tileset); + pTMXMapInfo->getTilesets().addObject(tileset); tileset->release(); } } @@ -333,7 +320,7 @@ 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().getLastObject(); Size layerSize = layer->_layerSize; unsigned int gid = (unsigned int)atoi(valueForKey("gid", attributeDict)); int tilesAmount = layerSize.width*layerSize.height; @@ -367,7 +354,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) } else { - TMXTilesetInfo* info = (TMXTilesetInfo*)pTMXMapInfo->getTilesets()->getLastObject(); + TMXTilesetInfo* info = pTMXMapInfo->getTilesets().getLastObject(); Dictionary *dict = new Dictionary(); dict->init(); pTMXMapInfo->setParentGID(info->_firstGid + atoi(valueForKey("id", attributeDict))); @@ -404,7 +391,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) float y = (float)atof(valueForKey("y", attributeDict)); layer->_offset = Point(x,y); - pTMXMapInfo->getLayers()->addObject(layer); + pTMXMapInfo->getLayers().addObject(layer); layer->release(); // The parent element is now "layer" @@ -420,7 +407,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) positionOffset.y = (float)atof(valueForKey("y", attributeDict)) * pTMXMapInfo->getTileSize().height; objectGroup->setPositionOffset(positionOffset); - pTMXMapInfo->getObjectGroups()->addObject(objectGroup); + pTMXMapInfo->getObjectGroups().addObject(objectGroup); objectGroup->release(); // The parent element is now "objectgroup" @@ -429,7 +416,7 @@ 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().getLastObject(); // build full path std::string imagename = valueForKey("source", attributeDict); @@ -453,7 +440,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { pTMXMapInfo->setLayerAttribs(pTMXMapInfo->getLayerAttribs() | TMXLayerAttribNone); - TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); Size layerSize = layer->_layerSize; int tilesAmount = layerSize.width*layerSize.height; @@ -499,7 +486,7 @@ 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().getLastObject(); // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties @@ -572,7 +559,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer ) { // The parent element is the last layer - TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); String *value = new String(valueForKey("value", attributeDict)); std::string key = valueForKey("name", attributeDict); // Add the property to the layer @@ -583,7 +570,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup ) { // The parent element is the last object group - TMXObjectGroup* objectGroup = (TMXObjectGroup*)pTMXMapInfo->getObjectGroups()->getLastObject(); + TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().getLastObject(); String *value = new String(valueForKey("value", attributeDict)); const char* key = valueForKey("name", attributeDict); objectGroup->getProperties()->setObject(value, key); @@ -593,7 +580,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject ) { // The parent element is the last object - TMXObjectGroup* objectGroup = (TMXObjectGroup*)pTMXMapInfo->getObjectGroups()->getLastObject(); + TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().getLastObject(); Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject(); const char* propertyName = valueForKey("name", attributeDict); @@ -614,7 +601,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if (elementName == "polygon") { // find parent object's dict and add polygon-points to it - TMXObjectGroup* objectGroup = (TMXObjectGroup*)_objectGroups->getLastObject(); + TMXObjectGroup* objectGroup = _objectGroups.getLastObject(); Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject(); // get points value string @@ -667,7 +654,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if (elementName == "polyline") { // find parent object's dict and add polyline-points to it - TMXObjectGroup* objectGroup = (TMXObjectGroup*)_objectGroups->getLastObject(); + TMXObjectGroup* objectGroup = _objectGroups.getLastObject(); Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject(); // get points value string @@ -739,7 +726,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name) { pTMXMapInfo->setStoringCharacters(false); - TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); std::string currentString = pTMXMapInfo->getCurrentString(); unsigned char *buffer; @@ -763,7 +750,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name) inflatedLen = (size_t)&inflatedLen; // XXX: to avoid warnings in compiler free(buffer); - buffer = NULL; + buffer = nullptr; if( ! deflated ) { @@ -782,7 +769,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name) } else if (pTMXMapInfo->getLayerAttribs() & TMXLayerAttribNone) { - TMXLayerInfo* layer = (TMXLayerInfo*)pTMXMapInfo->getLayers()->getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); Size layerSize = layer->_layerSize; int tilesAmount = layerSize.width * layerSize.height; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 80afafd1aa..2644f8b413 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -32,12 +32,15 @@ THE SOFTWARE. #include "CCDictionary.h" #include "CCGeometry.h" #include "platform/CCSAXParser.h" +#include "CCVector.h" #include NS_CC_BEGIN +class TMXLayerInfo; class TMXObjectGroup; +class TMXTilesetInfo; /** @file * Internal TMX parser @@ -213,26 +216,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; }; @@ -293,11 +293,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 diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 056a088826..7d40df896f 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -102,7 +102,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); diff --git a/cocos/2d/platform/CCSAXParser.h b/cocos/2d/platform/CCSAXParser.h index 452061776a..e97b55f8de 100644 --- a/cocos/2d/platform/CCSAXParser.h +++ b/cocos/2d/platform/CCSAXParser.h @@ -81,7 +81,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/base/CCVector.h b/cocos/base/CCVector.h index 6ddd3b9f97..3beb5b19e0 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -346,8 +346,8 @@ public: reverse_iterator rend() { return _data.rend(); } const_reverse_iterator rend() const { return _data.rend(); } - const_reverse_iterator rcbegin() const { return _data.crbegin(); } - const_reverse_iterator rcend() const { return _data.crend(); } + const_reverse_iterator crbegin() const { return _data.crbegin(); } + const_reverse_iterator crend() const { return _data.crend(); } protected: std::vector _data; From 9928e8bef1527251f64399e0c2ff461f524dd4da Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 16:33:15 +0800 Subject: [PATCH 015/107] issue #2790: Uses Vector::getObjectAtIndex instead of Vector[] operator to avoid some mistakes. --- cocos/2d/CCActionInterval.cpp | 10 ++-- cocos/2d/CCEventDispatcher.cpp | 4 +- cocos/2d/CCLayer.cpp | 12 ++-- cocos/2d/CCMenuItem.cpp | 8 +-- cocos/2d/CCNode.cpp | 21 ++++--- cocos/2d/CCParticleBatchNode.cpp | 12 ++-- cocos/2d/CCSprite.cpp | 2 +- cocos/2d/CCSpriteBatchNode.cpp | 8 +-- cocos/base/CCVector.h | 57 ++++++++++++------- .../editor-support/cocostudio/CCArmature.cpp | 2 +- 10 files changed, 77 insertions(+), 59 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 936c94823a..56c4c1a5f9 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -206,13 +206,13 @@ Sequence* Sequence::create(const Vector& arrayOfActions) long count = arrayOfActions.count(); CC_BREAK_IF(count == 0); - auto prev = arrayOfActions[0]; + auto prev = arrayOfActions.getObjectAtIndex(0); if (count > 1) { for (long i = 1; i < count; ++i) { - prev = createWithTwoActions(prev, arrayOfActions[i]); + prev = createWithTwoActions(prev, arrayOfActions.getObjectAtIndex(i)); } } else @@ -578,12 +578,12 @@ Spawn* Spawn::create(const Vector& arrayOfActions) { long count = arrayOfActions.count(); CC_BREAK_IF(count == 0); - auto prev = arrayOfActions[0]; + auto prev = arrayOfActions.getObjectAtIndex(0); if (count > 1) { for (int i = 1; i < arrayOfActions.count(); ++i) { - prev = createWithTwoActions(prev, arrayOfActions[i]); + prev = createWithTwoActions(prev, arrayOfActions.getObjectAtIndex(i)); } } else @@ -2104,7 +2104,7 @@ void Animate::update(float t) float splitTime = _splitTimes->at(i); if( splitTime <= t ) { - AnimationFrame* frame = frames[i]; + AnimationFrame* frame = frames.getObjectAtIndex(i); frameToDisplay = frame->getSpriteFrame(); static_cast(_target)->setDisplayFrame(frameToDisplay); diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 285ead66ea..a0831ce9ab 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -200,7 +200,7 @@ void EventDispatcher::visitTarget(Node* node) // visit children zOrder < 0 for( ; i < childrenCount; i++ ) { - child = children[i]; + child = children.getObjectAtIndex(i); if ( child && child->getZOrder() < 0 ) visitTarget(child); @@ -212,7 +212,7 @@ void EventDispatcher::visitTarget(Node* node) for( ; i < childrenCount; i++ ) { - child = children[i]; + child = children.getObjectAtIndex(i); if (child) visitTarget(child); } diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index bd04800a57..c9b9d0c38d 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -1005,7 +1005,7 @@ bool LayerMultiplex::initWithLayers(Layer *layer, va_list params) } _enabledLayer = 0; - this->addChild(_layers[_enabledLayer]); + this->addChild(_layers.getObjectAtIndex(_enabledLayer)); return true; } @@ -1020,7 +1020,7 @@ bool LayerMultiplex::initWithArray(const Vector& arrayOfLayers) _layers.addObjectsFromArray(arrayOfLayers); _enabledLayer = 0; - this->addChild(_layers[_enabledLayer]); + this->addChild(_layers.getObjectAtIndex(_enabledLayer)); return true; } return false; @@ -1030,24 +1030,24 @@ void LayerMultiplex::switchTo(int n) { CCASSERT( n < _layers.count(), "Invalid index in MultiplexLayer switchTo message" ); - this->removeChild(_layers[_enabledLayer], true); + this->removeChild(_layers.getObjectAtIndex(_enabledLayer), true); _enabledLayer = n; - this->addChild(_layers[n]); + this->addChild(_layers.getObjectAtIndex(n)); } void LayerMultiplex::switchToAndReleaseMe(int n) { CCASSERT( n < _layers.count(), "Invalid index in MultiplexLayer switchTo message" ); - this->removeChild(_layers[_enabledLayer], true); + this->removeChild(_layers.getObjectAtIndex(_enabledLayer), true); _layers.replaceObjectAtIndex(_enabledLayer, nullptr); _enabledLayer = n; - this->addChild(_layers[n]); + this->addChild(_layers.getObjectAtIndex(n)); } NS_CC_END diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 6e0b507e85..b6f98ea424 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -942,7 +942,7 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) currentItem->removeFromParentAndCleanup(false); } - MenuItem* item = _subItems[_selectedIndex]; + MenuItem* item = _subItems.getObjectAtIndex(_selectedIndex); this->addChild(item, 0, kCurrentItem); Size s = item->getContentSize(); this->setContentSize(s); @@ -953,13 +953,13 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::selected() { MenuItem::selected(); - _subItems[_selectedIndex]->selected(); + _subItems.getObjectAtIndex(_selectedIndex)->selected(); } void MenuItemToggle::unselected() { MenuItem::unselected(); - _subItems[_selectedIndex]->unselected(); + _subItems.getObjectAtIndex(_selectedIndex)->unselected(); } void MenuItemToggle::activate() @@ -986,7 +986,7 @@ void MenuItemToggle::setEnabled(bool enabled) MenuItem* MenuItemToggle::getSelectedItem() { - return _subItems[_selectedIndex]; + return _subItems.getObjectAtIndex(_selectedIndex); } NS_CC_END diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index fbba0e5df7..43cc219118 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -852,7 +852,7 @@ void Node::visit() } this->transform(); - int i = 0; + long i = 0; if(!_children.empty()) { @@ -860,7 +860,7 @@ void Node::visit() // draw children zOrder < 0 for( ; i < _children.count(); i++ ) { - auto node = _children[i]; + auto node = _children.getObjectAtIndex(i); if ( node && node->_ZOrder < 0 ) node->visit(); @@ -870,12 +870,17 @@ void Node::visit() // self draw this->draw(); - for( ; i < _children.count(); i++ ) - { - auto node = _children[i]; - if (node) - node->visit(); - } + // Uses std::for_each to improve performance. + std::for_each(_children.cbegin()+i, _children.cend(), [](Node* node){ + node->visit(); + }); + +// for( ; i < _children.count(); i++ ) +// { +// auto node = _children[i]; +// if (node) +// node->visit(); +// } } else { diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 2d5b54c248..b3ecc28fa1 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -177,14 +177,14 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag) CCASSERT( _blendFunc.src == child->getBlendFunc().src && _blendFunc.dst == child->getBlendFunc().dst, "Can't add a ParticleSystem that uses a different blending function"); //no lazy sorting, so don't call super addChild, call helper instead - unsigned int pos = addChildHelper(child,zOrder,tag); + long pos = addChildHelper(child,zOrder,tag); //get new atlasIndex int atlasIndex = 0; if (pos != 0) { - ParticleSystem* p = static_cast(_children[pos-1]); + ParticleSystem* p = static_cast(_children.getObjectAtIndex(pos-1)); atlasIndex = p->getAtlasIndex() + p->getTotalParticles(); } else @@ -267,7 +267,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) int newAtlasIndex = 0; for( int i=0;i < _children.count();i++) { - ParticleSystem* node = static_cast(_children[i]); + ParticleSystem* node = static_cast(_children.getObjectAtIndex(i)); if( node == child ) { newAtlasIndex = child->getAtlasIndex(); @@ -295,7 +295,7 @@ void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* newIndex, Node* ch for( long i=0; i < count; i++ ) { - Node* pNode = _children[i]; + Node* pNode = _children.getObjectAtIndex(i); // new index if( pNode->getZOrder() > z && ! foundNewIdx ) @@ -342,7 +342,7 @@ long ParticleBatchNode::searchNewPositionInChildrenForZ(int z) for( long i=0; i < count; i++ ) { - Node *child = _children[i]; + Node *child = _children.getObjectAtIndex(i); if (child->getZOrder() > z) { return i; @@ -378,7 +378,7 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup) void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) { - removeChild(_children[index],doCleanup); + removeChild(_children.getObjectAtIndex(index), doCleanup); } void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 867cc07d71..c8b328dcb0 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -1060,7 +1060,7 @@ void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - AnimationFrame* frame = a->getFrames()[frameIndex]; + AnimationFrame* frame = a->getFrames().getObjectAtIndex(frameIndex); CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index b7bbab495f..c6ca01d03c 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -218,7 +218,7 @@ void SpriteBatchNode::removeChild(Node *child, bool cleanup) void SpriteBatchNode::removeChildAtIndex(int index, bool doCleanup) { CCASSERT(index>=0 && index < _children.count(), "Invalid index"); - removeChild(_children[index], doCleanup); + removeChild(_children.getObjectAtIndex(index), doCleanup); } void SpriteBatchNode::removeAllChildrenWithCleanup(bool doCleanup) @@ -309,7 +309,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { bool needNewIndex=true; - if (array[0]->getZOrder() >= 0) + if (array.getObjectAtIndex(0)->getZOrder() >= 0) { //all children are in front of the parent oldIndex = sprite->getAtlasIndex(); @@ -476,7 +476,7 @@ int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite) } else { - return lowestAtlasIndexInChild(static_cast(children[0])); + return lowestAtlasIndexInChild(static_cast(children.getObjectAtIndex(0))); } } @@ -490,7 +490,7 @@ int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) Sprite *prev = NULL; if (childIndex > 0 && childIndex != -1) { - prev = static_cast(siblings[childIndex - 1]); + prev = static_cast(siblings.getObjectAtIndex(childIndex - 1)); } // first child of the sprite sheet diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 3beb5b19e0..31554a3c8c 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -35,7 +35,6 @@ template class CC_DLL Vector { public: - Vector() : _data() { @@ -50,7 +49,8 @@ public: setCapacity(capacity); } - virtual ~Vector() { + virtual ~Vector() + { CCLOG("In the destructor of Vector."); removeAllObjects(); } @@ -58,34 +58,42 @@ public: Vector(const Vector& other) { CCLOG("In the copy constructor!"); - copy(other); + _data = other._data; + addRefForAllObjects(); } /** Move constructor */ Vector(Vector&& other) { CCLOG("In the move constructor of Vector!"); - _data = std::move(other._data); + _data = other._data; } Vector& operator=(const Vector& other) { CCLOG("In the copy assignment operator!"); - copy(other); + removeAllObjects(); + _data = other._data; + addRefForAllObjects(); return *this; } Vector& operator=(Vector&& other) { CCLOG("In the move assignment operator!"); - _data = std::move(other._data); + _data = other._data; return *this; } - T operator[](long index) const - { - return getObjectAtIndex(index); - } +// T& operator[](long index) +// { +// return _data[index]; +// } +// +// const T& operator[](long index) const +// { +// return _data[index]; +// } /** Sets capacity of current array */ void setCapacity(long capacity) @@ -99,16 +107,6 @@ public: return _data.capacity(); } - void copy(const Vector& other) - { - if (this == &other) - return; - - removeAllObjects(); - setCapacity(other.count()); - addObjectsFromArray(other); - } - // Querying an Array /** Returns element count of the array */ @@ -153,7 +151,12 @@ public: /** Returns a random element */ T getRandomObject() const { - return *_data.begin(); + 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. */ @@ -204,6 +207,8 @@ public: /** sets a certain object at a certain index */ void setObject(T object, long index) { + CCASSERT(index >= 0 && index < count(), "Invalid index!"); + _data[index]->release(); _data[index] = object; object->retain(); } @@ -348,9 +353,17 @@ public: 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 diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 65c965276f..10dffd52b2 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -677,7 +677,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) const for(long i = length - 1; i >= 0; i--) { - bs = static_cast( _children[i] ); + bs = static_cast( _children.getObjectAtIndex(i) ); if(bs->getDisplayManager()->containPoint(x, y)) { return bs; From d2bddee11ea216aff88205481b78edadc9c63de7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 16:33:38 +0800 Subject: [PATCH 016/107] issue #2790: Adds CCMap.h. --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/cocos2d.h | 1 + cocos/base/CCMap.h | 252 ++++++++++++++++++ .../Cpp/HelloCpp/Classes/HelloWorldScene.cpp | 49 +++- 4 files changed, 294 insertions(+), 10 deletions(-) create mode 100644 cocos/base/CCMap.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index f3eb0ecbbc..1f939cccfd 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -0934e5b3cb72bb084c73b2cdc7dc70a5df006b44 \ No newline at end of file +6c2f36e8a93d2fd99c6bd5ed3c2d37e8cf366ce5 \ No newline at end of file diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index fa194c7fe0..e18bee1c4e 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -61,6 +61,7 @@ THE SOFTWARE. #include "CCObject.h" #include "CCArray.h" #include "CCVector.h" +#include "CCMap.h" #include "CCGeometry.h" #include "CCSet.h" #include "CCAutoreleasePool.h" diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h new file mode 100644 index 0000000000..540bd11afa --- /dev/null +++ b/cocos/base/CCMap.h @@ -0,0 +1,252 @@ +/**************************************************************************** +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 + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +template +class CC_DLL Map +{ +public: + Map() + : _data() + { + CCLOG("In the default constructor of Map!"); + } + + explicit Map(long capacity) + : _data() + { + CCLOG("In the constructor with capacity of Map!"); + _data.reserve(capacity); + } + + Map(const Map& other) + { + CCLOG("In the copy constructor of Map!"); + _data = other; + addRefForAllObjects(); + } + + Map(Map&& other) + { + CCLOG("In the move constructor of Map!"); + _data = other; + } + + ~Map() + { + CCLOG("In the destructor of Map!"); + removeAllObjects(); + } + + /** Sets capacity of current array */ + void setCapacity(long capacity) + { + _data.reserve(capacity); + } + + /** Returns capacity of the array */ + long getCapacity() const + { + return _data.capacity(); + } + + long count() const + { + return _data.size(); + } + + bool empty() const + { + return _data.empty(); + } + + std::vector getAllKeys() const + { + std::vector keys; + + if (!_data.empty()) + { + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) + { + keys.push_back(iter->first); + } + } + return keys; + } + + std::vector getAllKeysForObject(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 keys; + } + + V getObjectForKey(const K& key) const + { + auto iter = _data.find(key); + if (iter != _data.end()) + return iter->second; + + return nullptr; + } + + void setObject(V object, const K& key) + { + removeObjectForKey(key); + _data.insert(std::make_pair(key, object)); + object->retain(); + } + + void removeObjectForKey(const K& key) + { + auto iter = _data.find(key); + if (iter != _data.end()) + { + iter->second->release(); + _data.erase(iter); + } + } + + void removeObjectsForKeys(const std::vector& keys) + { + std::for_each(keys.cbegin(), keys.cend(), [this](K key){ + removeObjectForKey(key); + }); + } + + void removeAllObjects() + { + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) + { + CC_SAFE_RELEASE(iter->second); + } + + _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(); } + + // Operator +// 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 ) + { + CCLOG("In the copy assignment operator of Map!"); + removeAllObjects(); + _data = other._data; + addRefForAllObjects(); + } + + Map& operator= ( Map&& other ) + { + CCLOG("In the move assignment operator of Map!"); + _data = other._data; + } + +protected: + + void addRefForAllObjects() + { + for (auto iter = _data.begin(); iter != _data.end(); ++iter) + { + _data->second->retain(); + } + } + + RefMap _data; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCMAP_H__ */ diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp index 7b9a58bd4c..eab8247f4a 100644 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp +++ b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp @@ -42,15 +42,16 @@ Vector createAllSprites() bool HelloWorld::init() { -// Vector container; -// -// for (int i = 0; i < 10; ++i) -// { -// auto sp = Sprite::create(); -// sp->setTag(i); -// container.addObject(sp); -// } -// + Vector container; + + for (int i = 0; i < 10; ++i) + { + auto sp = Sprite::create(); + sp->setTag(i); + container.addObject(sp); + } + +// // showSprites(container); // // Vector containerCopy = container; @@ -76,7 +77,37 @@ bool HelloWorld::init() log("size of Vector = %ld", sizeof(Vector)); + Map map; + map.setObject(Sprite::create(), "1"); + map.setObject(Sprite::create(), "2"); + map.setObject(Sprite::create(), "3"); + + auto showMap = [](const Map& map) + { + for (auto iter = map.begin(); iter != map.end(); ++iter) + { + log("key = %s, value = %p, ref = %d", iter->first.c_str(), iter->second, iter->second ? iter->second->retainCount() : 0); + } + }; + showMap(map); + +// auto iter = std::find(map.begin(), map.end(), std::string("111")); +// if (iter != map.end()) +// { +// log("found!"); +// } +// else +// { +// log("not found!"); +// } + +// map["111"]; +// log("key[1]=%p", map["1"]); +// log("----------------------"); +// map["11"]->setPosition(Point(100, 100)); + + showMap(map); ////////////////////////////// // 1. super init first From f6676bd7efcfe663d34689467867e88ccff99286 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 16:52:12 +0800 Subject: [PATCH 017/107] issue #2790: [] -> getObjectAtIndex. --- extensions/GUI/CCScrollView/CCScrollView.cpp | 4 ++-- samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp | 4 ++-- .../TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index a7dd273e87..0d2d3610b4 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -564,7 +564,7 @@ void ScrollView::visit() // draw children zOrder < 0 for( ; i < _children.count(); i++ ) { - Node *child = _children[i]; + Node *child = _children.getObjectAtIndex(i); if ( child->getZOrder() < 0 ) { child->visit(); @@ -581,7 +581,7 @@ void ScrollView::visit() // draw children zOrder >= 0 for( ; i < _children.count(); i++ ) { - Node *child = _children[i]; + Node *child = _children.getObjectAtIndex(i); child->visit(); } diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index 16ac9680e7..cce6ac09f5 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1647,7 +1647,7 @@ void AddAndDeleteParticleSystems::removeSystem(float dt) { CCLOG("remove random system"); unsigned int uRand = rand() % (nChildrenCount - 1); - _batchNode->removeChild(_batchNode->getChildren()[uRand], true); + _batchNode->removeChild(_batchNode->getChildren().getObjectAtIndex(uRand), true); auto particleSystem = ParticleSystemQuad::create("Particles/Spiral.plist"); //add new @@ -1794,7 +1794,7 @@ void ReorderParticleSystems::onEnter() void ReorderParticleSystems::reorderSystem(float time) { - auto system = (ParticleSystem*)_batchNode->getChildren()->getObjectAtIndex(1); + auto system = static_cast(_batchNode->getChildren().getObjectAtIndex(1)); _batchNode->reorderChild(system, system->getZOrder() - 1); } 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 1fb53b3142..3b1651912b 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 @@ -49c7ab76862a3db1b3f4d1ce08c3017f99dc9ed4 \ No newline at end of file +c26021c35e371ded3c70784e0809493cddad7908 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index 60f2581a55..a9b3c32f54 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp @@ -170,7 +170,7 @@ void KeyboardNotificationLayer::keyboardWillShow(IMEKeyboardNotificationInfo& in Point pos; for (int i = 0; i < count; ++i) { - node = children[i]; + node = children.getObjectAtIndex(i); pos = node->getPosition(); pos.y += adjustVert; node->setPosition(pos); From 3136ffc3dd233646361b7dbed48cc9a04b744e77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 29 Nov 2013 22:48:47 +0800 Subject: [PATCH 018/107] issue #2790: Adds CCValue.h/.cpp. --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/CCValue.cpp | 14 ++ cocos/2d/CCValue.h | 232 ++++++++++++++++++ 3 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 cocos/2d/CCValue.cpp create mode 100644 cocos/2d/CCValue.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 1f939cccfd..7f97ea4693 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -6c2f36e8a93d2fd99c6bd5ed3c2d37e8cf366ce5 \ No newline at end of file +6cd064b4af81704d1a587ac778250f108fc585e0 \ No newline at end of file diff --git a/cocos/2d/CCValue.cpp b/cocos/2d/CCValue.cpp new file mode 100644 index 0000000000..07327298b4 --- /dev/null +++ b/cocos/2d/CCValue.cpp @@ -0,0 +1,14 @@ +// +// CCValue.cpp +// cocos2d_libs +// +// Created by James Chen on 11/29/13. +// +// + +#include "CCValue.h" + +NS_CC_BEGIN + + +NS_CC_END diff --git a/cocos/2d/CCValue.h b/cocos/2d/CCValue.h new file mode 100644 index 0000000000..1c05e3fbcb --- /dev/null +++ b/cocos/2d/CCValue.h @@ -0,0 +1,232 @@ +/**************************************************************************** + 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 ArrayValue; +typedef std::unordered_map DictValue; + +class Value +{ +public: + Value() + : _type(Type::NONE) + { + + } + explicit Value(int v) + { + _baseData.intVal = v; + _type = Type::INTEGER; + } + explicit Value(float v) + { + _baseData.floatVal = v; + _type = Type::FLOAT; + } + explicit Value(double v) + { + _baseData.doubleVal = v; + _type = Type::DOUBLE; + } + explicit Value(bool v) + { + _baseData.boolVal = v; + _type = Type::BOOLEAN; + } + explicit Value(const std::string& v) + { + _strData = v; + _type = Type::STRING; + } + explicit Value(const ArrayValue& v) + { + _arrData = v; + _type = Type::ARRAY; + } + explicit Value(const DictValue& v) + { + _dictData = v; + _type = Type::DICTIONARY; + } + + Value(const Value& other) + { + *this = other; + } + Value(Value&& other) + { + *this = other; + } + + ~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::ARRAY: + _arrData = other._arrData; + break; + case Type::DICTIONARY: + _dictData = other._dictData; + break; + default: + break; + } + _type = other._type; + return *this; + } + + 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::ARRAY: + _arrData = other._arrData; + break; + case Type::DICTIONARY: + _dictData = other._dictData; + break; + default: + break; + } + _type = other._type; + return *this; + } + + int asInt() + { + CCASSERT(_type == Type::INTEGER, ""); + return _baseData.intVal; + } + + float asFloat() + { + CCASSERT(_type == Type::FLOAT, ""); + return _baseData.floatVal; + } + double asDouble() + { + CCASSERT(_type == Type::DOUBLE, ""); + return _baseData.doubleVal; + } + bool asBool() + { + CCASSERT(_type == Type::BOOLEAN, ""); + return _baseData.boolVal; + } + std::string asString() + { + CCASSERT(_type == Type::STRING, ""); + return _strData; + } + ArrayValue asArray() + { + CCASSERT(_type == Type::ARRAY, ""); + return _arrData; + } + DictValue asDict() + { + CCASSERT(_type == Type::DICTIONARY, ""); + return _dictData; + } + + enum class Type + { + NONE, + INTEGER, + FLOAT, + DOUBLE, + BOOLEAN, + STRING, + ARRAY, + DICTIONARY + }; + + inline Type getType() { return _type; }; + +private: + union + { + int intVal; + float floatVal; + double doubleVal; + bool boolVal; + }_baseData; + + std::string _strData; + ArrayValue _arrData; + DictValue _dictData; + + + Type _type; +}; + + +NS_CC_END + +#endif /* defined(__cocos2d_libs__CCValue__) */ From 8a435aa274984ef212efd990ccaf7fe997e7e964 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 2 Dec 2013 15:03:13 +0800 Subject: [PATCH 019/107] =?UTF-8?q?issue=20#2790:=20ArrayValue=20=E2=80=94?= =?UTF-8?q?>=20ValueArray,=20DictValue=20=E2=80=94>=20ValueDict.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCValue.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCValue.h b/cocos/2d/CCValue.h index 1c05e3fbcb..ffb80dd5c5 100644 --- a/cocos/2d/CCValue.h +++ b/cocos/2d/CCValue.h @@ -35,8 +35,8 @@ NS_CC_BEGIN class Value; -typedef std::vector ArrayValue; -typedef std::unordered_map DictValue; +typedef std::vector ValueArray; +typedef std::unordered_map ValueDict; class Value { @@ -71,12 +71,12 @@ public: _strData = v; _type = Type::STRING; } - explicit Value(const ArrayValue& v) + explicit Value(const ValueArray& v) { _arrData = v; _type = Type::ARRAY; } - explicit Value(const DictValue& v) + explicit Value(const ValueDict& v) { _dictData = v; _type = Type::DICTIONARY; @@ -184,12 +184,12 @@ public: CCASSERT(_type == Type::STRING, ""); return _strData; } - ArrayValue asArray() + ValueArray asArray() { CCASSERT(_type == Type::ARRAY, ""); return _arrData; } - DictValue asDict() + ValueDict asDict() { CCASSERT(_type == Type::DICTIONARY, ""); return _dictData; @@ -219,8 +219,8 @@ private: }_baseData; std::string _strData; - ArrayValue _arrData; - DictValue _dictData; + ValueArray _arrData; + ValueDict _dictData; Type _type; From 4ec6e50cc4a2ec25c4254511c72aedda19d52fc1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 14:47:35 +0800 Subject: [PATCH 020/107] issue #2790: Pure base data from Dictionary* to ValueDict, Array* to ValueArray. --- cocos/2d/CCAction.cpp | 1 + cocos/2d/CCActionInterval.cpp | 4 +- cocos/2d/CCAnimation.cpp | 11 +- cocos/2d/CCAnimation.h | 15 +- cocos/2d/CCAnimationCache.cpp | 131 +++++---- cocos/2d/CCAnimationCache.h | 12 +- cocos/2d/CCTMXLayer.cpp | 32 ++- cocos/2d/CCTMXLayer.h | 13 +- cocos/2d/CCTMXObjectGroup.cpp | 30 +- cocos/2d/CCTMXObjectGroup.h | 32 +-- cocos/2d/CCTMXTiledMap.cpp | 23 +- cocos/2d/CCTMXTiledMap.h | 19 +- cocos/2d/CCTMXXMLParser.cpp | 260 ++++++------------ cocos/2d/CCTMXXMLParser.h | 25 +- cocos/2d/CCTextureAtlas.cpp | 2 +- cocos/2d/CCValue.h | 192 +++++++++++-- cocos/2d/platform/CCFileUtils.cpp | 47 ++-- cocos/2d/platform/CCFileUtils.h | 45 ++- cocos/2d/platform/apple/CCFileUtilsApple.h | 6 +- cocos/2d/platform/apple/CCFileUtilsApple.mm | 211 +++++++------- cocos/base/CCArray.cpp | 2 +- cocos/base/CCDictionary.cpp | 68 ++++- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 11 +- .../Classes/TileMapTest/TileMapTest.cpp | 105 +++---- 24 files changed, 684 insertions(+), 613 deletions(-) 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/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 56c4c1a5f9..5cf1d8b17d 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -2108,8 +2108,8 @@ void Animate::update(float t) frameToDisplay = frame->getSpriteFrame(); static_cast(_target)->setDisplayFrame(frameToDisplay); - Dictionary* dict = frame->getUserInfo(); - if( dict ) + const ValueDict& dict = frame->getUserInfo(); + if ( !dict.empty() ) { //TODO: [[NSNotificationCenter defaultCenter] postNotificationName:AnimationFrameDisplayedNotification object:target_ userInfo:dict]; } diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 8a3df8d0e9..3c78c4659f 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -32,7 +32,7 @@ THE SOFTWARE. NS_CC_BEGIN -AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnits, Dictionary* userInfo) +AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo) { auto ret = new AnimationFrame(); if (ret && ret->initWithSpriteFrame(spriteFrame, delayUnits, userInfo)) @@ -54,7 +54,7 @@ AnimationFrame::AnimationFrame() } -bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, Dictionary* userInfo) +bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo) { setSpriteFrame(spriteFrame); setDelayUnits(delayUnits); @@ -68,7 +68,6 @@ AnimationFrame::~AnimationFrame() CCLOGINFO( "deallocing AnimationFrame: %p", this); CC_SAFE_RELEASE(_spriteFrame); - CC_SAFE_RELEASE(_userInfo); } AnimationFrame* AnimationFrame::clone() const @@ -77,7 +76,7 @@ AnimationFrame* AnimationFrame::clone() const auto frame = new AnimationFrame(); frame->initWithSpriteFrame(_spriteFrame->clone(), _delayUnits, - _userInfo != NULL ? _userInfo->clone() : NULL); + _userInfo); frame->autorelease(); return frame; @@ -126,7 +125,7 @@ bool Animation::initWithSpriteFrames(const Vector& frames, float d for (auto& spriteFrame : frames) { - auto animFrame = AnimationFrame::create(spriteFrame, 1, nullptr); + auto animFrame = AnimationFrame::create(spriteFrame, 1, ValueDict()); _frames.addObject(animFrame); _totalDelayUnits++; } @@ -165,7 +164,7 @@ Animation::~Animation(void) void Animation::addSpriteFrame(SpriteFrame* spriteFrame) { - AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, 1.0f, nullptr); + AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, 1.0f, ValueDict()); _frames.addObject(animFrame); // update duration diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 2725314004..72bc30ab0c 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -29,7 +29,7 @@ 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" @@ -61,7 +61,7 @@ public: * Creates the animation frame with a spriteframe, number of delay units and a notification user info * @since 3.0 */ - static AnimationFrame* create(SpriteFrame* spriteFrame, float delayUnits, Dictionary* userInfo); + static AnimationFrame* create(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo); SpriteFrame* getSpriteFrame() const { return _spriteFrame; }; @@ -81,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 ValueDict& getUserInfo() const { return _userInfo; }; + ValueDict& getUserInfo() { return _userInfo; }; /** Sets user infomation */ - void setUserInfo(Dictionary* userInfo) + void setUserInfo(const ValueDict& userInfo) { - CC_SAFE_RETAIN(userInfo); - CC_SAFE_RELEASE(_userInfo); _userInfo = userInfo; } @@ -107,7 +106,7 @@ protected: 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); + bool initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo); /** SpriteFrameName to be used */ SpriteFrame* _spriteFrame; @@ -116,7 +115,7 @@ 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; + ValueDict _userInfo; private: CC_DISALLOW_COPY_AND_ASSIGN(AnimationFrame); diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index e4cb5dc6b2..c7328aeadf 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -55,8 +55,6 @@ void AnimationCache::destroyInstance() bool AnimationCache::init() { - _animations = new Dictionary; - _animations->init(); return true; } @@ -68,12 +66,11 @@ AnimationCache::AnimationCache() 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.setObject(animation, name); } void AnimationCache::removeAnimation(const std::string& name) @@ -81,110 +78,108 @@ void AnimationCache::removeAnimation(const std::string& name) if (name.size()==0) return; - _animations->removeObjectForKey(name); + _animations.removeObjectForKey(name); } Animation* AnimationCache::getAnimation(const std::string& name) { - return (Animation*)_animations->objectForKey(name); + return _animations.getObjectForKey(name); } -void AnimationCache::parseVersion1(Dictionary* animations) +void AnimationCache::parseVersion1(const ValueDict& 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 ValueDict& animationDict = iter->second.asDict(); + const ValueArray& frameNames = animationDict.at("frames").asArray(); + 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; } - Vector frames(frameNames->count()); + Vector frames(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 = AnimationFrame::create(spriteFrame, 1, nullptr); + AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, ValueDict()); frames.addObject(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.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.", 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.count() != 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()); + AnimationCache::getInstance()->addAnimation(animation, iter->first.c_str()); } } -void AnimationCache::parseVersion2(Dictionary* animations) +void AnimationCache::parseVersion2(const ValueDict& 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; + const ValueDict& animationDict = iter->second.asDict(); - const String* loops = animationDict->valueForKey("loops"); - bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue(); + const Value& loops = animationDict.at("loops"); + bool restoreOriginalFrame = animationDict.at("restoreOriginalFrame").asBool(); - Array* frameArray = static_cast(animationDict->objectForKey("frames")); + const ValueArray& frameArray = animationDict.at("frames").asArray(); - 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 - Vector array(frameArray->count()); + Vector array(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(); + const ValueDict& entry = obj.asDict(); + std::string spriteFrameName = entry.at("spriteframe").asString(); SpriteFrame *spriteFrame = frameCache->getSpriteFrameByName(spriteFrameName); if( ! spriteFrame ) { - CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", name, spriteFrameName); + CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", name.c_str(), spriteFrameName.c_str()); continue; } - float delayUnits = entry->valueForKey("delayUnits")->floatValue(); - Dictionary* userInfo = (Dictionary*)entry->objectForKey("notification"); + float delayUnits = entry.at("delayUnits").asFloat(); + const Value& userInfo = entry.at("notification"); - AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo); + AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asDict()); array.addObject(animFrame); } - float delayPerUnit = animationDict->valueForKey("delayPerUnit")->floatValue(); - Animation *animation = Animation::create(array, delayPerUnit, 0 != loops->length() ? loops->intValue() : 1); + float delayPerUnit = animationDict.at("delayPerUnit").asFloat(); + Animation *animation = Animation::create(array, delayPerUnit, loops.getType() != Value::Type::NONE ? loops.asInt() : 1); animation->setRestoreOriginalFrame(restoreOriginalFrame); @@ -192,36 +187,34 @@ void AnimationCache::parseVersion2(Dictionary* animations) } } -void AnimationCache::addAnimationsWithDictionary(Dictionary* dictionary) +void AnimationCache::addAnimationsWithDictionary(const ValueDict& 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 ValueDict& properties = dictionary.at("properties").asDict(); + version = properties.at("format").asInt(); + const ValueArray& spritesheets = properties.at("spritesheets").asArray(); + + std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){ + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString()); + }); } switch (version) { case 1: - parseVersion1(animations); + parseVersion1(animations.asDict()); break; case 2: - parseVersion2(animations); + parseVersion2(animations.asDict()); break; default: CCASSERT(false, "Invalid animation format"); @@ -234,9 +227,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()); + ValueDict dict = FileUtils::getInstance()->fileToValueDict(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..5478eda3ff 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 ValueDict& 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 ValueDict& animations); + void parseVersion2(const ValueDict& animations); private: - Dictionary* _animations; + Map _animations; static AnimationCache* s_pSharedAnimationCache; }; diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index cfb6edbaf9..4d3f68ca77 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 @@ -119,7 +119,6 @@ TMXLayer::~TMXLayer() { CC_SAFE_RELEASE(_tileSet); CC_SAFE_RELEASE(_reusedTile); - CC_SAFE_RELEASE(_properties); if (_atlasIndexArray) { @@ -193,28 +192,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 +227,7 @@ void TMXLayer::parseInternalProperties() } else { - _vertexZvalue = vertexz->intValue(); + _vertexZvalue = vertexz.asInt(); } } } @@ -395,7 +394,7 @@ Sprite * TMXLayer::insertTileForGID(unsigned int gid, const Point& pos) Sprite* sp = static_cast(child); if (child) { - unsigned int ai = sp->getAtlasIndex(); + int ai = sp->getAtlasIndex(); if ( ai >= indexForZ ) { sp->setAtlasIndex(ai+1); @@ -406,6 +405,7 @@ Sprite * TMXLayer::insertTileForGID(unsigned int gid, const Point& pos) _tiles[z] = gid; return tile; } + Sprite * TMXLayer::updateTileForGID(unsigned int gid, const Point& pos) { Rect rect = _tileSet->rectForGID(gid); @@ -458,6 +458,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; @@ -468,6 +469,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 diff --git a/cocos/2d/CCTMXLayer.h b/cocos/2d/CCTMXLayer.h index b85de82c1e..41794f05b2 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 ValueDict& getProperties() const { return _properties; }; + inline ValueDict& getProperties() { return _properties; }; + inline void setProperties(const ValueDict& 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; + ValueDict _properties; }; // end of tilemap_parallax_nodes group diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index b232b2f807..9191ea6418 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -35,41 +35,37 @@ TMXObjectGroup::TMXObjectGroup() : _groupName("") , _positionOffset(Point::ZERO) { - _objects = Array::create(); - _objects->retain(); - _properties = new Dictionary(); - _properties->init(); } TMXObjectGroup::~TMXObjectGroup() { CCLOGINFO("deallocing TMXObjectGroup: %p", this); - CC_SAFE_RELEASE(_objects); - CC_SAFE_RELEASE(_properties); } -Dictionary* TMXObjectGroup::getObject(const char *objectName) const +ValueDict TMXObjectGroup::getObject(const std::string& objectName) const { - if (_objects && _objects->count() > 0) + if (_objects.size() > 0) { - Object* pObj = nullptr; - CCARRAY_FOREACH(_objects, pObj) + for (auto& v : _objects) { - Dictionary* pDict = static_cast(pObj); - String *name = static_cast(pDict->objectForKey("name")); - if (name && name->_string == objectName) + ValueDict dict = v.asDict(); + if (dict["name"].asString() == objectName) { - return pDict; + return dict; } } } + // object not found - return NULL; + return ValueDict(); } -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..b8a8f57f12 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; + ValueDict getObject(const std::string& objectName) const; - CC_DEPRECATED_ATTRIBUTE Dictionary* objectNamed(const char *objectName) const { return getObject(objectName); }; + CC_DEPRECATED_ATTRIBUTE ValueDict 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 ValueDict& getProperties() const { return _properties; }; + inline ValueDict& 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 ValueDict& properties) { _properties = properties; }; /** Gets the array of the objects */ - inline Array* getObjects() const { return _objects; }; + inline const ValueArray& getObjects() const { return _objects; }; + inline ValueArray& 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 ValueArray& objects) { _objects = objects; }; @@ -102,9 +100,9 @@ protected: /** offset position of child objects */ Point _positionOffset; /** list of properties stored in a dictionary */ - Dictionary* _properties; + ValueDict _properties; /** array of the objects */ - Array* _objects; + ValueArray _objects; }; // end of tilemap_parallax_nodes group diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 4980093eb7..5b16a3c43c 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -90,14 +90,11 @@ bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& r TMXTiledMap::TMXTiledMap() :_mapSize(Size::ZERO) ,_tileSize(Size::ZERO) - ,_properties(nullptr) - ,_tileProperties(nullptr) { } + TMXTiledMap::~TMXTiledMap() { - CC_SAFE_RELEASE(_properties); - CC_SAFE_RELEASE(_tileProperties); } // private @@ -165,13 +162,9 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) _objectGroups = mapInfo->getObjectGroups(); - 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; @@ -235,14 +228,20 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const 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 ac3c3c964a..d58a016c48 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; }; @@ -163,10 +164,8 @@ public: }; /** properties */ - inline Dictionary* getProperties() const { return _properties; }; - inline void setProperties(Dictionary* properties) { - CC_SAFE_RETAIN(properties); - CC_SAFE_RELEASE(_properties); + inline ValueDict& getProperties() { return _properties; }; + inline void setProperties(const ValueDict& properties) { _properties = properties; }; @@ -200,10 +199,10 @@ protected: /** object groups */ Vector _objectGroups; /** properties */ - Dictionary* _properties; + ValueDict _properties; //! tile properties - Dictionary* _tileProperties; + IntValueDict _tileProperties; private: CC_DISALLOW_COPY_AND_ASSIGN(TMXTiledMap); diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 1c273325dd..c3031b7af0 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -38,15 +38,6 @@ 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("") @@ -56,14 +47,11 @@ TMXLayerInfo::TMXLayerInfo() , _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); @@ -71,14 +59,12 @@ TMXLayerInfo::~TMXLayerInfo() } } -Dictionary * TMXLayerInfo::getProperties() +ValueDict TMXLayerInfo::getProperties() { return _properties; } -void TMXLayerInfo::setProperties(Dictionary* var) +void TMXLayerInfo::setProperties(ValueDict var) { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(_properties); _properties = var; } @@ -150,11 +136,6 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& _objectGroups.setCapacity(4); - _properties = new Dictionary(); - _properties->init(); - _tileProperties = new Dictionary(); - _tileProperties->init(); - // tmp vars _currentString = ""; _storingCharacters = false; @@ -179,8 +160,6 @@ TMXMapInfo::TMXMapInfo() , _tileSize(Size::ZERO) , _layerAttribs(0) , _storingCharacters(false) -, _properties(nullptr) -, _tileProperties(nullptr) , _currentFirstGID(0) { } @@ -188,8 +167,6 @@ TMXMapInfo::TMXMapInfo() TMXMapInfo::~TMXMapInfo() { CCLOGINFO("deallocing TMXMapInfo: %p", this); - CC_SAFE_RELEASE(_properties); - CC_SAFE_RELEASE(_tileProperties); } bool TMXMapInfo::parseXMLString(const std::string& xmlString) @@ -231,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(); + ValueDict 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") @@ -259,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" @@ -273,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 @@ -288,28 +265,28 @@ 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); @@ -322,7 +299,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); 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 @@ -355,40 +332,37 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else { TMXTilesetInfo* info = 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); - + pTMXMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt()); + //FIXME:XXX Why insert an empty dict? + pTMXMapInfo->getTileProperties().insert(std::make_pair(pTMXMapInfo->getParentGID(), Value())); 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); @@ -401,10 +375,10 @@ 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); @@ -419,7 +393,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) TMXTilesetInfo* tileset = pTMXMapInfo->getTilesets().getLastObject(); // build full path - std::string imagename = valueForKey("source", attributeDict); + std::string imagename = attributeDict["source"].asString(); if (_TMXFileName.find_last_of("/") != string::npos) { @@ -433,8 +407,8 @@ 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 == "") { @@ -485,56 +459,36 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) } else if (elementName == "object") { - char buffer[32] = {0}; TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().getLastObject(); // 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(); + ValueDict 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); @@ -545,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 = pTMXMapInfo->getLayers().getLastObject(); - String *value = new String(valueForKey("value", attributeDict)); - std::string key = valueForKey("name", attributeDict); + 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 = pTMXMapInfo->getObjectGroups().getLastObject(); - String *value = new String(valueForKey("value", attributeDict)); - const char* key = valueForKey("name", attributeDict); - objectGroup->getProperties()->setObject(value, key); - value->release(); - - } + 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 = pTMXMapInfo->getObjectGroups().getLastObject(); - Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject(); + ValueDict& dict = objectGroup->getObjects().rbegin()->asDict(); - 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()); + IntValueDict& dict = pTMXMapInfo->getTileProperties().at(pTMXMapInfo->getParentGID()).asIntKeyDict(); - 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 = _objectGroups.getLastObject(); - Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject(); + ValueDict& dict = objectGroup->getObjects().rbegin()->asDict(); // 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); + ValueArray pointsArray; + pointsArray.reserve(10); // parse points string into a space-separated set of points stringstream pointsStream(value); @@ -618,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(); + ValueDict 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 = _objectGroups.getLastObject(); - Dictionary* dict = (Dictionary*)objectGroup->getObjects()->getLastObject(); + ValueDict& dict = objectGroup->getObjects().rbegin()->asDict(); // 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); + ValueArray pointsArray; + pointsArray.reserve(10); // parse points string into a space-separated set of points stringstream pointsStream(value); @@ -671,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(); + ValueDict 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,16 +661,14 @@ void TMXMapInfo::endElement(void *ctx, const char *name) if( pTMXMapInfo->getLayerAttribs() & (TMXLayerAttribGzip | TMXLayerAttribZlib) ) { - unsigned char *deflated; + unsigned char *deflated = nullptr; Size s = layer->_layerSize; // int sizeHint = s.width * s.height * sizeof(uint32_t); int sizeHint = (int)(s.width * s.height * sizeof(unsigned int)); - int inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint); + int CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint); CCASSERT(inflatedLen == sizeHint, ""); - inflatedLen = (size_t)&inflatedLen; // XXX: to avoid warnings in compiler - free(buffer); buffer = nullptr; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 2644f8b413..ac61eb6028 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -29,11 +29,10 @@ 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 @@ -102,10 +101,10 @@ public: */ virtual ~TMXLayerInfo(); - void setProperties(Dictionary *properties); - Dictionary* getProperties(); + void setProperties(ValueDict properties); + ValueDict getProperties(); - Dictionary *_properties; + ValueDict _properties; std::string _name; Size _layerSize; unsigned int *_tiles; @@ -196,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); + IntValueDict& getTileProperties() { return _tileProperties; }; + void setTileProperties(const IntValueDict& tileProperties) { _tileProperties = tileProperties; }; @@ -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 ValueDict getProperties() const { return _properties; }; + inline void setProperties(ValueDict properties) { _properties = properties; }; @@ -307,7 +302,7 @@ protected: /// is storing characters? bool _storingCharacters; /// properties - Dictionary* _properties; + ValueDict _properties; //! tmx filename std::string _TMXFileName; @@ -316,7 +311,7 @@ protected: //! current string std::string _currentString; //! tile properties - Dictionary* _tileProperties; + IntValueDict _tileProperties; unsigned int _currentFirstGID; }; diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index ec42b9dbfd..39b2cd7d30 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -338,7 +338,7 @@ void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index) CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); // issue #575. index can be > totalQuads - unsigned int remaining = (_totalQuads-1) - index; + long remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining > 0) diff --git a/cocos/2d/CCValue.h b/cocos/2d/CCValue.h index ffb80dd5c5..a985fd6f3f 100644 --- a/cocos/2d/CCValue.h +++ b/cocos/2d/CCValue.h @@ -28,6 +28,7 @@ #include "CCPlatformMacros.h" #include "ccMacros.h" #include +#include #include #include @@ -37,6 +38,7 @@ class Value; typedef std::vector ValueArray; typedef std::unordered_map ValueDict; +typedef std::unordered_map IntValueDict; class Value { @@ -158,43 +160,190 @@ public: return *this; } - int asInt() + int asInt() const { - CCASSERT(_type == Type::INTEGER, ""); - return _baseData.intVal; + CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + 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 asFloat() + float asFloat() const { - CCASSERT(_type == Type::FLOAT, ""); - return _baseData.floatVal; + CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + 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 asDouble() + double asDouble() const { - CCASSERT(_type == Type::DOUBLE, ""); - return _baseData.doubleVal; + CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + 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 asBool() + bool asBool() const { - CCASSERT(_type == Type::BOOLEAN, ""); - return _baseData.boolVal; + CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + 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 asString() + + std::string asString() const { - CCASSERT(_type == Type::STRING, ""); - return _strData; + CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + + 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(); } - ValueArray asArray() + + ValueArray& asArray() { CCASSERT(_type == Type::ARRAY, ""); return _arrData; } - ValueDict asDict() + + const ValueArray& asArray() const + { + CCASSERT(_type == Type::ARRAY, ""); + return _arrData; + } + + ValueDict& asDict() { CCASSERT(_type == Type::DICTIONARY, ""); return _dictData; } + const ValueDict& asDict() const + { + CCASSERT(_type == Type::DICTIONARY, ""); + return _dictData; + } + + IntValueDict& asIntKeyDict() + { + CCASSERT(_type == Type::INT_KEY_DICT, ""); + return _intKeyDictData; + } + + bool isNull() const { return _type == Type::NONE; } + enum class Type { NONE, @@ -204,10 +353,11 @@ public: BOOLEAN, STRING, ARRAY, - DICTIONARY + DICTIONARY, + INT_KEY_DICT }; - inline Type getType() { return _type; }; + inline Type getType() const { return _type; }; private: union @@ -221,12 +371,14 @@ private: std::string _strData; ValueArray _arrData; ValueDict _dictData; - + IntValueDict _intKeyDictData; Type _type; }; + NS_CC_END + #endif /* defined(__cocos2d_libs__CCValue__) */ diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index ddd9c25dfe..03b867649e 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -25,7 +25,6 @@ THE SOFTWARE. #include "CCFileUtils.h" #include "CCDirector.h" #include "CCDictionary.h" -#include "CCString.h" #include "CCSAXParser.h" #include "tinyxml2.h" #include "unzip.h" @@ -59,16 +58,16 @@ class DictMaker : public SAXDelegator { public: SAXResult _resultType; - Array* _rootArray; - Dictionary *_rootDict; - Dictionary *_curDict; - std::stack _dictStack; + ValueArray _rootArray; + ValueDict _rootDict; + ValueDict _curDict; + std::stack _dictStack; std::string _curKey; ///< parsed key std::string _curValue; // parsed value SAXState _state; - Array* _array; + ValueArray _array; - std::stack _arrayStack; + std::stack _arrayStack; std::stack _stateStack; public: @@ -450,9 +449,9 @@ 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;} +ValueDict FileUtils::fileToValueDict(const std::string& filename) {return ValueDict();} +ValueArray FileUtils::fileToValueArray(const std::string& filename) {return ValueArray();} +bool FileUtils::writeToFile(ValueDict dict, const std::string &fullPath) {return false;} #endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */ @@ -472,7 +471,6 @@ FileUtils::FileUtils() FileUtils::~FileUtils() { - CC_SAFE_RELEASE(_filenameLookupDict); } @@ -564,12 +562,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 +732,10 @@ void FileUtils::addSearchPath(const std::string &searchpath) _searchPathArray.push_back(path); } -void FileUtils::setFilenameLookupDictionary(Dictionary* pFilenameLookupDict) +void FileUtils::setFilenameLookupDictionary(const ValueDict& filenameLookupDict) { _fullPathCache.clear(); - CC_SAFE_RELEASE(_filenameLookupDict); - _filenameLookupDict = pFilenameLookupDict; - CC_SAFE_RETAIN(_filenameLookupDict); + _filenameLookupDict = filenameLookupDict; } void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename) @@ -744,17 +743,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) + ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); + if (!dict.empty()) { - Dictionary* metadata = static_cast( dict->objectForKey("metadata") ); - int version = static_cast( metadata->objectForKey("version"))->intValue(); + ValueDict& metadata = dict["metadata"].asDict(); + int version = metadata["version"].asInt(); if (version != 1) { CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename.c_str()); return; } - setFilenameLookupDictionary( static_cast( dict->objectForKey("filenames")) ); + setFilenameLookupDictionary( dict["filenames"].asDict()); } } } diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 672e4b7234..ac3da377c3 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. */ @@ -189,7 +185,7 @@ public: * @param pFilenameLookupDict The dictionary for replacing filename. * @since v2.1 */ - virtual void setFilenameLookupDictionary(Dictionary* filenameLookupDict); + virtual void setFilenameLookupDictionary(const ValueDict& 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 ValueDict. + * @note This method is used internally. + */ + virtual ValueDict fileToValueDict(const std::string& filename); + + /** + * Write a ValueDict to a plist file. + * @note This method is used internally. + */ + virtual bool writeToFile(ValueDict dict, const std::string& fullPath); + + /** + * Converts the contents of a file to a ValueArray. + * @note This method is used internally. + */ + virtual ValueArray fileToValueArray(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; + ValueDict _filenameLookupDict; /** * The vector contains resolution folders. diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.h b/cocos/2d/platform/apple/CCFileUtilsApple.h index 5be1708df1..4adba6e63c 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 ValueDict fileToValueDict(const std::string& filename) override; + virtual bool writeToFile(ValueDict dict, const std::string& fullPath) override; - virtual Array* createArrayWithContentsOfFile(const std::string& filename) override; + virtual ValueArray fileToValueArray(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..62a96cf622 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, ValueDict& dict); +static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict); -static void addItemToArray(id item, Array *pArray) +static void addItemToArray(id item, ValueArray& 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]]) + { + ValueDict 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]]) + { + ValueArray 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::ARRAY) + { NSMutableArray *arrElement = [NSMutableArray array]; - Object *element = NULL; - CCARRAY_FOREACH(ccArray, element) - { - addObjectToNSArray(element, arrElement); - } + + ValueArray valueArray = value.asArray(); + + 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::DICTIONARY) + { NSMutableDictionary *dictElement = [NSMutableDictionary dictionary]; - DictElement *element = NULL; - CCDICT_FOREACH(ccDict, element) + + auto valueDict = value.asDict(); + 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, ValueDict& 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]]) + { + ValueDict 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]]) + { + ValueArray 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::DICTIONARY) + { NSMutableDictionary *dictElement = [NSMutableDictionary dictionary]; - DictElement *element = NULL; - CCDICT_FOREACH(ccDict, element) + ValueDict subDict = value.asDict(); + 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::ARRAY) + { NSMutableArray *arrElement = [NSMutableArray array]; - Object *element = NULL; - CCARRAY_FOREACH(ccArray, element) - { - addObjectToNSArray(element, arrElement); - } + + ValueArray array = value.asArray(); + + 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) +ValueDict FileUtilsApple::fileToValueDict(const std::string& filename) { std::string fullPath = fullPathForFilename(filename); NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:path]; + ValueDict 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(ValueDict 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) +ValueArray FileUtilsApple::fileToValueArray(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(); + ValueArray ret; for (id value in array) { diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index fdb96b2de9..6b06cd64f1 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -478,7 +478,7 @@ Array* Array::createWithContentsOfFile(const char* fileName) Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) { - return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); + return nullptr;//FIXME:XXX FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); } bool Array::init() diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 6b8df0febf..59306baa7f 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -377,9 +377,73 @@ Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) return srcDict->clone(); } +static Array* visitArray(const ValueArray& array); + +static Dictionary* visitDict(const ValueDict& dict) +{ + Dictionary* ret = new Dictionary(); + ret->init(); + + for (auto iter = dict.begin(); iter != dict.end(); ++iter) + { + if (iter->second.getType() == Value::Type::DICTIONARY) + { + const ValueDict& subDict = iter->second.asDict(); + auto sub = visitDict(subDict); + ret->setObject(sub, iter->first); + sub->release(); + } + else if (iter->second.getType() == Value::Type::ARRAY) + { + const ValueArray& arr = iter->second.asArray(); + 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 ValueArray& array) +{ + Array* ret = new Array(); + ret->init(); + + std::for_each(array.begin(), array.end(), [&ret](const Value& value){ + if (value.getType() == Value::Type::DICTIONARY) + { + const ValueDict& subDict = value.asDict(); + auto sub = visitDict(subDict); + ret->addObject(sub); + sub->release(); + } + else if (value.getType() == Value::Type::ARRAY) + { + const ValueArray& arr = value.asArray(); + 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()->fileToValueDict(pFileName)); } void Dictionary::acceptVisitor(DataVisitor &visitor) @@ -399,7 +463,7 @@ Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName) bool Dictionary::writeToFile(const char *fullPath) { - return FileUtils::getInstance()->writeToFile(this, fullPath); + return false;//FIXME: XXX FileUtils::getInstance()->writeToFile(this, fullPath); } Dictionary* Dictionary::clone() const diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp index bc2737edf6..d8a2766357 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"); + ValueDict 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(ValueDict()); FileUtilsDemo::onExit(); } @@ -298,7 +297,7 @@ void TestIsFileExist::onExit() FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset filename lookup - sharedFileUtils->setFilenameLookupDictionary(Dictionary::create()); + sharedFileUtils->setFilenameLookupDictionary(ValueDict()); FileUtilsDemo::onExit(); } diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index df3f3b522b..5f6b6fa13e 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -585,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; - + ValueDict& dict = obj.asDict(); ////----CCLOG("object: %x", dict); } @@ -609,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); + ValueDict& dict = obj.asDict(); - 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); } @@ -666,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; + ValueDict& dict = obj.asDict(); ////----CCLOG("object: %x", dict); } @@ -686,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(); + ValueDict& dict = obj.asDict(); + float x = dict["x"].asFloat(); + float y = dict["y"].asFloat(); + float width = dict["width"].asFloat(); + float height = dict["height"].asFloat(); glLineWidth(3); @@ -1096,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()); } } @@ -1479,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(); + ValueDict& dict = obj.asDict(); + + float x = dict["x"].asFloat(); + float y = dict["y"].asFloat(); + float width = dict["width"].asFloat(); + float height = dict["height"].asFloat(); glLineWidth(3); From 411136dd574844c04f1f0f5971e6582cd77fb021 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 15:29:23 +0800 Subject: [PATCH 021/107] =?UTF-8?q?issue=20#2790:=20Updates=20CCValue,=20s?= =?UTF-8?q?upports=20using=20=E2=80=98const=20char*=E2=80=99=20to=20constr?= =?UTF-8?q?uct=20a=20Value.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCValue.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cocos/2d/CCValue.h b/cocos/2d/CCValue.h index a985fd6f3f..f7bc2d61b4 100644 --- a/cocos/2d/CCValue.h +++ b/cocos/2d/CCValue.h @@ -68,6 +68,13 @@ public: _baseData.boolVal = v; _type = Type::BOOLEAN; } + + explicit Value(const char* v) + { + _strData = v; + _type = Type::STRING; + } + explicit Value(const std::string& v) { _strData = v; From 1164176bed3e57c5da5db17414ab895972cbbe80 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 15:31:36 +0800 Subject: [PATCH 022/107] =?UTF-8?q?issue=20#2790:=20NULL=20=E2=80=94>=20nu?= =?UTF-8?q?llptr=20in=20CCParticleSystem.cpp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCParticleSystem.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 53fa60625f..3aa138bbc3 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -198,9 +198,9 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary) bool ParticleSystem::initWithDictionary(Dictionary *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(); @@ -393,11 +393,11 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin { // 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"); + CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData"); CC_BREAK_IF(!buffer); int deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated); - CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); + CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage() From 2d6e6dbdb0606d0b2d4b5778971385b6fcdf6cd1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 15:32:20 +0800 Subject: [PATCH 023/107] issue #2790: Assert fix for Vector::insertObject. --- cocos/base/CCVector.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 31554a3c8c..91e21d361a 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -199,7 +199,7 @@ public: /** Insert a certain object at a certain index */ void insertObject(T object, long index) { - CCASSERT(index >= 0 && index < count(), "Invalid index!"); + CCASSERT(index >= 0 && index <= count(), "Invalid index!"); _data.insert((std::begin(_data) + index), object); object->retain(); } From 2e0489a49c98807e4603f0eec2e0d4b7c3f051d6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 15:41:01 +0800 Subject: [PATCH 024/107] issue #2790: Uses ValueDict instead of Dictionary* for ParticleSystem. --- cocos/2d/CCParticleSystem.cpp | 137 +++++++++++++++++----------------- cocos/2d/CCParticleSystem.h | 6 +- 2 files changed, 70 insertions(+), 73 deletions(-) diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 3aa138bbc3..b8a1256f1b 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()); + ValueDict dict = FileUtils::getInstance()->fileToValueDict(_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,17 +185,15 @@ bool ParticleSystem::initWithFile(const std::string& plistFile) bRet = this->initWithDictionary(dict, ""); } - dict->release(); - return bRet; } -bool ParticleSystem::initWithDictionary(Dictionary *dictionary) +bool ParticleSystem::initWithDictionary(ValueDict& dictionary) { return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::string& dirname) +bool ParticleSystem::initWithDictionary(ValueDict& dictionary, const std::string& dirname) { bool bRet = false; unsigned char *buffer = nullptr; @@ -203,95 +201,94 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin 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,14 +382,14 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin } else { - const char *textureData = dictionary->valueForKey("textureImageData")->getCString(); - CCASSERT(textureData, ""); + std::string textureData = dictionary["textureImageData"].asString(); + CCASSERT(!textureData.empty(), ""); - long dataLen = strlen(textureData); - if(dataLen != 0) + long dataLen = textureData.size(); + if (dataLen != 0) { // if it fails, try to get it from the base64-gzipped data - int decodeLen = base64Decode((unsigned char*)textureData, (unsigned int)dataLen, &buffer); + int decodeLen = base64Decode((unsigned char*)textureData.c_str(), (unsigned int)dataLen, &buffer); CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData"); CC_BREAK_IF(!buffer); @@ -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..c5674ba7bb 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(ValueDict& 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(ValueDict& dictionary, const std::string& dirname); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(int numberOfParticles); From 9881ab2178502619a50c7ed1e465df62d9478e6c Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 16:20:41 +0800 Subject: [PATCH 025/107] issue #2790: Uses cocos2d::Map and ValueDict for SpriteFrameCache. --- cocos/2d/CCSpriteFrameCache.cpp | 178 +++++++++++++++----------------- cocos/2d/CCSpriteFrameCache.h | 16 +-- 2 files changed, 92 insertions(+), 102 deletions(-) diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 80cff587b5..828974cfdc 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.setCapacity(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(ValueDict& dictionary, Texture2D* texture) { /* Supported Zwoptex Formats: @@ -90,25 +86,24 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+ */ - Dictionary *metadataDict = (Dictionary*)dictionary->objectForKey("metadata"); - Dictionary *framesDict = (Dictionary*)dictionary->objectForKey("frames"); + ValueDict& metadataDict = dictionary["metadata"].asDict(); + ValueDict& framesDict = dictionary["frames"].asDict(); int format = 0; // get the format - if(metadataDict != NULL) + if (!metadataDict.empty()) { - format = metadataDict->valueForKey("format")->intValue(); + format = metadataDict["format"].asInt(); } // check the format CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); - DictElement* element = NULL; - CCDICT_FOREACH(framesDict, element) + for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter) { - Dictionary* frameDict = static_cast(element->getObject()); - std::string spriteFrameName = element->getStrKey(); - SpriteFrame* spriteFrame = static_cast(_spriteFrames->objectForKey(spriteFrameName)); + ValueDict& frameDict = iter->second.asDict(); + std::string spriteFrameName = iter->first; + SpriteFrame* spriteFrame = _spriteFrames.getObjectForKey(spriteFrameName); if (spriteFrame) { continue; @@ -116,14 +111,14 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex if(format == 0) { - float x = frameDict->valueForKey("x")->floatValue(); - float y = frameDict->valueForKey("y")->floatValue(); - float w = frameDict->valueForKey("width")->floatValue(); - float h = frameDict->valueForKey("height")->floatValue(); - float ox = frameDict->valueForKey("offsetX")->floatValue(); - float oy = frameDict->valueForKey("offsetY")->floatValue(); - int ow = frameDict->valueForKey("originalWidth")->intValue(); - int oh = frameDict->valueForKey("originalHeight")->intValue(); + float x = frameDict["x"].asFloat(); + float y = frameDict["y"].asFloat(); + float w = frameDict["width"].asFloat(); + float h = frameDict["height"].asFloat(); + float ox = frameDict["offsetX"].asFloat(); + float oy = frameDict["offsetY"].asFloat(); + int ow = frameDict["originalWidth"].asInt(); + int oh = frameDict["originalHeight"].asInt(); // check ow/oh if(!ow || !oh) { @@ -134,7 +129,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex oh = abs(oh); // create frame spriteFrame = new SpriteFrame(); - spriteFrame->initWithTexture(pobTexture, + spriteFrame->initWithTexture(texture, Rect(x, y, w, h), false, Point(ox, oy), @@ -143,21 +138,21 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex } else if(format == 1 || format == 2) { - Rect frame = RectFromString(frameDict->valueForKey("frame")->getCString()); + Rect frame = RectFromString(frameDict["frame"].asString()); bool rotated = false; // rotation if (format == 2) { - rotated = frameDict->valueForKey("rotated")->boolValue(); + rotated = frameDict["rotated"].asBool(); } - Point offset = PointFromString(frameDict->valueForKey("offset")->getCString()); - Size sourceSize = SizeFromString(frameDict->valueForKey("sourceSize")->getCString()); + Point offset = PointFromString(frameDict["offset"].asString()); + Size sourceSize = SizeFromString(frameDict["sourceSize"].asString()); // create frame spriteFrame = new SpriteFrame(); - spriteFrame->initWithTexture(pobTexture, + spriteFrame->initWithTexture(texture, frame, rotated, offset, @@ -167,31 +162,28 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex else if (format == 3) { // get values - Size spriteSize = SizeFromString(frameDict->valueForKey("spriteSize")->getCString()); - Point spriteOffset = PointFromString(frameDict->valueForKey("spriteOffset")->getCString()); - Size spriteSourceSize = SizeFromString(frameDict->valueForKey("spriteSourceSize")->getCString()); - Rect textureRect = RectFromString(frameDict->valueForKey("textureRect")->getCString()); - bool textureRotated = frameDict->valueForKey("textureRotated")->boolValue(); + Size spriteSize = SizeFromString(frameDict["spriteSize"].asString()); + Point spriteOffset = PointFromString(frameDict["spriteOffset"].asString()); + Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString()); + Rect textureRect = RectFromString(frameDict["textureRect"].asString()); + bool textureRotated = frameDict["textureRotated"].asBool(); // get aliases - Array* aliases = (Array*) (frameDict->objectForKey("aliases")); - String * frameKey = new String(spriteFrameName); + ValueArray& aliases = frameDict["aliases"].asArray(); - 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 +191,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex } // add sprite frame - _spriteFrames->setObject(spriteFrame, spriteFrameName); + _spriteFrames.setObject(spriteFrame, spriteFrameName); spriteFrame->release(); } } @@ -207,10 +199,9 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); - Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); + ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); addSpriteFramesWithDictionary(dict, pobTexture); - dict->release(); } void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) @@ -235,18 +226,18 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end()) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); - Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); + ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); string texturePath(""); - Dictionary* metadataDict = static_cast( dict->objectForKey("metadata") ); - if (metadataDict) + ValueDict& metadataDict = dict["metadata"].asDict(); + if (!metadataDict.empty()) { // try to read texture file name from meta data - texturePath = metadataDict->valueForKey("textureFileName")->getCString(); + texturePath = metadataDict["textureFileName"].asString(); } - if (! texturePath.empty()) + if (!texturePath.empty()) { // build texture path relative to plist file texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath.c_str(), pszPlist); @@ -277,37 +268,39 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) { CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture"); } - dict->release(); } } void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const std::string& pszFrameName) { - _spriteFrames->setObject(pobFrame, pszFrameName); + _spriteFrames.setObject(pobFrame, pszFrameName); } -void SpriteFrameCache::removeSpriteFrames(void) +void SpriteFrameCache::removeSpriteFrames() { - _spriteFrames->removeAllObjects(); - _spriteFramesAliases->removeAllObjects(); + _spriteFrames.removeAllObjects(); + _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.removeObjectsForKeys(toRemoveFrames); + // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache if( bRemoved ) { @@ -323,16 +316,16 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) return; // Is this an alias ? - String* key = (String*)_spriteFramesAliases->objectForKey(name); + std::string key = _spriteFramesAliases[name].asString(); - if (key) + if (!key.empty()) { - _spriteFrames->removeObjectForKey(key->getCString()); - _spriteFramesAliases->removeObjectForKey(key->getCString()); + _spriteFrames.removeObjectForKey(key); + _spriteFramesAliases.erase(key); } else { - _spriteFrames->removeObjectForKey(name); + _spriteFrames.removeObjectForKey(name); } // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache @@ -342,13 +335,13 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); - Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); - if (dict == nullptr) + ValueDict dict = FileUtils::getInstance()->fileToValueDict(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 +349,52 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { _loadedFileNames->erase(ret); } - dict->release(); } -void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary) +void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueDict& dictionary) { - Dictionary* framesDict = static_cast(dictionary->objectForKey("frames")); - Array* keysToRemove = Array::create(); + ValueDict framesDict = dictionary["frames"].asDict(); + 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.getObjectForKey(iter->first)) { - keysToRemove->addObject(String::create(element->getStrKey())); + keysToRemove.push_back(iter->first); } } - _spriteFrames->removeObjectsForKeys(keysToRemove); + _spriteFrames.removeObjectsForKeys(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.getObjectForKey(key); if (frame && (frame->getTexture() == texture)) { - keysToRemove->addObject(String::create(element->getStrKey())); + keysToRemove.push_back(key); } } - _spriteFrames->removeObjectsForKeys(keysToRemove); + _spriteFrames.removeObjectsForKeys(keysToRemove); } SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) { - SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(name); + SpriteFrame* frame = _spriteFrames.getObjectForKey(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.getObjectForKey(key); + if (!frame) { CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str()); } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 11733fa0ff..7ce42d8871 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; /** @@ -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(ValueDict& dictionary, Texture2D *texture); /** Removes multiple Sprite Frames from Dictionary. * @since v0.99.5 */ - void removeSpriteFramesFromDictionary(Dictionary* dictionary); + void removeSpriteFramesFromDictionary(ValueDict& dictionary); protected: - Dictionary* _spriteFrames; - Dictionary* _spriteFramesAliases; + Map _spriteFrames; + ValueDict _spriteFramesAliases; std::set* _loadedFileNames; }; From 3fc5fffd2634286aed1e5c973096cd1053b8493a Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 16:21:16 +0800 Subject: [PATCH 026/107] =?UTF-8?q?issue=20#2790:=20const=20char*=20?= =?UTF-8?q?=E2=80=94>=20const=20std::string&=20=20=20for=20CCNS.h/.cpp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCNS.cpp | 18 +++++++++--------- cocos/base/CCNS.h | 6 +++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cocos/base/CCNS.cpp b/cocos/base/CCNS.cpp index 8cf496c0b1..f2f39e1173 100644 --- a/cocos/base/CCNS.cpp +++ b/cocos/base/CCNS.cpp @@ -53,16 +53,16 @@ static inline void split(std::string src, const char* token, strArray& vect) // if the form is right,the string will be split into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. -static bool splitWithForm(const char* pStr, strArray& strs) +static bool splitWithForm(const std::string& str, strArray& strs) { bool bRet = false; do { - CC_BREAK_IF(!pStr); + CC_BREAK_IF(str.empty()); // string is empty - std::string content = pStr; + std::string content = str; CC_BREAK_IF(content.length() == 0); int nPosLeft = content.find('{'); @@ -97,14 +97,14 @@ static bool splitWithForm(const char* pStr, strArray& strs) // implement the functions -Rect RectFromString(const char* pszContent) +Rect RectFromString(const std::string& str) { Rect result = Rect::ZERO; do { - CC_BREAK_IF(!pszContent); - std::string content = pszContent; + CC_BREAK_IF(str.empty()); + std::string content = str; // find the first '{' and the third '}' int nPosLeft = content.find('{'); @@ -146,14 +146,14 @@ Rect RectFromString(const char* pszContent) return result; } -Point PointFromString(const char* pszContent) +Point PointFromString(const std::string& str) { Point ret = Point::ZERO; do { strArray strs; - CC_BREAK_IF(!splitWithForm(pszContent, strs)); + CC_BREAK_IF(!splitWithForm(str, strs)); float x = (float) atof(strs[0].c_str()); float y = (float) atof(strs[1].c_str()); @@ -164,7 +164,7 @@ Point PointFromString(const char* pszContent) return ret; } -Size SizeFromString(const char* pszContent) +Size SizeFromString(const std::string& pszContent) { Size ret = Size::ZERO; 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 /// @} From 5eb9446b802ddbcad9bee2b732c93e23a283dbe0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 16:21:55 +0800 Subject: [PATCH 027/107] =?UTF-8?q?issue=20#2790:=20Uses=20const=20referen?= =?UTF-8?q?ce=20instead=20of=20value=20for=20std::for=5Feach=20=E2=80=99s?= =?UTF-8?q?=20argument.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCMap.h | 2 +- cocos/base/CCVector.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 540bd11afa..36715ab4f1 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -150,7 +150,7 @@ public: void removeObjectsForKeys(const std::vector& keys) { - std::for_each(keys.cbegin(), keys.cend(), [this](K key){ + std::for_each(keys.cbegin(), keys.cend(), [this](const K& key){ removeObjectForKey(key); }); } diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 91e21d361a..4a51a43669 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -312,7 +312,7 @@ public: if (count() <= 0) return; - std::for_each(_data.cbegin(), _data.cend(), [&callback](T obj){ + std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){ callback(obj); }); } @@ -322,7 +322,7 @@ public: if (count() <= 0) return; - std::for_each(_data.crbegin(), _data.crend(), [&callback](T obj){ + std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){ callback(obj); }); } From f01f56113cf951e47fcbf2a313bc6e1a7c770902 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 16:24:24 +0800 Subject: [PATCH 028/107] =?UTF-8?q?issue=20#2790:=20Don=E2=80=99t=20make?= =?UTF-8?q?=20an=20assert=20if=20converting=20Value=20failed.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCValue.h | 5 ----- 1 file changed, 5 deletions(-) diff --git a/cocos/2d/CCValue.h b/cocos/2d/CCValue.h index f7bc2d61b4..6e385bf2d8 100644 --- a/cocos/2d/CCValue.h +++ b/cocos/2d/CCValue.h @@ -321,31 +321,26 @@ public: ValueArray& asArray() { - CCASSERT(_type == Type::ARRAY, ""); return _arrData; } const ValueArray& asArray() const { - CCASSERT(_type == Type::ARRAY, ""); return _arrData; } ValueDict& asDict() { - CCASSERT(_type == Type::DICTIONARY, ""); return _dictData; } const ValueDict& asDict() const { - CCASSERT(_type == Type::DICTIONARY, ""); return _dictData; } IntValueDict& asIntKeyDict() { - CCASSERT(_type == Type::INT_KEY_DICT, ""); return _intKeyDictData; } From 5c60f66c63a65cf2f14119bd669fa204a8e71c9f Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 3 Dec 2013 17:15:48 +0800 Subject: [PATCH 029/107] =?UTF-8?q?issue=20#2790:=20Menu::itemForTouch=20?= =?UTF-8?q?=E2=80=94>=20Menu::getItemForTouch.=20=20=20Array*=20=E2=80=94>?= =?UTF-8?q?=20ValueArray.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCMenu.cpp | 65 +++++++++++++++++---------------------------- cocos/2d/CCMenu.h | 7 ++--- 2 files changed, 28 insertions(+), 44 deletions(-) diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index fa44b28630..1c0988af58 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, @@ -238,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; @@ -278,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) @@ -360,31 +347,29 @@ void Menu::alignItemsInColumns(int columns, ...) void Menu::alignItemsInColumns(int columns, va_list args) { CCASSERT(columns >= 0, "Columns must be >= 0"); - Array* rows = Array::create(); + ValueArray 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 ValueArray& 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; _children.forEach([&](Node* child){ if (child) { CCASSERT(row < rows.size(), ""); - rowColumns = rows[row]; + rowColumns = rows[row].asInt(); // can not have zero columns on a row CCASSERT(rowColumns, ""); @@ -422,7 +407,7 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray) { if (rowColumns == 0) { - rowColumns = rows[row]; + rowColumns = rows[row].asInt(); w = winSize.width / (1 + rowColumns); x = w; } @@ -462,28 +447,26 @@ void Menu::alignItemsInRows(int rows, ...) void Menu::alignItemsInRows(int rows, va_list args) { - Array* pArray = Array::create(); + ValueArray 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 ValueArray& 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; _children.forEach([&](Node* child){ if (child) @@ -491,7 +474,7 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray) // check if too many menu items for the amount of rows/columns CCASSERT(column < columns.size(), ""); - columnRows = columns[column]; + columnRows = columns[column].asInt(); // can't have zero rows on a column CCASSERT(columnRows, ""); @@ -532,7 +515,7 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray) { if (columnRows == 0) { - columnRows = columns[column]; + columnRows = columns[column].asInt(); y = (float) columnHeights[column]; } @@ -558,7 +541,7 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray) }); } -MenuItem* Menu::itemForTouch(Touch *touch) +MenuItem* Menu::getItemForTouch(Touch *touch) { Point touchLocation = touch->getLocation(); diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index ad285fbadb..c5ad4e3fd7 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -29,6 +29,7 @@ THE SOFTWARE. #include "CCLayer.h" #include "CCVector.h" #include "CCEventTouch.h" +#include "CCValue.h" NS_CC_BEGIN @@ -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 ValueArray& 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 ValueArray& columns); virtual bool isEnabled() const { return _enabled; } virtual void setEnabled(bool value) { _enabled = value; }; @@ -134,7 +135,7 @@ protected: /** whether or not the menu will receive events */ bool _enabled; - MenuItem* itemForTouch(Touch * touch); + MenuItem* getItemForTouch(Touch * touch); State _state; MenuItem *_selectedItem; From 35b96602d35626d12d945d4655b14352804157aa Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 10:32:42 +0800 Subject: [PATCH 030/107] issue #2790: includes for std::for_each. --- cocos/base/CCDictionary.cpp | 1 + cocos/base/CCMap.h | 1 + cocos/base/CCVector.h | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 59306baa7f..cf9ea4b184 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; diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 36715ab4f1..823307d58b 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -27,6 +27,7 @@ THE SOFTWARE. #include #include +#include // std::for_each NS_CC_BEGIN diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 4a51a43669..960b98cd48 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CCVECTOR_H__ #include -#include +#include // std::for_each #include "ccMacros.h" NS_CC_BEGIN From 76896d70d0e5a7876bcd492382c5bee89123e1b8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 10:33:27 +0800 Subject: [PATCH 031/107] issue #2790: Android build was ok, fixes some warnings. --- cocos/2d/CCAnimation.cpp | 1 - cocos/2d/CCAnimationCache.cpp | 1 - cocos/2d/CCLabel.cpp | 2 +- cocos/2d/CCMenuItem.h | 1 - cocos/2d/CCSpriteFrameCache.h | 2 +- cocos/2d/CCTMXLayer.cpp | 1 - cocos/2d/CCValue.h | 107 +++++++++--- cocos/2d/cocos2d.h | 1 + cocos/2d/platform/CCFileUtils.cpp | 180 ++++++++++---------- cocos/2d/platform/CCFileUtils.h | 2 +- cocos/2d/platform/CCSAXParser.cpp | 1 - cocos/2d/platform/CCSAXParser.h | 1 + cocos/2d/platform/apple/CCFileUtilsApple.h | 2 +- cocos/2d/platform/apple/CCFileUtilsApple.mm | 2 +- 14 files changed, 177 insertions(+), 127 deletions(-) diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 3c78c4659f..144294bcff 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -49,7 +49,6 @@ AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnit AnimationFrame::AnimationFrame() : _spriteFrame(NULL) , _delayUnits(0.0f) -, _userInfo(NULL) { } diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index c7328aeadf..592b659d1a 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -59,7 +59,6 @@ bool AnimationCache::init() } AnimationCache::AnimationCache() -: _animations(NULL) { } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index f6e980d719..54427e9c43 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -373,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)); } diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 006cb3d0a7..e07c1a6b94 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -511,7 +511,6 @@ protected: */ MenuItemToggle() : _selectedIndex(0) - , _subItems(NULL) {} /** * @js NA diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 7ce42d8871..066716a94a 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -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: /** diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 4d3f68ca77..ed11ad55f6 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -112,7 +112,6 @@ TMXLayer::TMXLayer() ,_tiles(NULL) ,_tileSet(NULL) ,_layerOrientation(TMXOrientationOrtho) -,_properties(NULL) {} TMXLayer::~TMXLayer() diff --git a/cocos/2d/CCValue.h b/cocos/2d/CCValue.h index 6e385bf2d8..174e01d431 100644 --- a/cocos/2d/CCValue.h +++ b/cocos/2d/CCValue.h @@ -35,7 +35,6 @@ NS_CC_BEGIN class Value; - typedef std::vector ValueArray; typedef std::unordered_map ValueDict; typedef std::unordered_map IntValueDict; @@ -44,65 +43,109 @@ class Value { public: Value() - : _type(Type::NONE) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::NONE) { } explicit Value(int v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::INTEGER) { _baseData.intVal = v; - _type = Type::INTEGER; } explicit Value(float v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::FLOAT) { _baseData.floatVal = v; - _type = Type::FLOAT; } explicit Value(double v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::DOUBLE) { _baseData.doubleVal = v; - _type = Type::DOUBLE; } explicit Value(bool v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::BOOLEAN) { _baseData.boolVal = v; - _type = Type::BOOLEAN; } explicit Value(const char* v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::STRING) { _strData = v; - _type = Type::STRING; } explicit Value(const std::string& v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::STRING) { _strData = v; - _type = Type::STRING; } explicit Value(const ValueArray& v) + : _arrData(new ValueArray()) + , _dictData(nullptr) + , _intKeyDictData(nullptr) + , _type(Type::ARRAY) { - _arrData = v; - _type = Type::ARRAY; + *_arrData = v; } explicit Value(const ValueDict& v) + : _arrData(nullptr) + , _dictData(new ValueDict()) + , _intKeyDictData(nullptr) + , _type(Type::DICTIONARY) { - _dictData = v; - _type = Type::DICTIONARY; + *_dictData = v; + } + + explicit Value(const IntValueDict& v) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(new IntValueDict()) + , _type(Type::INT_KEY_DICT) + { + *_intKeyDictData = v; } Value(const Value& other) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) { *this = other; } Value(Value&& other) + : _arrData(nullptr) + , _dictData(nullptr) + , _intKeyDictData(nullptr) { - *this = other; + *this = std::move(other); } ~Value() { - + CC_SAFE_DELETE(_arrData); + CC_SAFE_DELETE(_dictData); + CC_SAFE_DELETE(_intKeyDictData); } Value& operator= (const Value& other) @@ -124,10 +167,13 @@ public: _strData = other._strData; break; case Type::ARRAY: - _arrData = other._arrData; + *_arrData = *other._arrData; break; case Type::DICTIONARY: - _dictData = other._dictData; + *_dictData = *other._dictData; + break; + case Type::INT_KEY_DICT: + *_intKeyDictData = *other._intKeyDictData; break; default: break; @@ -155,14 +201,25 @@ public: _strData = other._strData; break; case Type::ARRAY: + CC_SAFE_DELETE(_arrData); _arrData = other._arrData; break; case Type::DICTIONARY: + CC_SAFE_DELETE(_dictData); _dictData = other._dictData; break; + case Type::INT_KEY_DICT: + CC_SAFE_DELETE(_intKeyDictData); + _intKeyDictData = other._intKeyDictData; + break; default: break; } + + _arrData = nullptr; + _dictData = nullptr; + _intKeyDictData = nullptr; + _type = other._type; return *this; } @@ -321,27 +378,27 @@ public: ValueArray& asArray() { - return _arrData; + return *_arrData; } const ValueArray& asArray() const { - return _arrData; + return *_arrData; } ValueDict& asDict() { - return _dictData; + return *_dictData; } const ValueDict& asDict() const { - return _dictData; + return *_dictData; } IntValueDict& asIntKeyDict() { - return _intKeyDictData; + return *_intKeyDictData; } bool isNull() const { return _type == Type::NONE; } @@ -371,15 +428,13 @@ private: }_baseData; std::string _strData; - ValueArray _arrData; - ValueDict _dictData; - IntValueDict _intKeyDictData; + ValueArray* _arrData; + ValueDict* _dictData; + IntValueDict* _intKeyDictData; Type _type; }; - - NS_CC_END diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index e18bee1c4e..bcfe8d7cf8 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -72,6 +72,7 @@ THE SOFTWARE. #include "CCString.h" #include "CCNS.h" #include "CCData.h" +#include "CCValue.h" // draw nodes #include "CCDrawingPrimitives.h" diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 03b867649e..63a2673a7b 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCFileUtils.h" +#include "ccMacros.h" #include "CCDirector.h" -#include "CCDictionary.h" #include "CCSAXParser.h" #include "tinyxml2.h" #include "unzip.h" @@ -72,12 +72,7 @@ public: public: DictMaker() - : _resultType(SAX_RESULT_NONE), - _rootArray(NULL), - _rootDict(NULL), - _curDict(NULL), - _state(SAX_NONE), - _array(NULL) + : _resultType(SAX_RESULT_NONE) { } @@ -85,30 +80,24 @@ public: { } - Dictionary* dictionaryWithContentsOfFile(const char *pFileName) + ValueDict& 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; } - Array* arrayWithContentsOfFile(const char* pFileName) + ValueArray& 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); @@ -122,12 +111,9 @@ public: std::string sName((char*)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(); } _state = SAX_DICT; @@ -140,18 +126,15 @@ public: if (SAX_ARRAY == preState) { // add the dictionary into the array - _array->addObject(_curDict); + _array.push_back(Value(_curDict)); } else if (SAX_DICT == preState) { // add the dictionary into the pre dictionary CCASSERT(! _dictStack.empty(), "The state is wrong!"); - Dictionary* pPreDict = _dictStack.top(); - pPreDict->setObject(_curDict, _curKey.c_str()); + ValueDict& pPreDict = _dictStack.top(); + pPreDict[_curKey] = Value(_curDict); } - - _curDict->release(); - // record the dict state _stateStack.push(_state); _dictStack.push(_curDict); @@ -175,12 +158,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(); } SAXState preState = SAX_NONE; if (! _stateStack.empty()) @@ -190,15 +171,14 @@ public: if (preState == SAX_DICT) { - _curDict->setObject(_array, _curKey.c_str()); + _curDict[_curKey] = Value(_array); } else if (preState == SAX_ARRAY) { CCASSERT(! _arrayStack.empty(), "The state is wrong!"); - Array* pPreArray = _arrayStack.top(); - pPreArray->addObject(_array); + ValueArray& pPreArray = _arrayStack.top(); + pPreArray.push_back(Value(_array)); } - _array->release(); // record the array state _stateStack.push(_state); _arrayStack.push(_array); @@ -234,44 +214,47 @@ public: } else if (sName == "true") { - String *str = new String("1"); if (SAX_ARRAY == curState) { - _array->addObject(str); + _array.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); + _array.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") + _array.push_back(Value(_curValue)); + else if (sName == "integer") + _array.push_back(Value(atoi(_curValue.c_str()))); + else + _array.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(); } @@ -287,12 +270,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: @@ -303,49 +286,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) +ValueDict FileUtils::fileToValueDict(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) +ValueArray FileUtils::fileToValueArray(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(ValueArray& array, tinyxml2::XMLDocument *pDoc); +static tinyxml2::XMLElement* generateElementForDict(ValueDict& dict, tinyxml2::XMLDocument *pDoc); /* * Use tinyxml2 to write plist files */ -bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) +bool FileUtils::writeToFile(ValueDict& 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; @@ -357,7 +339,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; @@ -365,7 +347,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; @@ -381,46 +363,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::ARRAY) + return generateElementForArray(value.asArray(), pDoc); // object is Dictionary - if (Dictionary *innerDict = dynamic_cast(object)) - return generateElementForDict(innerDict, pDoc); + if (value.getType() == Value::Type::DICTIONARY) + return generateElementForDict(value.asDict(), 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(ValueDict& 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); } @@ -430,17 +430,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(ValueArray& 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; } @@ -451,12 +450,12 @@ NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ ValueDict FileUtils::fileToValueDict(const std::string& filename) {return ValueDict();} ValueArray FileUtils::fileToValueArray(const std::string& filename) {return ValueArray();} -bool FileUtils::writeToFile(ValueDict dict, const std::string &fullPath) {return false;} +bool FileUtils::writeToFile(ValueDict& 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() @@ -465,7 +464,6 @@ void FileUtils::destroyInstance() } FileUtils::FileUtils() -: _filenameLookupDict(NULL) { } @@ -488,8 +486,8 @@ void FileUtils::purgeCachedEntries() unsigned char* FileUtils::getFileData(const char* filename, const char* mode, long *size) { - unsigned char * buffer = NULL; - CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); + unsigned char * buffer = nullptr; + CCASSERT(filename != nullptr && size != nullptr && mode != nullptr, "Invalid parameters."); *size = 0; do { @@ -518,8 +516,8 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, lo unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, long *size) { - unsigned char * buffer = NULL; - unzFile pFile = NULL; + unsigned char * buffer = nullptr; + unzFile pFile = nullptr; *size = 0; do @@ -535,7 +533,7 @@ unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char char szFilePathA[260]; unz_file_info FileInfo; - nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0); + nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), nullptr, 0, nullptr, 0); CC_BREAK_IF(UNZ_OK != nRet); nRet = unzOpenCurrentFile(pFile); diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index ac3da377c3..c0d6712650 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -306,7 +306,7 @@ public: * Write a ValueDict to a plist file. * @note This method is used internally. */ - virtual bool writeToFile(ValueDict dict, const std::string& fullPath); + virtual bool writeToFile(ValueDict& dict, const std::string& fullPath); /** * Converts the contents of a file to a ValueArray. diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 7d40df896f..b1e815866c 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" diff --git a/cocos/2d/platform/CCSAXParser.h b/cocos/2d/platform/CCSAXParser.h index e97b55f8de..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 diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.h b/cocos/2d/platform/apple/CCFileUtilsApple.h index 4adba6e63c..d773b337e3 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.h +++ b/cocos/2d/platform/apple/CCFileUtilsApple.h @@ -47,7 +47,7 @@ public: virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) override; virtual ValueDict fileToValueDict(const std::string& filename) override; - virtual bool writeToFile(ValueDict dict, const std::string& fullPath) override; + virtual bool writeToFile(ValueDict& dict, const std::string& fullPath) override; virtual ValueArray fileToValueArray(const std::string& filename) override; }; diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.mm b/cocos/2d/platform/apple/CCFileUtilsApple.mm index 62a96cf622..d0088fc8c3 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -327,7 +327,7 @@ ValueDict FileUtilsApple::fileToValueDict(const std::string& filename) return ret; } -bool FileUtilsApple::writeToFile(ValueDict dict, const std::string &fullPath) +bool FileUtilsApple::writeToFile(ValueDict& dict, const std::string &fullPath) { //CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str()); NSMutableDictionary *nsDict = [NSMutableDictionary dictionary]; From ceaa1f26bb2b3e80ba624d6460d600899c7c0e14 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 15:34:05 +0800 Subject: [PATCH 032/107] issue #2790: Windows run ok with ValueDict for FileUtils. --- cocos/2d/CCNode.cpp | 7 --- cocos/2d/platform/CCFileUtils.cpp | 78 +++++++++++++++------------ cocos/2d/platform/CCImageCommon_cpp.h | 2 +- cocos/{2d => base}/CCValue.cpp | 0 cocos/{2d => base}/CCValue.h | 20 +++++-- 5 files changed, 59 insertions(+), 48 deletions(-) rename cocos/{2d => base}/CCValue.cpp (100%) rename cocos/{2d => base}/CCValue.h (96%) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 43cc219118..3d200903df 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -874,13 +874,6 @@ void Node::visit() std::for_each(_children.cbegin()+i, _children.cend(), [](Node* node){ node->visit(); }); - -// for( ; i < _children.count(); i++ ) -// { -// auto node = _children[i]; -// if (node) -// node->visit(); -// } } else { diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 63a2673a7b..bae6a1abe8 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -58,16 +58,18 @@ class DictMaker : public SAXDelegator { public: SAXResult _resultType; - ValueArray _rootArray; - ValueDict _rootDict; - ValueDict _curDict; - std::stack _dictStack; + ValueDict _rootDict; + ValueArray _rootArray; + std::string _curKey; ///< parsed key std::string _curValue; // parsed value SAXState _state; - ValueArray _array; - std::stack _arrayStack; + ValueDict* _curDict; + ValueArray* _curArray; + + std::stack _dictStack; + std::stack _arrayStack; std::stack _stateStack; public: @@ -80,7 +82,7 @@ public: { } - ValueDict& dictionaryWithContentsOfFile(const char *pFileName) + ValueDict dictionaryWithContentsOfFile(const char *pFileName) { _resultType = SAX_RESULT_DICT; SAXParser parser; @@ -89,10 +91,10 @@ public: parser.setDelegator(this); parser.parse(pFileName); - return _rootDict; + return std::move(_rootDict); } - ValueArray& arrayWithContentsOfFile(const char* pFileName) + ValueArray arrayWithContentsOfFile(const char* pFileName) { _resultType = SAX_RESULT_ARRAY; SAXParser parser; @@ -101,20 +103,21 @@ public: 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" ) { - if(_resultType == SAX_RESULT_DICT && _rootDict.empty()) + if(_resultType == SAX_RESULT_DICT && _rootDict.empty()) { - _rootDict = _curDict; + _curDict = &_rootDict; } + _state = SAX_DICT; SAXState preState = SAX_NONE; @@ -125,16 +128,19 @@ public: if (SAX_ARRAY == preState) { - // add the dictionary into the array - _array.push_back(Value(_curDict)); + // add a new dictionary into the array + _curArray->push_back(Value(ValueDict())); + _curDict = &(_curArray->rbegin())->asDict(); } 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!"); - ValueDict& pPreDict = _dictStack.top(); - pPreDict[_curKey] = Value(_curDict); + ValueDict* preDict = _dictStack.top(); + (*preDict)[_curKey] = Value(ValueDict()); + _curDict = &(*preDict)[_curKey].asDict(); } + // record the dict state _stateStack.push(_state); _dictStack.push(_curDict); @@ -159,9 +165,9 @@ public: { _state = SAX_ARRAY; - if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty()) + if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty()) { - _rootArray = _array; + _curArray = &_rootArray; } SAXState preState = SAX_NONE; if (! _stateStack.empty()) @@ -171,17 +177,19 @@ public: if (preState == SAX_DICT) { - _curDict[_curKey] = Value(_array); + (*_curDict)[_curKey] = Value(ValueArray()); + _curArray = &(*_curDict)[_curKey].asArray(); } else if (preState == SAX_ARRAY) { CCASSERT(! _arrayStack.empty(), "The state is wrong!"); - ValueArray& pPreArray = _arrayStack.top(); - pPreArray.push_back(Value(_array)); + ValueArray* preArray = _arrayStack.top(); + preArray->push_back(Value(ValueArray())); + _curArray = &(_curArray->rbegin())->asArray(); } // record the array state _stateStack.push(_state); - _arrayStack.push(_array); + _arrayStack.push(_curArray); } else { @@ -209,29 +217,29 @@ public: _arrayStack.pop(); if (! _arrayStack.empty()) { - _array = _arrayStack.top(); + _curArray = _arrayStack.top(); } } else if (sName == "true") { if (SAX_ARRAY == curState) { - _array.push_back(Value(true)); + _curArray->push_back(Value(true)); } else if (SAX_DICT == curState) { - _curDict[_curKey] = Value(true); + (*_curDict)[_curKey] = Value(true); } } else if (sName == "false") { if (SAX_ARRAY == curState) { - _array.push_back(Value(false)); + _curArray->push_back(Value(false)); } else if (SAX_DICT == curState) { - _curDict[_curKey] = Value(false); + (*_curDict)[_curKey] = Value(false); } } else if (sName == "string" || sName == "integer" || sName == "real") @@ -239,20 +247,20 @@ public: if (SAX_ARRAY == curState) { if (sName == "string") - _array.push_back(Value(_curValue)); + _curArray->push_back(Value(_curValue)); else if (sName == "integer") - _array.push_back(Value(atoi(_curValue.c_str()))); + _curArray->push_back(Value(atoi(_curValue.c_str()))); else - _array.push_back(Value(atof(_curValue.c_str()))); + _curArray->push_back(Value(atof(_curValue.c_str()))); } else if (SAX_DICT == curState) { if (sName == "string") - _curDict[_curKey] = Value(_curValue); + (*_curDict)[_curKey] = Value(_curValue); else if (sName == "integer") - _curDict[_curKey] = Value(atoi(_curValue.c_str())); + (*_curDict)[_curKey] = Value(atoi(_curValue.c_str())); else - _curDict[_curKey] = Value(atof(_curValue.c_str())); + (*_curDict)[_curKey] = Value(atof(_curValue.c_str())); } _curValue.clear(); diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index edbf424868..210f3c3cb2 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -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; diff --git a/cocos/2d/CCValue.cpp b/cocos/base/CCValue.cpp similarity index 100% rename from cocos/2d/CCValue.cpp rename to cocos/base/CCValue.cpp diff --git a/cocos/2d/CCValue.h b/cocos/base/CCValue.h similarity index 96% rename from cocos/2d/CCValue.h rename to cocos/base/CCValue.h index 174e01d431..6c9bfd4a7b 100644 --- a/cocos/2d/CCValue.h +++ b/cocos/base/CCValue.h @@ -116,6 +116,15 @@ public: { *_dictData = v; } + + explicit Value(ValueDict&& v) + : _arrData(nullptr) + , _dictData(new ValueDict()) + , _intKeyDictData(nullptr) + , _type(Type::DICTIONARY) + { + *_dictData = std::move(v); + } explicit Value(const IntValueDict& v) : _arrData(nullptr) @@ -215,12 +224,13 @@ public: default: break; } - - _arrData = nullptr; - _dictData = nullptr; - _intKeyDictData = nullptr; - _type = other._type; + + other._arrData = nullptr; + other._dictData = nullptr; + other._intKeyDictData = nullptr; + other._type = Type::NONE; + return *this; } From 18d604d3494e72771fdb6de54ad6ea530e508112 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 15:39:28 +0800 Subject: [PATCH 033/107] issue #2790: Bug fix in CCScale9Sprite.cpp. Sprite::Sprite::create --> Sprite::create --- extensions/GUI/CCControlExtension/CCScale9Sprite.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index ecb67a4798..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); From 3649530f97acc035d83810aa79444db42df9071d Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 15:55:24 +0800 Subject: [PATCH 034/107] issue #2790: Moves CCValue.h/.cpp to base folder. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 7f97ea4693..72d75d5a4b 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -6cd064b4af81704d1a587ac778250f108fc585e0 \ No newline at end of file +d97a47c45785d37e9aa29c3d046cad5ab109ac81 \ No newline at end of file From 60874ece64b2a40d2722389f93616304c4e93041 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 16:18:22 +0800 Subject: [PATCH 035/107] issue #2790: Updates Makefile, Moves some codes to CCValue.cpp. --- cocos/2d/Android.mk | 1 + cocos/base/CCValue.cpp | 383 +++++++++++++++++++++++++++++++++++- cocos/base/CCValue.h | 400 +++----------------------------------- cocos/base/CMakeLists.txt | 1 + 4 files changed, 410 insertions(+), 375 deletions(-) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 854d56829d..f9d8919fb6 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -129,6 +129,7 @@ platform/CCThread.cpp \ ../base/CCObject.cpp \ ../base/CCSet.cpp \ ../base/CCString.cpp \ +../base/CCValue.cpp \ ../base/etc1.cpp \ ../base/s3tc.cpp \ ../math/kazmath/src/aabb.c \ diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 07327298b4..97ccff8635 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -1,14 +1,383 @@ -// -// CCValue.cpp -// cocos2d_libs -// -// Created by James Chen on 11/29/13. -// -// +/**************************************************************************** + 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() +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::NONE) +{ + +} + +Value::Value(int v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::INTEGER) +{ + _baseData.intVal = v; +} + +Value::Value(float v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::FLOAT) +{ + _baseData.floatVal = v; +} + +Value::Value(double v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::DOUBLE) +{ + _baseData.doubleVal = v; +} + +Value::Value(bool v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::BOOLEAN) +{ + _baseData.boolVal = v; +} + +Value::Value(const char* v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::STRING) +{ + _strData = v; +} + +Value::Value(const std::string& v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::STRING) +{ + _strData = v; +} + +Value::Value(const ValueArray& v) +: _arrData(new ValueArray()) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::ARRAY) +{ + *_arrData = v; +} + +Value::Value(const ValueDict& v) +: _arrData(nullptr) +, _dictData(new ValueDict()) +, _intKeyDictData(nullptr) +, _type(Type::DICTIONARY) +{ + *_dictData = v; +} + +Value::Value(ValueDict&& v) +: _arrData(nullptr) +, _dictData(new ValueDict()) +, _intKeyDictData(nullptr) +, _type(Type::DICTIONARY) +{ + *_dictData = std::move(v); +} + +Value::Value(const IntValueDict& v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(new IntValueDict()) +, _type(Type::INT_KEY_DICT) +{ + *_intKeyDictData = v; +} + +Value::Value(const Value& other) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +{ + *this = other; +} + +Value::Value(Value&& other) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +{ + *this = std::move(other); +} + +Value::~Value() +{ + CC_SAFE_DELETE(_arrData); + CC_SAFE_DELETE(_dictData); + CC_SAFE_DELETE(_intKeyDictData); +} + +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::ARRAY: + *_arrData = *other._arrData; + break; + case Type::DICTIONARY: + *_dictData = *other._dictData; + break; + case Type::INT_KEY_DICT: + *_intKeyDictData = *other._intKeyDictData; + 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::ARRAY: + CC_SAFE_DELETE(_arrData); + _arrData = other._arrData; + break; + case Type::DICTIONARY: + CC_SAFE_DELETE(_dictData); + _dictData = other._dictData; + break; + case Type::INT_KEY_DICT: + CC_SAFE_DELETE(_intKeyDictData); + _intKeyDictData = other._intKeyDictData; + break; + default: + break; + } + _type = other._type; + + other._arrData = nullptr; + other._dictData = nullptr; + other._intKeyDictData = nullptr; + other._type = Type::NONE; + + return *this; +} + +int Value::asInt() const +{ + CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + 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::ARRAY && _type != Type::DICTIONARY, ""); + 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::ARRAY && _type != Type::DICTIONARY, ""); + 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::ARRAY && _type != Type::DICTIONARY, ""); + 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::ARRAY && _type != Type::DICTIONARY, ""); + + 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 index 6c9bfd4a7b..ec8422d2e9 100644 --- a/cocos/base/CCValue.h +++ b/cocos/base/CCValue.h @@ -28,13 +28,13 @@ #include "CCPlatformMacros.h" #include "ccMacros.h" #include -#include #include #include NS_CC_BEGIN class Value; + typedef std::vector ValueArray; typedef std::unordered_map ValueDict; typedef std::unordered_map IntValueDict; @@ -42,376 +42,40 @@ typedef std::unordered_map IntValueDict; class Value { public: - Value() - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::NONE) - { - - } - explicit Value(int v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::INTEGER) - { - _baseData.intVal = v; - } - explicit Value(float v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::FLOAT) - { - _baseData.floatVal = v; - } - explicit Value(double v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::DOUBLE) - { - _baseData.doubleVal = v; - } - explicit Value(bool v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::BOOLEAN) - { - _baseData.boolVal = v; - } + 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 ValueArray& v); + explicit Value(const ValueDict& v); + explicit Value(ValueDict&& v); + explicit Value(const IntValueDict& v); + Value(const Value& other); + Value(Value&& other); + ~Value(); - explicit Value(const char* v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::STRING) - { - _strData = v; - } + Value& operator= (const Value& other); + Value& operator= (Value&& other); - explicit Value(const std::string& v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::STRING) - { - _strData = v; - } - explicit Value(const ValueArray& v) - : _arrData(new ValueArray()) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - , _type(Type::ARRAY) - { - *_arrData = v; - } - explicit Value(const ValueDict& v) - : _arrData(nullptr) - , _dictData(new ValueDict()) - , _intKeyDictData(nullptr) - , _type(Type::DICTIONARY) - { - *_dictData = v; - } + int asInt() const; + float asFloat() const; + double asDouble() const; + bool asBool() const; + std::string asString() const; + + inline ValueArray& asArray() { return *_arrData; } + inline const ValueArray& asArray() const { return *_arrData; } + + inline ValueDict& asDict() { return *_dictData; } + inline const ValueDict& asDict() const { return *_dictData; } + + inline IntValueDict& asIntKeyDict() { return *_intKeyDictData; } + inline const IntValueDict& asIntKeyDict() const { return *_intKeyDictData; } - explicit Value(ValueDict&& v) - : _arrData(nullptr) - , _dictData(new ValueDict()) - , _intKeyDictData(nullptr) - , _type(Type::DICTIONARY) - { - *_dictData = std::move(v); - } - - explicit Value(const IntValueDict& v) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(new IntValueDict()) - , _type(Type::INT_KEY_DICT) - { - *_intKeyDictData = v; - } - - Value(const Value& other) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - { - *this = other; - } - Value(Value&& other) - : _arrData(nullptr) - , _dictData(nullptr) - , _intKeyDictData(nullptr) - { - *this = std::move(other); - } - - ~Value() - { - CC_SAFE_DELETE(_arrData); - CC_SAFE_DELETE(_dictData); - CC_SAFE_DELETE(_intKeyDictData); - } - - 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::ARRAY: - *_arrData = *other._arrData; - break; - case Type::DICTIONARY: - *_dictData = *other._dictData; - break; - case Type::INT_KEY_DICT: - *_intKeyDictData = *other._intKeyDictData; - break; - default: - break; - } - _type = other._type; - return *this; - } - - 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::ARRAY: - CC_SAFE_DELETE(_arrData); - _arrData = other._arrData; - break; - case Type::DICTIONARY: - CC_SAFE_DELETE(_dictData); - _dictData = other._dictData; - break; - case Type::INT_KEY_DICT: - CC_SAFE_DELETE(_intKeyDictData); - _intKeyDictData = other._intKeyDictData; - break; - default: - break; - } - _type = other._type; - - other._arrData = nullptr; - other._dictData = nullptr; - other._intKeyDictData = nullptr; - other._type = Type::NONE; - - return *this; - } - - int asInt() const - { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); - 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 asFloat() const - { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); - 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 asDouble() const - { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); - 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 asBool() const - { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); - 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 asString() const - { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); - - 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(); - } - - ValueArray& asArray() - { - return *_arrData; - } - - const ValueArray& asArray() const - { - return *_arrData; - } - - ValueDict& asDict() - { - return *_dictData; - } - - const ValueDict& asDict() const - { - return *_dictData; - } - - IntValueDict& asIntKeyDict() - { - return *_intKeyDictData; - } - - bool isNull() const { return _type == Type::NONE; } + inline bool isNull() const { return _type == Type::NONE; } enum class Type { diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index 3d37d21a2f..d8f69559d7 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -10,6 +10,7 @@ set(COCOS_BASE_SRC CCString.cpp CCDataVisitor.cpp CCData.cpp + CCValue.cpp etc1.cpp s3tc.cpp atitc.cpp From 293ba0210b1615bfc22b22f769cfcb3ccf196db6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 16:37:08 +0800 Subject: [PATCH 036/107] =?UTF-8?q?issue=20#2790:=20CCLOG=20=E2=80=94>=20C?= =?UTF-8?q?CLOGINFO=20for=20CCMap.h=20and=20CCVector.h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCMap.h | 10 +++++----- cocos/base/CCVector.h | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 823307d58b..eb7a970feb 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -43,32 +43,32 @@ public: Map() : _data() { - CCLOG("In the default constructor of Map!"); + CCLOGINFO("In the default constructor of Map!"); } explicit Map(long capacity) : _data() { - CCLOG("In the constructor with capacity of Map!"); + CCLOGINFO("In the constructor with capacity of Map!"); _data.reserve(capacity); } Map(const Map& other) { - CCLOG("In the copy constructor of Map!"); + CCLOGINFO("In the copy constructor of Map!"); _data = other; addRefForAllObjects(); } Map(Map&& other) { - CCLOG("In the move constructor of Map!"); + CCLOGINFO("In the move constructor of Map!"); _data = other; } ~Map() { - CCLOG("In the destructor of Map!"); + CCLOGINFO("In the destructor of Map!"); removeAllObjects(); } diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 960b98cd48..fdeadc6026 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -45,19 +45,19 @@ public: explicit Vector(long capacity) : _data() { - CCLOG("In the default constructor with capacity of Vector."); + CCLOGINFO("In the default constructor with capacity of Vector."); setCapacity(capacity); } virtual ~Vector() { - CCLOG("In the destructor of Vector."); + CCLOGINFO("In the destructor of Vector."); removeAllObjects(); } Vector(const Vector& other) { - CCLOG("In the copy constructor!"); + CCLOGINFO("In the copy constructor!"); _data = other._data; addRefForAllObjects(); } @@ -65,13 +65,13 @@ public: /** Move constructor */ Vector(Vector&& other) { - CCLOG("In the move constructor of Vector!"); + CCLOGINFO("In the move constructor of Vector!"); _data = other._data; } Vector& operator=(const Vector& other) { - CCLOG("In the copy assignment operator!"); + CCLOGINFO("In the copy assignment operator!"); removeAllObjects(); _data = other._data; addRefForAllObjects(); @@ -80,7 +80,7 @@ public: Vector& operator=(Vector&& other) { - CCLOG("In the move assignment operator!"); + CCLOGINFO("In the move assignment operator!"); _data = other._data; return *this; } From 82cc795ecf183e1f0404d242be0c2da2581f0fc9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 16:37:48 +0800 Subject: [PATCH 037/107] issue #2790: Adds more move functions. --- cocos/base/CCValue.cpp | 18 ++++++++++++++++++ cocos/base/CCValue.h | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 97ccff8635..24b55728bc 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -99,6 +99,15 @@ Value::Value(const ValueArray& v) *_arrData = v; } +Value::Value(ValueArray&& v) +: _arrData(new ValueArray()) +, _dictData(nullptr) +, _intKeyDictData(nullptr) +, _type(Type::ARRAY) +{ + *_arrData = std::move(v); +} + Value::Value(const ValueDict& v) : _arrData(nullptr) , _dictData(new ValueDict()) @@ -126,6 +135,15 @@ Value::Value(const IntValueDict& v) *_intKeyDictData = v; } +Value::Value(IntValueDict&& v) +: _arrData(nullptr) +, _dictData(nullptr) +, _intKeyDictData(new IntValueDict()) +, _type(Type::INT_KEY_DICT) +{ + *_intKeyDictData = std::move(v); +} + Value::Value(const Value& other) : _arrData(nullptr) , _dictData(nullptr) diff --git a/cocos/base/CCValue.h b/cocos/base/CCValue.h index ec8422d2e9..dfcb910118 100644 --- a/cocos/base/CCValue.h +++ b/cocos/base/CCValue.h @@ -49,10 +49,16 @@ public: explicit Value(bool v); explicit Value(const char* v); explicit Value(const std::string& v); + explicit Value(const ValueArray& v); + explicit Value(ValueArray&& v); + explicit Value(const ValueDict& v); explicit Value(ValueDict&& v); + explicit Value(const IntValueDict& v); + explicit Value(IntValueDict&& v); + Value(const Value& other); Value(Value&& other); ~Value(); From bbeec97b481d875038f792d76bd2a789b46832d8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 16:38:12 +0800 Subject: [PATCH 038/107] issue #2790: Bug fixes in CCValue.cpp. --- cocos/base/CCValue.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 24b55728bc..63a5167ab8 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -186,12 +186,18 @@ Value& Value::operator= (const Value& other) _strData = other._strData; break; case Type::ARRAY: + if (_arrData == nullptr) + _arrData = new ValueArray(); *_arrData = *other._arrData; break; case Type::DICTIONARY: + if (_dictData == nullptr) + _dictData = new ValueDict(); *_dictData = *other._dictData; break; case Type::INT_KEY_DICT: + if (_intKeyDictData == nullptr) + _intKeyDictData = new IntValueDict(); *_intKeyDictData = *other._intKeyDictData; break; default: From 4212e33aee1c186baa05af83b46f8fef6ec54b55 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 17:27:53 +0800 Subject: [PATCH 039/107] issue #2790: Removes unused comments in CCAnimation.h --- cocos/2d/CCAnimation.h | 8 -------- 1 file changed, 8 deletions(-) diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 72bc30ab0c..6ffb1657ee 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -213,15 +213,7 @@ public: virtual Animation *clone() const override; protected: - - /** - * @js ctor - */ Animation(); - /** - * @js NA - * @lua NA - */ virtual ~Animation(void); /** Initializes a Animation */ From 736c70704bdf3deaa9c809eebaa8cbe3ff180512 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 17:28:14 +0800 Subject: [PATCH 040/107] issue #2790: Some FIXME fixes. --- cocos/base/CCArray.cpp | 10 +++++++++- cocos/base/CCDictionary.cpp | 9 ++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index 6b06cd64f1..4bb00b2ff2 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -478,7 +478,15 @@ Array* Array::createWithContentsOfFile(const char* fileName) Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) { - return nullptr;//FIXME:XXX FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); + ValueArray arr = FileUtils::getInstance()->fileToValueArray(fileName); + + Array* ret = Array::createWithCapacity(arr.size()); + + std::for_each(arr.cbegin(), arr.cend(), [&ret](const Value& value){ + ret->addObject(String::create(value.asString())); + }); + + return ret; } bool Array::init() diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index cf9ea4b184..3c4e4b3cfe 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -464,7 +464,14 @@ Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName) bool Dictionary::writeToFile(const char *fullPath) { - return false;//FIXME: XXX FileUtils::getInstance()->writeToFile(this, fullPath); + ValueDict 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 From 54289276ded1ece1d309805522c77635eb1e13af Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 17:46:57 +0800 Subject: [PATCH 041/107] =?UTF-8?q?issue=20#2790:=20ValueArray=20=E2=80=94?= =?UTF-8?q?>=20ValueVector,=20ValueDict=20=E2=80=94>=20ValueMap,=20IntValu?= =?UTF-8?q?eDict=20=E2=80=94>=20IntValueMap.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCActionInterval.cpp | 2 +- cocos/2d/CCAnimation.cpp | 8 +- cocos/2d/CCAnimation.h | 12 +- cocos/2d/CCAnimationCache.cpp | 30 +-- cocos/2d/CCAnimationCache.h | 6 +- cocos/2d/CCMenu.cpp | 8 +- cocos/2d/CCMenu.h | 4 +- cocos/2d/CCParticleSystem.cpp | 6 +- cocos/2d/CCParticleSystem.h | 4 +- cocos/2d/CCSpriteFrameCache.cpp | 22 +- cocos/2d/CCSpriteFrameCache.h | 6 +- cocos/2d/CCTMXLayer.h | 8 +- cocos/2d/CCTMXObjectGroup.cpp | 6 +- cocos/2d/CCTMXObjectGroup.h | 20 +- cocos/2d/CCTMXTiledMap.h | 8 +- cocos/2d/CCTMXXMLParser.cpp | 24 +-- cocos/2d/CCTMXXMLParser.h | 18 +- cocos/2d/platform/CCFileUtils.cpp | 68 +++---- cocos/2d/platform/CCFileUtils.h | 16 +- cocos/2d/platform/apple/CCFileUtilsApple.h | 6 +- cocos/2d/platform/apple/CCFileUtilsApple.mm | 40 ++-- cocos/base/CCArray.cpp | 2 +- cocos/base/CCDictionary.cpp | 26 +-- cocos/base/CCValue.cpp | 190 +++++++++--------- cocos/base/CCValue.h | 42 ++-- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 6 +- .../Classes/TileMapTest/TileMapTest.cpp | 10 +- 27 files changed, 299 insertions(+), 299 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 5cf1d8b17d..69071b7fbb 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -2108,7 +2108,7 @@ void Animate::update(float t) frameToDisplay = frame->getSpriteFrame(); static_cast(_target)->setDisplayFrame(frameToDisplay); - const ValueDict& dict = frame->getUserInfo(); + const ValueMap& dict = frame->getUserInfo(); if ( !dict.empty() ) { //TODO: [[NSNotificationCenter defaultCenter] postNotificationName:AnimationFrameDisplayedNotification object:target_ userInfo:dict]; diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 144294bcff..eb79075f44 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -32,7 +32,7 @@ THE SOFTWARE. NS_CC_BEGIN -AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo) +AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo) { auto ret = new AnimationFrame(); if (ret && ret->initWithSpriteFrame(spriteFrame, delayUnits, userInfo)) @@ -53,7 +53,7 @@ AnimationFrame::AnimationFrame() } -bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo) +bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo) { setSpriteFrame(spriteFrame); setDelayUnits(delayUnits); @@ -124,7 +124,7 @@ bool Animation::initWithSpriteFrames(const Vector& frames, float d for (auto& spriteFrame : frames) { - auto animFrame = AnimationFrame::create(spriteFrame, 1, ValueDict()); + auto animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap()); _frames.addObject(animFrame); _totalDelayUnits++; } @@ -163,7 +163,7 @@ Animation::~Animation(void) void Animation::addSpriteFrame(SpriteFrame* spriteFrame) { - AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, 1.0f, ValueDict()); + AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, 1.0f, ValueMap()); _frames.addObject(animFrame); // update duration diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 6ffb1657ee..99fae8882d 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -61,7 +61,7 @@ public: * Creates the animation frame with a spriteframe, number of delay units and a notification user info * @since 3.0 */ - static AnimationFrame* create(SpriteFrame* spriteFrame, float delayUnits, const ValueDict& userInfo); + static AnimationFrame* create(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo); SpriteFrame* getSpriteFrame() const { return _spriteFrame; }; @@ -81,11 +81,11 @@ 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. */ - const ValueDict& getUserInfo() const { return _userInfo; }; - ValueDict& getUserInfo() { return _userInfo; }; + const ValueMap& getUserInfo() const { return _userInfo; }; + ValueMap& getUserInfo() { return _userInfo; }; /** Sets user infomation */ - void setUserInfo(const ValueDict& userInfo) + void setUserInfo(const ValueMap& userInfo) { _userInfo = userInfo; } @@ -106,7 +106,7 @@ protected: 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 ValueDict& userInfo); + bool initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUnits, const ValueMap& userInfo); /** SpriteFrameName to be used */ SpriteFrame* _spriteFrame; @@ -115,7 +115,7 @@ 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. */ - ValueDict _userInfo; + ValueMap _userInfo; private: CC_DISALLOW_COPY_AND_ASSIGN(AnimationFrame); diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 592b659d1a..4a600504ce 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -85,14 +85,14 @@ Animation* AnimationCache::getAnimation(const std::string& name) return _animations.getObjectForKey(name); } -void AnimationCache::parseVersion1(const ValueDict& animations) +void AnimationCache::parseVersion1(const ValueMap& animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter) { - const ValueDict& animationDict = iter->second.asDict(); - const ValueArray& frameNames = animationDict.at("frames").asArray(); + const ValueMap& animationDict = iter->second.asValueMap(); + const ValueVector& frameNames = animationDict.at("frames").asValueVector(); float delay = animationDict.at("delay").asFloat(); Animation* animation = nullptr; @@ -114,7 +114,7 @@ void AnimationCache::parseVersion1(const ValueDict& animations) continue; } - AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, ValueDict()); + AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap()); frames.addObject(animFrame); } @@ -134,19 +134,19 @@ void AnimationCache::parseVersion1(const ValueDict& animations) } } -void AnimationCache::parseVersion2(const ValueDict& animations) +void AnimationCache::parseVersion2(const ValueMap& animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter) { std::string name = iter->first; - const ValueDict& animationDict = iter->second.asDict(); + const ValueMap& animationDict = iter->second.asValueMap(); const Value& loops = animationDict.at("loops"); bool restoreOriginalFrame = animationDict.at("restoreOriginalFrame").asBool(); - const ValueArray& frameArray = animationDict.at("frames").asArray(); + const ValueVector& frameArray = animationDict.at("frames").asValueVector(); if ( frameArray.empty() ) { @@ -159,7 +159,7 @@ void AnimationCache::parseVersion2(const ValueDict& animations) for (auto& obj : frameArray) { - const ValueDict& entry = obj.asDict(); + const ValueMap& entry = obj.asValueMap(); std::string spriteFrameName = entry.at("spriteframe").asString(); SpriteFrame *spriteFrame = frameCache->getSpriteFrameByName(spriteFrameName); @@ -172,7 +172,7 @@ void AnimationCache::parseVersion2(const ValueDict& animations) float delayUnits = entry.at("delayUnits").asFloat(); const Value& userInfo = entry.at("notification"); - AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asDict()); + AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asValueMap()); array.addObject(animFrame); } @@ -186,7 +186,7 @@ void AnimationCache::parseVersion2(const ValueDict& animations) } } -void AnimationCache::addAnimationsWithDictionary(const ValueDict& dictionary) +void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary) { if ( dictionary.find("animations") == dictionary.end() ) { @@ -199,9 +199,9 @@ void AnimationCache::addAnimationsWithDictionary(const ValueDict& dictionary) if( dictionary.find("properties") != dictionary.end() ) { - const ValueDict& properties = dictionary.at("properties").asDict(); + const ValueMap& properties = dictionary.at("properties").asValueMap(); version = properties.at("format").asInt(); - const ValueArray& spritesheets = properties.at("spritesheets").asArray(); + const ValueVector& spritesheets = properties.at("spritesheets").asValueVector(); std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){ SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString()); @@ -210,10 +210,10 @@ void AnimationCache::addAnimationsWithDictionary(const ValueDict& dictionary) switch (version) { case 1: - parseVersion1(animations.asDict()); + parseVersion1(animations.asValueMap()); break; case 2: - parseVersion2(animations.asDict()); + parseVersion2(animations.asValueMap()); break; default: CCASSERT(false, "Invalid animation format"); @@ -226,7 +226,7 @@ void AnimationCache::addAnimationsWithFile(const std::string& plist) CCASSERT( plist.size()>0, "Invalid texture file name"); std::string path = FileUtils::getInstance()->fullPathForFilename(plist); - ValueDict dict = FileUtils::getInstance()->fileToValueDict(path); + ValueMap dict = FileUtils::getInstance()->fileToValueMap(path); CCASSERT( !dict.empty(), "CCAnimationCache: File could not be found"); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index 5478eda3ff..cfc48ababb 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -104,7 +104,7 @@ public: Make sure that the frames were previously loaded in the SpriteFrameCache. @since v1.1 */ - void addAnimationsWithDictionary(const ValueDict& 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,8 +115,8 @@ public: void addAnimationsWithFile(const std::string& plist); private: - void parseVersion1(const ValueDict& animations); - void parseVersion2(const ValueDict& animations); + void parseVersion1(const ValueMap& animations); + void parseVersion2(const ValueMap& animations); private: Map _animations; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 1c0988af58..ac62437636 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -347,7 +347,7 @@ void Menu::alignItemsInColumns(int columns, ...) void Menu::alignItemsInColumns(int columns, va_list args) { CCASSERT(columns >= 0, "Columns must be >= 0"); - ValueArray rows; + ValueVector rows; while (columns) { rows.push_back(Value(columns)); @@ -356,7 +356,7 @@ void Menu::alignItemsInColumns(int columns, va_list args) alignItemsInColumnsWithArray(rows); } -void Menu::alignItemsInColumnsWithArray(const ValueArray& rows) +void Menu::alignItemsInColumnsWithArray(const ValueVector& rows) { int height = -5; int row = 0; @@ -447,7 +447,7 @@ void Menu::alignItemsInRows(int rows, ...) void Menu::alignItemsInRows(int rows, va_list args) { - ValueArray array; + ValueVector array; while (rows) { array.push_back(Value(rows)); @@ -456,7 +456,7 @@ void Menu::alignItemsInRows(int rows, va_list args) alignItemsInRowsWithArray(array); } -void Menu::alignItemsInRowsWithArray(const ValueArray& columns) +void Menu::alignItemsInRowsWithArray(const ValueVector& columns) { vector columnWidths; vector columnHeights; diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index c5ad4e3fd7..47e1f4eafe 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -92,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(const ValueArray& 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(const ValueArray& columns); + void alignItemsInRowsWithArray(const ValueVector& columns); virtual bool isEnabled() const { return _enabled; } virtual void setEnabled(bool value) { _enabled = value; }; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index b8a1256f1b..392452d1cf 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -169,7 +169,7 @@ bool ParticleSystem::initWithFile(const std::string& plistFile) { bool bRet = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); - ValueDict dict = FileUtils::getInstance()->fileToValueDict(_plistFile.c_str()); + ValueMap dict = FileUtils::getInstance()->fileToValueMap(_plistFile.c_str()); CCASSERT( !dict.empty(), "Particles: file not found"); @@ -188,12 +188,12 @@ bool ParticleSystem::initWithFile(const std::string& plistFile) return bRet; } -bool ParticleSystem::initWithDictionary(ValueDict& dictionary) +bool ParticleSystem::initWithDictionary(ValueMap& dictionary) { return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(ValueDict& dictionary, const std::string& dirname) +bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname) { bool bRet = false; unsigned char *buffer = nullptr; diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index c5674ba7bb..c09dc527a6 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -386,12 +386,12 @@ protected: /** initializes a QuadParticleSystem from a Dictionary. @since v0.99.3 */ - bool initWithDictionary(ValueDict& 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(ValueDict& 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/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 828974cfdc..3d58ab6001 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -75,7 +75,7 @@ SpriteFrameCache::~SpriteFrameCache(void) CC_SAFE_DELETE(_loadedFileNames); } -void SpriteFrameCache::addSpriteFramesWithDictionary(ValueDict& dictionary, Texture2D* texture) +void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture) { /* Supported Zwoptex Formats: @@ -86,8 +86,8 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueDict& dictionary, Text ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+ */ - ValueDict& metadataDict = dictionary["metadata"].asDict(); - ValueDict& framesDict = dictionary["frames"].asDict(); + ValueMap& metadataDict = dictionary["metadata"].asValueMap(); + ValueMap& framesDict = dictionary["frames"].asValueMap(); int format = 0; // get the format @@ -101,7 +101,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueDict& dictionary, Text for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter) { - ValueDict& frameDict = iter->second.asDict(); + ValueMap& frameDict = iter->second.asValueMap(); std::string spriteFrameName = iter->first; SpriteFrame* spriteFrame = _spriteFrames.getObjectForKey(spriteFrameName); if (spriteFrame) @@ -169,7 +169,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueDict& dictionary, Text bool textureRotated = frameDict["textureRotated"].asBool(); // get aliases - ValueArray& aliases = frameDict["aliases"].asArray(); + ValueVector& aliases = frameDict["aliases"].asValueVector(); std::for_each(aliases.cbegin(), aliases.cend(), [this, &spriteFrameName](const Value& value){ std::string oneAlias = value.asString(); @@ -199,7 +199,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueDict& dictionary, Text void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); - ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); + ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); addSpriteFramesWithDictionary(dict, pobTexture); } @@ -226,11 +226,11 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end()) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); - ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); + ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); string texturePath(""); - ValueDict& metadataDict = dict["metadata"].asDict(); + ValueMap& metadataDict = dict["metadata"].asValueMap(); if (!metadataDict.empty()) { // try to read texture file name from meta data @@ -335,7 +335,7 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); - ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); + ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); if (dict.empty()) { CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str()); @@ -351,9 +351,9 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) } } -void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueDict& dictionary) +void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueMap& dictionary) { - ValueDict framesDict = dictionary["frames"].asDict(); + ValueMap framesDict = dictionary["frames"].asValueMap(); std::vector keysToRemove; for (auto iter = framesDict.cbegin(); iter != framesDict.cend(); ++iter) diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 066716a94a..d9fff83c08 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -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(ValueDict& dictionary, Texture2D *texture); + void addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D *texture); /** Removes multiple Sprite Frames from Dictionary. * @since v0.99.5 */ - void removeSpriteFramesFromDictionary(ValueDict& dictionary); + void removeSpriteFramesFromDictionary(ValueMap& dictionary); protected: Map _spriteFrames; - ValueDict _spriteFramesAliases; + ValueMap _spriteFramesAliases; std::set* _loadedFileNames; }; diff --git a/cocos/2d/CCTMXLayer.h b/cocos/2d/CCTMXLayer.h index 41794f05b2..2667739599 100644 --- a/cocos/2d/CCTMXLayer.h +++ b/cocos/2d/CCTMXLayer.h @@ -174,9 +174,9 @@ public: inline void setLayerOrientation(unsigned int orientation) { _layerOrientation = orientation; }; /** properties from the layer. They can be added using Tiled */ - inline const ValueDict& getProperties() const { return _properties; }; - inline ValueDict& getProperties() { return _properties; }; - inline void setProperties(const ValueDict& properties) { + inline const ValueMap& getProperties() const { return _properties; }; + inline ValueMap& getProperties() { return _properties; }; + inline void setProperties(const ValueMap& properties) { _properties = properties; }; // @@ -243,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 */ - ValueDict _properties; + ValueMap _properties; }; // end of tilemap_parallax_nodes group diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index 9191ea6418..672dc0509f 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -42,13 +42,13 @@ TMXObjectGroup::~TMXObjectGroup() CCLOGINFO("deallocing TMXObjectGroup: %p", this); } -ValueDict TMXObjectGroup::getObject(const std::string& objectName) const +ValueMap TMXObjectGroup::getObject(const std::string& objectName) const { if (_objects.size() > 0) { for (auto& v : _objects) { - ValueDict dict = v.asDict(); + ValueMap dict = v.asValueMap(); if (dict["name"].asString() == objectName) { return dict; @@ -57,7 +57,7 @@ ValueDict TMXObjectGroup::getObject(const std::string& objectName) const } // object not found - return ValueDict(); + return ValueMap(); } Value TMXObjectGroup::getProperty(const std::string& propertyName) const diff --git a/cocos/2d/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h index b8a8f57f12..2064b6bd67 100644 --- a/cocos/2d/CCTMXObjectGroup.h +++ b/cocos/2d/CCTMXObjectGroup.h @@ -66,9 +66,9 @@ public: /** return the dictionary for the specific object name. It will return the 1st object found on the array for the given name. */ - ValueDict getObject(const std::string& objectName) const; + ValueMap getObject(const std::string& objectName) const; - CC_DEPRECATED_ATTRIBUTE ValueDict objectNamed(const std::string& 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,20 +77,20 @@ public: inline void setPositionOffset(const Point& offset) { _positionOffset = offset; }; /** Gets the list of properties stored in a dictionary */ - inline const ValueDict& getProperties() const { return _properties; }; - inline ValueDict& getProperties() { return _properties; }; + inline const ValueMap& getProperties() const { return _properties; }; + inline ValueMap& getProperties() { return _properties; }; /** Sets the list of properties */ - inline void setProperties(const ValueDict& properties) { + inline void setProperties(const ValueMap& properties) { _properties = properties; }; /** Gets the array of the objects */ - inline const ValueArray& getObjects() const { return _objects; }; - inline ValueArray& getObjects() { return _objects; }; + inline const ValueVector& getObjects() const { return _objects; }; + inline ValueVector& getObjects() { return _objects; }; /** Sets the array of the objects */ - inline void setObjects(const ValueArray& objects) { + inline void setObjects(const ValueVector& objects) { _objects = objects; }; @@ -100,9 +100,9 @@ protected: /** offset position of child objects */ Point _positionOffset; /** list of properties stored in a dictionary */ - ValueDict _properties; + ValueMap _properties; /** array of the objects */ - ValueArray _objects; + ValueVector _objects; }; // end of tilemap_parallax_nodes group diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index d58a016c48..7138e2bac0 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -164,8 +164,8 @@ public: }; /** properties */ - inline ValueDict& getProperties() { return _properties; }; - inline void setProperties(const ValueDict& properties) { + inline ValueMap& getProperties() { return _properties; }; + inline void setProperties(const ValueMap& properties) { _properties = properties; }; @@ -199,10 +199,10 @@ protected: /** object groups */ Vector _objectGroups; /** properties */ - ValueDict _properties; + ValueMap _properties; //! tile properties - IntValueDict _tileProperties; + IntValueMap _tileProperties; private: CC_DISALLOW_COPY_AND_ASSIGN(TMXTiledMap); diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index c3031b7af0..f58a2c2a5a 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -59,11 +59,11 @@ TMXLayerInfo::~TMXLayerInfo() } } -ValueDict TMXLayerInfo::getProperties() +ValueMap TMXLayerInfo::getProperties() { return _properties; } -void TMXLayerInfo::setProperties(ValueDict var) +void TMXLayerInfo::setProperties(ValueMap var) { _properties = var; } @@ -208,7 +208,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) CC_UNUSED_PARAM(ctx); TMXMapInfo *pTMXMapInfo = this; std::string elementName = (char*)name; - ValueDict attributeDict; + ValueMap attributeDict; if (atts && atts[0]) { for(int i = 0; atts[i]; i += 2) @@ -463,7 +463,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties - ValueDict dict; + ValueMap dict; // Parse everything automatically const char* pArray[] = {"name", "type", "width", "height", "gid"}; @@ -529,14 +529,14 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { // The parent element is the last object TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().getLastObject(); - ValueDict& dict = objectGroup->getObjects().rbegin()->asDict(); + ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); std::string propertyName = attributeDict["name"].asString(); dict[propertyName] = attributeDict["value"]; } else if ( pTMXMapInfo->getParentElement() == TMXPropertyTile ) { - IntValueDict& dict = pTMXMapInfo->getTileProperties().at(pTMXMapInfo->getParentGID()).asIntKeyDict(); + IntValueMap& dict = pTMXMapInfo->getTileProperties().at(pTMXMapInfo->getParentGID()).asIntKeyMap(); int propertyName = attributeDict["name"].asInt(); dict[propertyName] = attributeDict["value"]; @@ -546,13 +546,13 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { // find parent object's dict and add polygon-points to it TMXObjectGroup* objectGroup = _objectGroups.getLastObject(); - ValueDict& dict = objectGroup->getObjects().rbegin()->asDict(); + ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string std::string value = attributeDict["points"].asString(); if (!value.empty()) { - ValueArray pointsArray; + ValueVector pointsArray; pointsArray.reserve(10); // parse points string into a space-separated set of points @@ -564,7 +564,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) stringstream pointStream(pointPair); string xStr,yStr; - ValueDict pointDict; + ValueMap pointDict; // set x if(std::getline(pointStream, xStr, ',')) @@ -591,13 +591,13 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { // find parent object's dict and add polyline-points to it TMXObjectGroup* objectGroup = _objectGroups.getLastObject(); - ValueDict& dict = objectGroup->getObjects().rbegin()->asDict(); + ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string std::string value = attributeDict["points"].asString(); if (!value.empty()) { - ValueArray pointsArray; + ValueVector pointsArray; pointsArray.reserve(10); // parse points string into a space-separated set of points @@ -609,7 +609,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) stringstream pointStream(pointPair); string xStr,yStr; - ValueDict pointDict; + ValueMap pointDict; // set x if(std::getline(pointStream, xStr, ',')) diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index ac61eb6028..4753bf81a0 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -101,10 +101,10 @@ public: */ virtual ~TMXLayerInfo(); - void setProperties(ValueDict properties); - ValueDict getProperties(); + void setProperties(ValueMap properties); + ValueMap getProperties(); - ValueDict _properties; + ValueMap _properties; std::string _name; Size _layerSize; unsigned int *_tiles; @@ -195,8 +195,8 @@ public: /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ bool parseXMLString(const std::string& xmlString); - IntValueDict& getTileProperties() { return _tileProperties; }; - void setTileProperties(const IntValueDict& tileProperties) { + IntValueMap& getTileProperties() { return _tileProperties; }; + void setTileProperties(const IntValueMap& tileProperties) { _tileProperties = tileProperties; }; @@ -251,8 +251,8 @@ public: inline void setStoringCharacters(bool storingCharacters) { _storingCharacters = storingCharacters; }; /// properties - inline ValueDict getProperties() const { return _properties; }; - inline void setProperties(ValueDict properties) { + inline ValueMap getProperties() const { return _properties; }; + inline void setProperties(ValueMap properties) { _properties = properties; }; @@ -302,7 +302,7 @@ protected: /// is storing characters? bool _storingCharacters; /// properties - ValueDict _properties; + ValueMap _properties; //! tmx filename std::string _TMXFileName; @@ -311,7 +311,7 @@ protected: //! current string std::string _currentString; //! tile properties - IntValueDict _tileProperties; + IntValueMap _tileProperties; unsigned int _currentFirstGID; }; diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index bae6a1abe8..58ef862c59 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -58,18 +58,18 @@ class DictMaker : public SAXDelegator { public: SAXResult _resultType; - ValueDict _rootDict; - ValueArray _rootArray; + ValueMap _rootDict; + ValueVector _rootArray; std::string _curKey; ///< parsed key std::string _curValue; // parsed value SAXState _state; - ValueDict* _curDict; - ValueArray* _curArray; + ValueMap* _curDict; + ValueVector* _curArray; - std::stack _dictStack; - std::stack _arrayStack; + std::stack _dictStack; + std::stack _arrayStack; std::stack _stateStack; public: @@ -82,7 +82,7 @@ public: { } - ValueDict dictionaryWithContentsOfFile(const char *pFileName) + ValueMap dictionaryWithContentsOfFile(const char *pFileName) { _resultType = SAX_RESULT_DICT; SAXParser parser; @@ -94,7 +94,7 @@ public: return std::move(_rootDict); } - ValueArray arrayWithContentsOfFile(const char* pFileName) + ValueVector arrayWithContentsOfFile(const char* pFileName) { _resultType = SAX_RESULT_ARRAY; SAXParser parser; @@ -129,16 +129,16 @@ public: if (SAX_ARRAY == preState) { // add a new dictionary into the array - _curArray->push_back(Value(ValueDict())); - _curDict = &(_curArray->rbegin())->asDict(); + _curArray->push_back(Value(ValueMap())); + _curDict = &(_curArray->rbegin())->asValueMap(); } else if (SAX_DICT == preState) { // add a new dictionary into the pre dictionary CCASSERT(! _dictStack.empty(), "The state is wrong!"); - ValueDict* preDict = _dictStack.top(); - (*preDict)[_curKey] = Value(ValueDict()); - _curDict = &(*preDict)[_curKey].asDict(); + ValueMap* preDict = _dictStack.top(); + (*preDict)[_curKey] = Value(ValueMap()); + _curDict = &(*preDict)[_curKey].asValueMap(); } // record the dict state @@ -177,15 +177,15 @@ public: if (preState == SAX_DICT) { - (*_curDict)[_curKey] = Value(ValueArray()); - _curArray = &(*_curDict)[_curKey].asArray(); + (*_curDict)[_curKey] = Value(ValueVector()); + _curArray = &(*_curDict)[_curKey].asValueVector(); } else if (preState == SAX_ARRAY) { CCASSERT(! _arrayStack.empty(), "The state is wrong!"); - ValueArray* preArray = _arrayStack.top(); - preArray->push_back(Value(ValueArray())); - _curArray = &(_curArray->rbegin())->asArray(); + ValueVector* preArray = _arrayStack.top(); + preArray->push_back(Value(ValueVector())); + _curArray = &(_curArray->rbegin())->asValueVector(); } // record the array state _stateStack.push(_state); @@ -303,14 +303,14 @@ public: } }; -ValueDict FileUtils::fileToValueDict(const std::string& filename) +ValueMap FileUtils::fileToValueMap(const std::string& filename) { std::string fullPath = fullPathForFilename(filename.c_str()); DictMaker tMaker; return std::move(tMaker.dictionaryWithContentsOfFile(fullPath.c_str())); } -ValueArray FileUtils::fileToValueArray(const std::string& filename) +ValueVector FileUtils::fileToValueVector(const std::string& filename) { std::string fullPath = fullPathForFilename(filename.c_str()); DictMaker tMaker; @@ -321,13 +321,13 @@ ValueArray FileUtils::fileToValueArray(const std::string& filename) /* * forward statement */ -static tinyxml2::XMLElement* generateElementForArray(ValueArray& array, tinyxml2::XMLDocument *pDoc); -static tinyxml2::XMLElement* generateElementForDict(ValueDict& 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(ValueDict& 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(); @@ -404,11 +404,11 @@ static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XM // object is Array if (value.getType() == Value::Type::ARRAY) - return generateElementForArray(value.asArray(), pDoc); + return generateElementForArray(value.asValueVector(), pDoc); // object is Dictionary if (value.getType() == Value::Type::DICTIONARY) - return generateElementForDict(value.asDict(), pDoc); + return generateElementForDict(value.asValueMap(), pDoc); CCLOG("This type cannot appear in property list"); return nullptr; @@ -417,7 +417,7 @@ static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XM /* * Generate tinyxml2::XMLElement for Dictionary through a tinyxml2::XMLDocument */ -static tinyxml2::XMLElement* generateElementForDict(ValueDict& dict, tinyxml2::XMLDocument *pDoc) +static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *pDoc) { tinyxml2::XMLElement* rootNode = pDoc->NewElement("dict"); @@ -438,7 +438,7 @@ static tinyxml2::XMLElement* generateElementForDict(ValueDict& dict, tinyxml2::X /* * Generate tinyxml2::XMLElement for Array through a tinyxml2::XMLDocument */ -static tinyxml2::XMLElement* generateElementForArray(ValueArray& array, tinyxml2::XMLDocument *pDoc) +static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *pDoc) { tinyxml2::XMLElement* rootNode = pDoc->NewElement("array"); @@ -456,9 +456,9 @@ static tinyxml2::XMLElement* generateElementForArray(ValueArray& array, tinyxml2 NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ -ValueDict FileUtils::fileToValueDict(const std::string& filename) {return ValueDict();} -ValueArray FileUtils::fileToValueArray(const std::string& filename) {return ValueArray();} -bool FileUtils::writeToFile(ValueDict& dict, const std::string &fullPath) {return false;} +ValueMap FileUtils::fileToValueMap(const std::string& filename) {return ValueMap();} +ValueVector FileUtils::fileToValueVector(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) */ @@ -738,7 +738,7 @@ void FileUtils::addSearchPath(const std::string &searchpath) _searchPathArray.push_back(path); } -void FileUtils::setFilenameLookupDictionary(const ValueDict& filenameLookupDict) +void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict) { _fullPathCache.clear(); _filenameLookupDict = filenameLookupDict; @@ -749,17 +749,17 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename std::string fullPath = fullPathForFilename(filename); if (fullPath.length() > 0) { - ValueDict dict = FileUtils::getInstance()->fileToValueDict(fullPath); + ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); if (!dict.empty()) { - ValueDict& metadata = dict["metadata"].asDict(); + ValueMap& metadata = dict["metadata"].asValueMap(); int version = metadata["version"].asInt(); if (version != 1) { CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename.c_str()); return; } - setFilenameLookupDictionary( dict["filenames"].asDict()); + setFilenameLookupDictionary( dict["filenames"].asValueMap()); } } } diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index c0d6712650..9bdf4f632d 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -185,7 +185,7 @@ public: * @param pFilenameLookupDict The dictionary for replacing filename. * @since v2.1 */ - virtual void setFilenameLookupDictionary(const ValueDict& filenameLookupDict); + virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict); /** * Gets full path from a file name and the path of the reletive file. @@ -297,22 +297,22 @@ public: virtual bool isPopupNotify(); /** - * Converts the contents of a file to a ValueDict. + * Converts the contents of a file to a ValueMap. * @note This method is used internally. */ - virtual ValueDict fileToValueDict(const std::string& filename); + virtual ValueMap fileToValueMap(const std::string& filename); /** - * Write a ValueDict to a plist file. + * Write a ValueMap to a plist file. * @note This method is used internally. */ - virtual bool writeToFile(ValueDict& dict, const std::string& fullPath); + virtual bool writeToFile(ValueMap& dict, const std::string& fullPath); /** - * Converts the contents of a file to a ValueArray. + * Converts the contents of a file to a ValueVector. * @note This method is used internally. */ - virtual ValueArray fileToValueArray(const std::string& filename); + virtual ValueVector fileToValueVector(const std::string& filename); protected: /** @@ -369,7 +369,7 @@ protected: * * @since v2.1 */ - ValueDict _filenameLookupDict; + ValueMap _filenameLookupDict; /** * The vector contains resolution folders. diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.h b/cocos/2d/platform/apple/CCFileUtilsApple.h index d773b337e3..5bcb76732d 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 ValueDict fileToValueDict(const std::string& filename) override; - virtual bool writeToFile(ValueDict& dict, const std::string& fullPath) override; + virtual ValueMap fileToValueMap(const std::string& filename) override; + virtual bool writeToFile(ValueMap& dict, const std::string& fullPath) override; - virtual ValueArray fileToValueArray(const std::string& filename) override; + virtual ValueVector fileToValueVector(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 d0088fc8c3..0b18e49b7e 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -37,10 +37,10 @@ THE SOFTWARE. NS_CC_BEGIN -static void addValueToDict(id nsKey, id nsValue, ValueDict& 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, ValueArray& array) +static void addItemToArray(id item, ValueVector& array) { // add string value into array if ([item isKindOfClass:[NSString class]]) @@ -59,7 +59,7 @@ static void addItemToArray(id item, ValueArray& array) // add dictionary value into array if ([item isKindOfClass:[NSDictionary class]]) { - ValueDict dict; + ValueMap dict; for (id subKey in [item allKeys]) { id subValue = [item objectForKey:subKey]; @@ -73,7 +73,7 @@ static void addItemToArray(id item, ValueArray& array) // add array value into array if ([item isKindOfClass:[NSArray class]]) { - ValueArray subArray; + ValueVector subArray; for (id subItem in item) { addItemToArray(subItem, subArray); @@ -94,11 +94,11 @@ static void addObjectToNSArray(Value& value, NSMutableArray *array) } // add array into array - if (value.getType() == Value::Type::ARRAY) + if (value.getType() == Value::Type::VECTOR) { NSMutableArray *arrElement = [NSMutableArray array]; - ValueArray valueArray = value.asArray(); + ValueVector valueArray = value.asValueVector(); std::for_each(valueArray.begin(), valueArray.end(), [=](Value& e){ addObjectToNSArray(e, arrElement); @@ -109,11 +109,11 @@ static void addObjectToNSArray(Value& value, NSMutableArray *array) } // add dictionary value into array - if (value.getType() == Value::Type::DICTIONARY) + if (value.getType() == Value::Type::MAP) { NSMutableDictionary *dictElement = [NSMutableDictionary dictionary]; - auto valueDict = value.asDict(); + auto valueDict = value.asValueMap(); for (auto iter = valueDict.begin(); iter != valueDict.end(); ++iter) { addObjectToNSDict(iter->first, iter->second, dictElement); @@ -123,7 +123,7 @@ static void addObjectToNSArray(Value& value, NSMutableArray *array) } } -static void addValueToDict(id nsKey, id nsValue, ValueDict& dict) +static void addValueToDict(id nsKey, id nsValue, ValueMap& dict) { // the key must be a string CCASSERT([nsKey isKindOfClass:[NSString class]], "The key should be a string!"); @@ -146,7 +146,7 @@ static void addValueToDict(id nsKey, id nsValue, ValueDict& dict) // the value is a new dictionary if ([nsValue isKindOfClass:[NSDictionary class]]) { - ValueDict subDict; + ValueMap subDict; for (id subKey in [nsValue allKeys]) { @@ -160,7 +160,7 @@ static void addValueToDict(id nsKey, id nsValue, ValueDict& dict) // the value is a array if ([nsValue isKindOfClass:[NSArray class]]) { - ValueArray valueArray; + ValueVector valueArray; for (id item in nsValue) { @@ -176,10 +176,10 @@ static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDic NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding]; // the object is a Dictionary - if (value.getType() == Value::Type::DICTIONARY) + if (value.getType() == Value::Type::MAP) { NSMutableDictionary *dictElement = [NSMutableDictionary dictionary]; - ValueDict subDict = value.asDict(); + ValueMap subDict = value.asValueMap(); for (auto iter = subDict.begin(); iter != subDict.end(); ++iter) { addObjectToNSDict(iter->first, iter->second, dictElement); @@ -198,11 +198,11 @@ static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDic } // the object is a Array - if (value.getType() == Value::Type::ARRAY) + if (value.getType() == Value::Type::VECTOR) { NSMutableArray *arrElement = [NSMutableArray array]; - ValueArray array = value.asArray(); + ValueVector array = value.asValueVector(); std::for_each(array.begin(), array.end(), [=](Value& v){ addObjectToNSArray(v, arrElement); @@ -308,13 +308,13 @@ std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string return ""; } -ValueDict FileUtilsApple::fileToValueDict(const std::string& filename) +ValueMap FileUtilsApple::fileToValueMap(const std::string& filename) { std::string fullPath = fullPathForFilename(filename); NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:path]; - ValueDict ret; + ValueMap ret; if (dict != nil) { @@ -327,7 +327,7 @@ ValueDict FileUtilsApple::fileToValueDict(const std::string& filename) return ret; } -bool FileUtilsApple::writeToFile(ValueDict& 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]; @@ -344,7 +344,7 @@ bool FileUtilsApple::writeToFile(ValueDict& dict, const std::string &fullPath) return true; } -ValueArray FileUtilsApple::fileToValueArray(const std::string& filename) +ValueVector FileUtilsApple::fileToValueVector(const std::string& filename) { // NSString* pPath = [NSString stringWithUTF8String:pFileName]; // NSString* pathExtension= [pPath pathExtension]; @@ -355,7 +355,7 @@ ValueArray FileUtilsApple::fileToValueArray(const std::string& filename) NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; NSArray* array = [NSArray arrayWithContentsOfFile:path]; - ValueArray ret; + ValueVector ret; for (id value in array) { diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index 4bb00b2ff2..c137a21970 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -478,7 +478,7 @@ Array* Array::createWithContentsOfFile(const char* fileName) Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) { - ValueArray arr = FileUtils::getInstance()->fileToValueArray(fileName); + ValueVector arr = FileUtils::getInstance()->fileToValueVector(fileName); Array* ret = Array::createWithCapacity(arr.size()); diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 3c4e4b3cfe..aca15e4a0b 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -378,25 +378,25 @@ Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) return srcDict->clone(); } -static Array* visitArray(const ValueArray& array); +static Array* visitArray(const ValueVector& array); -static Dictionary* visitDict(const ValueDict& dict) +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::DICTIONARY) + if (iter->second.getType() == Value::Type::MAP) { - const ValueDict& subDict = iter->second.asDict(); + const ValueMap& subDict = iter->second.asValueMap(); auto sub = visitDict(subDict); ret->setObject(sub, iter->first); sub->release(); } - else if (iter->second.getType() == Value::Type::ARRAY) + else if (iter->second.getType() == Value::Type::VECTOR) { - const ValueArray& arr = iter->second.asArray(); + const ValueVector& arr = iter->second.asValueVector(); auto sub = visitArray(arr); ret->setObject(sub, iter->first); sub->release(); @@ -411,22 +411,22 @@ static Dictionary* visitDict(const ValueDict& dict) return ret; } -static Array* visitArray(const ValueArray& array) +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::DICTIONARY) + if (value.getType() == Value::Type::MAP) { - const ValueDict& subDict = value.asDict(); + const ValueMap& subDict = value.asValueMap(); auto sub = visitDict(subDict); ret->addObject(sub); sub->release(); } - else if (value.getType() == Value::Type::ARRAY) + else if (value.getType() == Value::Type::VECTOR) { - const ValueArray& arr = value.asArray(); + const ValueVector& arr = value.asValueVector(); auto sub = visitArray(arr); ret->addObject(sub); sub->release(); @@ -444,7 +444,7 @@ static Array* visitArray(const ValueArray& array) Dictionary* Dictionary::createWithContentsOfFileThreadSafe(const char *pFileName) { - return visitDict(FileUtils::getInstance()->fileToValueDict(pFileName)); + return visitDict(FileUtils::getInstance()->fileToValueMap(pFileName)); } void Dictionary::acceptVisitor(DataVisitor &visitor) @@ -464,7 +464,7 @@ Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName) bool Dictionary::writeToFile(const char *fullPath) { - ValueDict dict; + ValueMap dict; DictElement* element = nullptr; CCDICT_FOREACH(this, element) { diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 63a5167ab8..41f18db6b3 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -28,143 +28,143 @@ NS_CC_BEGIN Value::Value() -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::NONE) { } Value::Value(int v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::INTEGER) { _baseData.intVal = v; } Value::Value(float v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::FLOAT) { _baseData.floatVal = v; } Value::Value(double v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::DOUBLE) { _baseData.doubleVal = v; } Value::Value(bool v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::BOOLEAN) { _baseData.boolVal = v; } Value::Value(const char* v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::STRING) { _strData = v; } Value::Value(const std::string& v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) , _type(Type::STRING) { _strData = v; } -Value::Value(const ValueArray& v) -: _arrData(new ValueArray()) -, _dictData(nullptr) -, _intKeyDictData(nullptr) -, _type(Type::ARRAY) +Value::Value(const ValueVector& v) +: _vectorData(new ValueVector()) +, _mapData(nullptr) +, _intKeyMapData(nullptr) +, _type(Type::VECTOR) { - *_arrData = v; + *_vectorData = v; } -Value::Value(ValueArray&& v) -: _arrData(new ValueArray()) -, _dictData(nullptr) -, _intKeyDictData(nullptr) -, _type(Type::ARRAY) +Value::Value(ValueVector&& v) +: _vectorData(new ValueVector()) +, _mapData(nullptr) +, _intKeyMapData(nullptr) +, _type(Type::VECTOR) { - *_arrData = std::move(v); + *_vectorData = std::move(v); } -Value::Value(const ValueDict& v) -: _arrData(nullptr) -, _dictData(new ValueDict()) -, _intKeyDictData(nullptr) -, _type(Type::DICTIONARY) +Value::Value(const ValueMap& v) +: _vectorData(nullptr) +, _mapData(new ValueMap()) +, _intKeyMapData(nullptr) +, _type(Type::MAP) { - *_dictData = v; + *_mapData = v; } -Value::Value(ValueDict&& v) -: _arrData(nullptr) -, _dictData(new ValueDict()) -, _intKeyDictData(nullptr) -, _type(Type::DICTIONARY) +Value::Value(ValueMap&& v) +: _vectorData(nullptr) +, _mapData(new ValueMap()) +, _intKeyMapData(nullptr) +, _type(Type::MAP) { - *_dictData = std::move(v); + *_mapData = std::move(v); } -Value::Value(const IntValueDict& v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(new IntValueDict()) -, _type(Type::INT_KEY_DICT) +Value::Value(const IntValueMap& v) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(new IntValueMap()) +, _type(Type::INT_KEY_MAP) { - *_intKeyDictData = v; + *_intKeyMapData = v; } -Value::Value(IntValueDict&& v) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(new IntValueDict()) -, _type(Type::INT_KEY_DICT) +Value::Value(IntValueMap&& v) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(new IntValueMap()) +, _type(Type::INT_KEY_MAP) { - *_intKeyDictData = std::move(v); + *_intKeyMapData = std::move(v); } Value::Value(const Value& other) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) { *this = other; } Value::Value(Value&& other) -: _arrData(nullptr) -, _dictData(nullptr) -, _intKeyDictData(nullptr) +: _vectorData(nullptr) +, _mapData(nullptr) +, _intKeyMapData(nullptr) { *this = std::move(other); } Value::~Value() { - CC_SAFE_DELETE(_arrData); - CC_SAFE_DELETE(_dictData); - CC_SAFE_DELETE(_intKeyDictData); + CC_SAFE_DELETE(_vectorData); + CC_SAFE_DELETE(_mapData); + CC_SAFE_DELETE(_intKeyMapData); } Value& Value::operator= (const Value& other) @@ -185,20 +185,20 @@ Value& Value::operator= (const Value& other) case Type::STRING: _strData = other._strData; break; - case Type::ARRAY: - if (_arrData == nullptr) - _arrData = new ValueArray(); - *_arrData = *other._arrData; + case Type::VECTOR: + if (_vectorData == nullptr) + _vectorData = new ValueVector(); + *_vectorData = *other._vectorData; break; - case Type::DICTIONARY: - if (_dictData == nullptr) - _dictData = new ValueDict(); - *_dictData = *other._dictData; + case Type::MAP: + if (_mapData == nullptr) + _mapData = new ValueMap(); + *_mapData = *other._mapData; break; - case Type::INT_KEY_DICT: - if (_intKeyDictData == nullptr) - _intKeyDictData = new IntValueDict(); - *_intKeyDictData = *other._intKeyDictData; + case Type::INT_KEY_MAP: + if (_intKeyMapData == nullptr) + _intKeyMapData = new IntValueMap(); + *_intKeyMapData = *other._intKeyMapData; break; default: break; @@ -225,26 +225,26 @@ Value& Value::operator= (Value&& other) case Type::STRING: _strData = other._strData; break; - case Type::ARRAY: - CC_SAFE_DELETE(_arrData); - _arrData = other._arrData; + case Type::VECTOR: + CC_SAFE_DELETE(_vectorData); + _vectorData = other._vectorData; break; - case Type::DICTIONARY: - CC_SAFE_DELETE(_dictData); - _dictData = other._dictData; + case Type::MAP: + CC_SAFE_DELETE(_mapData); + _mapData = other._mapData; break; - case Type::INT_KEY_DICT: - CC_SAFE_DELETE(_intKeyDictData); - _intKeyDictData = other._intKeyDictData; + case Type::INT_KEY_MAP: + CC_SAFE_DELETE(_intKeyMapData); + _intKeyMapData = other._intKeyMapData; break; default: break; } _type = other._type; - other._arrData = nullptr; - other._dictData = nullptr; - other._intKeyDictData = nullptr; + other._vectorData = nullptr; + other._mapData = nullptr; + other._intKeyMapData = nullptr; other._type = Type::NONE; return *this; @@ -252,7 +252,7 @@ Value& Value::operator= (Value&& other) int Value::asInt() const { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + CCASSERT(_type != Type::VECTOR && _type != Type::MAP, ""); if (_type == Type::INTEGER) { return _baseData.intVal; @@ -283,7 +283,7 @@ int Value::asInt() const float Value::asFloat() const { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + CCASSERT(_type != Type::VECTOR && _type != Type::MAP, ""); if (_type == Type::FLOAT) { return _baseData.floatVal; @@ -314,7 +314,7 @@ float Value::asFloat() const double Value::asDouble() const { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + CCASSERT(_type != Type::VECTOR && _type != Type::MAP, ""); if (_type == Type::DOUBLE) { return _baseData.doubleVal; @@ -345,7 +345,7 @@ double Value::asDouble() const bool Value::asBool() const { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + CCASSERT(_type != Type::VECTOR && _type != Type::MAP, ""); if (_type == Type::BOOLEAN) { return _baseData.boolVal; @@ -376,7 +376,7 @@ bool Value::asBool() const std::string Value::asString() const { - CCASSERT(_type != Type::ARRAY && _type != Type::DICTIONARY, ""); + CCASSERT(_type != Type::VECTOR && _type != Type::MAP, ""); if (_type == Type::STRING) { diff --git a/cocos/base/CCValue.h b/cocos/base/CCValue.h index dfcb910118..498cf0f1f4 100644 --- a/cocos/base/CCValue.h +++ b/cocos/base/CCValue.h @@ -35,9 +35,9 @@ NS_CC_BEGIN class Value; -typedef std::vector ValueArray; -typedef std::unordered_map ValueDict; -typedef std::unordered_map IntValueDict; +typedef std::vector ValueVector; +typedef std::unordered_map ValueMap; +typedef std::unordered_map IntValueMap; class Value { @@ -50,14 +50,14 @@ public: explicit Value(const char* v); explicit Value(const std::string& v); - explicit Value(const ValueArray& v); - explicit Value(ValueArray&& v); + explicit Value(const ValueVector& v); + explicit Value(ValueVector&& v); - explicit Value(const ValueDict& v); - explicit Value(ValueDict&& v); + explicit Value(const ValueMap& v); + explicit Value(ValueMap&& v); - explicit Value(const IntValueDict& v); - explicit Value(IntValueDict&& v); + explicit Value(const IntValueMap& v); + explicit Value(IntValueMap&& v); Value(const Value& other); Value(Value&& other); @@ -72,14 +72,14 @@ public: bool asBool() const; std::string asString() const; - inline ValueArray& asArray() { return *_arrData; } - inline const ValueArray& asArray() const { return *_arrData; } + inline ValueVector& asValueVector() { return *_vectorData; } + inline const ValueVector& asValueVector() const { return *_vectorData; } - inline ValueDict& asDict() { return *_dictData; } - inline const ValueDict& asDict() const { return *_dictData; } + inline ValueMap& asValueMap() { return *_mapData; } + inline const ValueMap& asValueMap() const { return *_mapData; } - inline IntValueDict& asIntKeyDict() { return *_intKeyDictData; } - inline const IntValueDict& asIntKeyDict() const { return *_intKeyDictData; } + inline IntValueMap& asIntKeyMap() { return *_intKeyMapData; } + inline const IntValueMap& asIntKeyMap() const { return *_intKeyMapData; } inline bool isNull() const { return _type == Type::NONE; } @@ -91,9 +91,9 @@ public: DOUBLE, BOOLEAN, STRING, - ARRAY, - DICTIONARY, - INT_KEY_DICT + VECTOR, + MAP, + INT_KEY_MAP }; inline Type getType() const { return _type; }; @@ -108,9 +108,9 @@ private: }_baseData; std::string _strData; - ValueArray* _arrData; - ValueDict* _dictData; - IntValueDict* _intKeyDictData; + ValueVector* _vectorData; + ValueMap* _mapData; + IntValueMap* _intKeyMapData; Type _type; }; diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp index d8a2766357..0433711a73 100644 --- a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -233,7 +233,7 @@ void TestFilenameLookup::onEnter() auto sharedFileUtils = FileUtils::getInstance(); - ValueDict dict; + ValueMap dict; dict["grossini.bmp"] = Value("Images/grossini.png"); dict["grossini.xcf"] = Value("Images/grossini.png"); @@ -253,7 +253,7 @@ void TestFilenameLookup::onExit() FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset filename lookup - sharedFileUtils->setFilenameLookupDictionary(ValueDict()); + sharedFileUtils->setFilenameLookupDictionary(ValueMap()); FileUtilsDemo::onExit(); } @@ -297,7 +297,7 @@ void TestIsFileExist::onExit() FileUtils *sharedFileUtils = FileUtils::getInstance(); // reset filename lookup - sharedFileUtils->setFilenameLookupDictionary(ValueDict()); + sharedFileUtils->setFilenameLookupDictionary(ValueMap()); FileUtilsDemo::onExit(); } diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 5f6b6fa13e..4390b52f33 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -589,7 +589,7 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest() for (auto& obj : objects) { - ValueDict& dict = obj.asDict(); + ValueMap& dict = obj.asValueMap(); ////----CCLOG("object: %x", dict); } @@ -607,7 +607,7 @@ void TMXOrthoObjectsTest::draw() for (auto& obj : objects) { - ValueDict& dict = obj.asDict(); + ValueMap& dict = obj.asValueMap(); float x = dict["x"].asFloat(); float y = dict["y"].asFloat(); @@ -657,7 +657,7 @@ TMXIsoObjectsTest::TMXIsoObjectsTest() //UxMutableDictionary* dict; for (auto& obj : objects) { - ValueDict& dict = obj.asDict(); + ValueMap& dict = obj.asValueMap(); ////----CCLOG("object: %x", dict); } @@ -671,7 +671,7 @@ void TMXIsoObjectsTest::draw() auto& objects = group->getObjects(); for (auto& obj : objects) { - ValueDict& dict = obj.asDict(); + ValueMap& dict = obj.asValueMap(); float x = dict["x"].asFloat(); float y = dict["y"].asFloat(); float width = dict["width"].asFloat(); @@ -1455,7 +1455,7 @@ void TMXGIDObjectsTest::draw() auto& objects = group->getObjects(); for (auto& obj : objects) { - ValueDict& dict = obj.asDict(); + ValueMap& dict = obj.asValueMap(); float x = dict["x"].asFloat(); float y = dict["y"].asFloat(); From c9767b8ea01d36ec87119b154bc335ec48691d96 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 17:50:57 +0800 Subject: [PATCH 042/107] =?UTF-8?q?issue=20#2790:=20fileToValueDict=20?= =?UTF-8?q?=E2=80=94>=20getValueMapFromFile,=20fileToValueArray=20?= =?UTF-8?q?=E2=80=94>=20getValueVectorFromFile.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCAnimationCache.cpp | 2 +- cocos/2d/CCParticleSystem.cpp | 2 +- cocos/2d/CCSpriteFrameCache.cpp | 6 +++--- cocos/2d/platform/CCFileUtils.cpp | 10 +++++----- cocos/2d/platform/CCFileUtils.h | 4 ++-- cocos/2d/platform/apple/CCFileUtilsApple.h | 4 ++-- cocos/2d/platform/apple/CCFileUtilsApple.mm | 4 ++-- cocos/base/CCArray.cpp | 2 +- cocos/base/CCDictionary.cpp | 2 +- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 4a600504ce..c76ccec235 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -226,7 +226,7 @@ void AnimationCache::addAnimationsWithFile(const std::string& plist) CCASSERT( plist.size()>0, "Invalid texture file name"); std::string path = FileUtils::getInstance()->fullPathForFilename(plist); - ValueMap dict = FileUtils::getInstance()->fileToValueMap(path); + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(path); CCASSERT( !dict.empty(), "CCAnimationCache: File could not be found"); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 392452d1cf..9c58e15c9a 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -169,7 +169,7 @@ bool ParticleSystem::initWithFile(const std::string& plistFile) { bool bRet = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); - ValueMap dict = FileUtils::getInstance()->fileToValueMap(_plistFile.c_str()); + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(_plistFile.c_str()); CCASSERT( !dict.empty(), "Particles: file not found"); diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 3d58ab6001..d16802ffec 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -199,7 +199,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); - ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); addSpriteFramesWithDictionary(dict, pobTexture); } @@ -226,7 +226,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end()) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); - ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); string texturePath(""); @@ -335,7 +335,7 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); - ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); if (dict.empty()) { CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str()); diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 58ef862c59..3959ee98f5 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -303,14 +303,14 @@ public: } }; -ValueMap FileUtils::fileToValueMap(const std::string& filename) +ValueMap FileUtils::getValueMapFromFile(const std::string& filename) { std::string fullPath = fullPathForFilename(filename.c_str()); DictMaker tMaker; return std::move(tMaker.dictionaryWithContentsOfFile(fullPath.c_str())); } -ValueVector FileUtils::fileToValueVector(const std::string& filename) +ValueVector FileUtils::getValueVectorFromFile(const std::string& filename) { std::string fullPath = fullPathForFilename(filename.c_str()); DictMaker tMaker; @@ -456,8 +456,8 @@ static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ -ValueMap FileUtils::fileToValueMap(const std::string& filename) {return ValueMap();} -ValueVector FileUtils::fileToValueVector(const std::string& filename) {return ValueVector();} +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) */ @@ -749,7 +749,7 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename std::string fullPath = fullPathForFilename(filename); if (fullPath.length() > 0) { - ValueMap dict = FileUtils::getInstance()->fileToValueMap(fullPath); + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); if (!dict.empty()) { ValueMap& metadata = dict["metadata"].asValueMap(); diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 9bdf4f632d..be2f3f2af7 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -300,7 +300,7 @@ public: * Converts the contents of a file to a ValueMap. * @note This method is used internally. */ - virtual ValueMap fileToValueMap(const std::string& filename); + virtual ValueMap getValueMapFromFile(const std::string& filename); /** * Write a ValueMap to a plist file. @@ -312,7 +312,7 @@ public: * Converts the contents of a file to a ValueVector. * @note This method is used internally. */ - virtual ValueVector fileToValueVector(const std::string& filename); + virtual ValueVector getValueVectorFromFile(const std::string& filename); protected: /** diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.h b/cocos/2d/platform/apple/CCFileUtilsApple.h index 5bcb76732d..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 ValueMap fileToValueMap(const std::string& filename) override; + virtual ValueMap getValueMapFromFile(const std::string& filename) override; virtual bool writeToFile(ValueMap& dict, const std::string& fullPath) override; - virtual ValueVector fileToValueVector(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 0b18e49b7e..11b2644a6b 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -308,7 +308,7 @@ std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string return ""; } -ValueMap FileUtilsApple::fileToValueMap(const std::string& filename) +ValueMap FileUtilsApple::getValueMapFromFile(const std::string& filename) { std::string fullPath = fullPathForFilename(filename); NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; @@ -344,7 +344,7 @@ bool FileUtilsApple::writeToFile(ValueMap& dict, const std::string &fullPath) return true; } -ValueVector FileUtilsApple::fileToValueVector(const std::string& filename) +ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename) { // NSString* pPath = [NSString stringWithUTF8String:pFileName]; // NSString* pathExtension= [pPath pathExtension]; diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index c137a21970..27b04422a6 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -478,7 +478,7 @@ Array* Array::createWithContentsOfFile(const char* fileName) Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) { - ValueVector arr = FileUtils::getInstance()->fileToValueVector(fileName); + ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName); Array* ret = Array::createWithCapacity(arr.size()); diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index aca15e4a0b..107203285f 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -444,7 +444,7 @@ static Array* visitArray(const ValueVector& array) Dictionary* Dictionary::createWithContentsOfFileThreadSafe(const char *pFileName) { - return visitDict(FileUtils::getInstance()->fileToValueMap(pFileName)); + return visitDict(FileUtils::getInstance()->getValueMapFromFile(pFileName)); } void Dictionary::acceptVisitor(DataVisitor &visitor) From 28eed3c8e0cbd8228c9e0b4b8ff71e12b0ada977 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 4 Dec 2013 17:51:53 +0800 Subject: [PATCH 043/107] issue #2790: Reverts HelloWorldScene.cpp. --- .../Cpp/HelloCpp/Classes/HelloWorldScene.cpp | 91 +------------------ 1 file changed, 1 insertion(+), 90 deletions(-) diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp index eab8247f4a..077a92aa11 100644 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp +++ b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp @@ -2,10 +2,10 @@ #include "AppMacros.h" #include "CCEventListenerTouch.h" -#include "CCVector.h" USING_NS_CC; + Scene* HelloWorld::scene() { // 'scene' is an autorelease object @@ -21,94 +21,9 @@ Scene* HelloWorld::scene() return scene; } -void showSprites(const Vector& sprites) -{ - log("container size = %ld", sprites.count()); - for (auto& sp : sprites) - { - log("sp tag: %d, ref count = %d", sp->getTag(), sp->retainCount()); - } -} - -Vector createAllSprites() -{ - Vector ret; - ret.addObject(Sprite::create()); - ret.addObject(Sprite::create()); - return ret; -} - // on "init" you need to initialize your instance bool HelloWorld::init() { - - Vector container; - - for (int i = 0; i < 10; ++i) - { - auto sp = Sprite::create(); - sp->setTag(i); - container.addObject(sp); - } - -// -// showSprites(container); -// -// Vector containerCopy = container; -// -// showSprites(containerCopy); -// -// containerCopy = container; -// -// showSprites(containerCopy); - -// Vector moveVector(createAllSprites()); -// showSprites(moveVector); -// -// CCLOG("------------- 2 ----------"); -// moveVector = createAllSprites(); -// showSprites(moveVector); -// -// CCLOG("------------- 3 ----------"); -// Vector aaa; -// aaa.addObject(Sprite::create()); -// moveVector = aaa; -// showSprites(moveVector); - - log("size of Vector = %ld", sizeof(Vector)); - - Map map; - map.setObject(Sprite::create(), "1"); - map.setObject(Sprite::create(), "2"); - map.setObject(Sprite::create(), "3"); - - auto showMap = [](const Map& map) - { - for (auto iter = map.begin(); iter != map.end(); ++iter) - { - log("key = %s, value = %p, ref = %d", iter->first.c_str(), iter->second, iter->second ? iter->second->retainCount() : 0); - } - }; - - showMap(map); - -// auto iter = std::find(map.begin(), map.end(), std::string("111")); -// if (iter != map.end()) -// { -// log("found!"); -// } -// else -// { -// log("not found!"); -// } - -// map["111"]; -// log("key[1]=%p", map["1"]); -// log("----------------------"); -// map["11"]->setPosition(Point(100, 100)); - - showMap(map); - ////////////////////////////// // 1. super init first if ( !Layer::init() ) @@ -160,10 +75,6 @@ bool HelloWorld::init() // add the sprite as a child to this layer this->addChild(sprite); - this->getChildren().forEach([](Node* node){ - log("node = %p, name = %s", node, typeid(*node).name()); - }); - return true; } From 245d33e4ad44f581611491ac86237f2113774db0 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 12:26:43 -0800 Subject: [PATCH 044/107] Fixes several bugs in the console. [*] Doesn't crash [*] Closes connection [*] Its faster --- cocos/CCConsole.cpp | 41 ++++++++++++++++++++++------------------- cocos/CCConsole.h | 5 ++++- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/cocos/CCConsole.cpp b/cocos/CCConsole.cpp index 42ba70f8c4..a18984e2cd 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/CCConsole.cpp @@ -11,15 +11,15 @@ #include #include +#include +#include #include +#include +#include #include -#include +#include #include #include -#include -#include -#include -#include #include "CCDirector.h" #include "CCScheduler.h" @@ -114,9 +114,6 @@ void Console::cancel() { if( _running ) { _endThread = true; - if( _listenfd ) - write(_listenfd,"\n",1); - _thread.join(); } } @@ -172,21 +169,22 @@ void Console::loop() fd_set read_set, copy_set; struct sockaddr client; socklen_t client_len; - int fd; struct timeval timeout, timeout_copy; FD_ZERO(&read_set); FD_SET(_listenfd, &read_set); - _max_fd = _listenfd; + _maxfd = _listenfd; timeout.tv_sec = 0; - timeout.tv_usec = 50000; /* 0.05 secons */ + + /* 0.016 seconds. Wake up once per frame at 60PFS */ + timeout.tv_usec = 016000; while(!_endThread) { - copy_set = read_set; + FD_COPY(&read_set, ©_set); timeout_copy = timeout; - int nready = select(_max_fd+1, ©_set, NULL, NULL, &timeout_copy); + int nready = select(_maxfd+1, ©_set, NULL, NULL, &timeout_copy); if( nready == -1 ) { /* error ?*/ @@ -203,13 +201,13 @@ void Console::loop() if(FD_ISSET(_listenfd, ©_set)) { /* new client */ client_len = sizeof( client ); - fd = accept(_listenfd, (struct sockaddr *)&client, &client_len ); + int fd = accept(_listenfd, (struct sockaddr *)&client, &client_len ); // add fd to list of FD if( fd != -1 ) { FD_SET(fd, &read_set); - if(fd > _max_fd) - _max_fd = fd; + _fds.push_back(fd); + _maxfd = std::max(_maxfd,fd); } if(--nready <= 0) @@ -217,8 +215,8 @@ void Console::loop() } /* input from client */ - for(fd=0; fd <= _max_fd; fd++) { - if( fd != _listenfd && FD_ISSET(fd,©_set) ) { + for(const auto &fd: _fds) { + if(FD_ISSET(fd,©_set)) { readline(fd); parseToken(); log("read: %s", _buffer); @@ -226,5 +224,10 @@ void Console::loop() break; } } - } + } + + // clean up: ignore stdin, stdout and stderr + for(const auto &fd: _fds ) + close(fd); + close(_listenfd); } diff --git a/cocos/CCConsole.h b/cocos/CCConsole.h index acf674f6f1..be3dfe938e 100644 --- a/cocos/CCConsole.h +++ b/cocos/CCConsole.h @@ -10,6 +10,7 @@ #define __cocos2d_libs__CCConsole__ #include +#include #include "ccMacros.h" #include "base/CCObject.h" @@ -49,8 +50,10 @@ protected: // file descriptor: socket, console, etc. int _listenfd; - int _max_fd; + int _maxfd; + std::vector _fds; std::thread _thread; + bool _running; bool _endThread; From ef18d4891ecb4f3127b6d3444259ed1f92c1b641 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 16:26:21 -0800 Subject: [PATCH 045/107] More bug fixes --- cocos/CCConsole.cpp | 204 +++++++++++++----- cocos/CCConsole.h | 82 +++++-- .../Classes/ConsoleTest/ConsoleTest.cpp | 4 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../TestCpp/Classes/SpriteTest/SpriteTest.h | 24 +++ 5 files changed, 236 insertions(+), 80 deletions(-) diff --git a/cocos/CCConsole.cpp b/cocos/CCConsole.cpp index a18984e2cd..65af34ab94 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/CCConsole.cpp @@ -1,10 +1,26 @@ -// -// CCConsole.cpp -// cocos2d_libs -// -// Created by Ricardo Quesada on 11/26/13. -// -// +/**************************************************************************** + 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" @@ -17,7 +33,6 @@ #include #include #include -#include #include #include @@ -39,12 +54,27 @@ Console::Console() : _listenfd(-1) , _running(false) , _endThread(false) -{ - _scheduler = Director::getInstance()->getScheduler(); +, _tokens{ + { "fps on", [](int anFd) { + Director *dir = Director::getInstance(); + Scheduler *sched = dir->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, true)); + } }, + { "fps off", [](int anFd) { + Director *dir = Director::getInstance(); + Scheduler *sched = dir->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, false)); + } }, + { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1) }, + { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, } +{ + _maxTokens = 4; + } Console::~Console() { + cancel(); } bool Console::listenOnTCP(int port) @@ -86,24 +116,28 @@ bool Console::listenOnTCP(int port) freeaddrinfo(ressave); return false; } - + listen(listenfd, 50); - + + if (res->ai_family == AF_INET) { + char buf2[256] = ""; + gethostname(buf2, sizeof(buf2)-1); + char buf[INET_ADDRSTRLEN] = ""; + struct sockaddr_in *sin = (struct sockaddr_in*) res->ai_addr; + if( inet_ntop(res->ai_family, sin , buf, sizeof(buf)) != NULL ) + CCLOG("Console: listening on %s : %d", buf2, ntohs(sin->sin_port)); + else + perror("inet_ntop"); + } + freeaddrinfo(ressave); - CCLOG("Console: listening on port %d", port); return listenOnFileDescriptor(listenfd); } -bool Console::listenOnStdin() -{ - return listenOnFileDescriptor(STDIN_FILENO); -} - bool Console::listenOnFileDescriptor(int fd) { CCASSERT(!_running, "already running"); - _running = true; _listenfd = fd; _thread = std::thread( std::bind( &Console::loop, this) ); @@ -118,29 +152,68 @@ void Console::cancel() } } -void Console::parseToken() + +// +// commands +// + +void Console::commandHelp(int fd) { - struct _tokens { - const char * func_name; - std::function callback; - } tokens[] { - { "fps on", []() { Director::getInstance()->setDisplayStats(true); } }, - { "fps off", []() { Director::getInstance()->setDisplayStats(false); } }, - }; + const char help[] = "\nAvailable commands:\n"; + write(fd, help, sizeof(help)); + for(int i=0; i<_maxTokens; ++i) { + write(fd,"\t",1); + write(fd, _tokens[i].func_name, strlen(_tokens[i].func_name)); + write(fd,"\n",1); + } +} - const int max = sizeof(tokens) / sizeof(tokens[0]); +void Console::commandExit(int fd) +{ + FD_CLR(fd, &_read_set); + _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); + close(fd); +} - Scheduler *sched = Director::getInstance()->getScheduler(); - for( int i=0; i < max; ++i) { - if( strncmp(_buffer, tokens[i].func_name,strlen(tokens[i].func_name)) == 0 ) - sched->performFunctionInCocosThread( tokens[i].callback ); +bool Console::parseToken(int fd) +{ + auto r = readline(fd); + if(r < 1) + return false; + + int i=0; + for( ; i < _maxTokens; ++i) { + if( strncmp(_buffer, _tokens[i].func_name,strlen(_tokens[i].func_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 + _tokens[i].callback(fd); + break; + } + } + if(i == _maxTokens) { + 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 = 512; + int maxlen = sizeof(_buffer)-1; ssize_t n, rc; char c, *ptr; @@ -164,15 +237,38 @@ ssize_t Console::readline(int fd) return n; } +void Console::addClient() +{ + struct sockaddr client; + socklen_t client_len; + + /* new client */ + client_len = sizeof( client ); + int fd = accept(_listenfd, (struct sockaddr *)&client, &client_len ); + + // add fd to list of FD + if( fd != -1 ) { + FD_SET(fd, &_read_set); + _fds.push_back(fd); + _maxfd = std::max(_maxfd,fd); + + sendPrompt(fd); + } +} + +// +// Main Loop +// + void Console::loop() { - fd_set read_set, copy_set; - struct sockaddr client; - socklen_t client_len; + fd_set copy_set; struct timeval timeout, timeout_copy; - FD_ZERO(&read_set); - FD_SET(_listenfd, &read_set); + _running = true; + + FD_ZERO(&_read_set); + FD_SET(_listenfd, &_read_set); _maxfd = _listenfd; timeout.tv_sec = 0; @@ -182,7 +278,7 @@ void Console::loop() while(!_endThread) { - FD_COPY(&read_set, ©_set); + FD_COPY(&_read_set, ©_set); timeout_copy = timeout; int nready = select(_maxfd+1, ©_set, NULL, NULL, &timeout_copy); @@ -198,36 +294,36 @@ void Console::loop() continue; } + // new client if(FD_ISSET(_listenfd, ©_set)) { - /* new client */ - client_len = sizeof( client ); - int fd = accept(_listenfd, (struct sockaddr *)&client, &client_len ); - - // add fd to list of FD - if( fd != -1 ) { - FD_SET(fd, &read_set); - _fds.push_back(fd); - _maxfd = std::max(_maxfd,fd); - } - + addClient(); if(--nready <= 0) continue; } - /* input from client */ + // data from client + std::vector to_remove; for(const auto &fd: _fds) { if(FD_ISSET(fd,©_set)) { - readline(fd); - parseToken(); - log("read: %s", _buffer); + if( ! parseToken(fd) ) { + to_remove.push_back(fd); + } if(--nready <= 0) break; } } + + // remove closed conections + for(const auto &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; } diff --git a/cocos/CCConsole.h b/cocos/CCConsole.h index be3dfe938e..9d5667d109 100644 --- a/cocos/CCConsole.h +++ b/cocos/CCConsole.h @@ -1,16 +1,36 @@ -// -// CCConsole.h -// cocos2d_libs -// -// Created by Ricardo Quesada on 11/26/13. -// -// +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org -#ifndef __cocos2d_libs__CCConsole__ -#define __cocos2d_libs__CCConsole__ + 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__ + +#include #include #include +#include #include "ccMacros.h" #include "base/CCObject.h" @@ -18,35 +38,45 @@ NS_CC_BEGIN -class Scheduler; - +/** 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: + /** creates a new instnace of the Console */ static Console* create(); + /** starts listening to specifed TCP port */ bool listenOnTCP(int port); - bool listenOnStdin(); + + /** starts listening to specifed file descriptor */ bool listenOnFileDescriptor(int fd); + /** cancels the Console. Cancel will be called at destruction time as well */ void cancel(); - int getFileDescriptor() const { return _listenfd; } - void setFileDescriptor(int fd) { _listenfd = fd; } - - protected: Console(); virtual ~Console(); - ssize_t readline(int fd); - void loop(); - void parseToken(); - // weak ref - Scheduler *_scheduler; + ssize_t readline(int fd); + bool parseToken(int fd); + void sendPrompt(int fd); + void addClient(); + + // Add commands here + void commandHelp(int fd); + void commandExit(int fd); // file descriptor: socket, console, etc. int _listenfd; @@ -54,11 +84,19 @@ protected: std::vector _fds; std::thread _thread; + fd_set _read_set; + bool _running; bool _endThread; char _buffer[512]; + struct Tokens { + const char * func_name; + const std::function callback; + } _tokens[15]; + int _maxTokens; + private: CC_DISALLOW_COPY_AND_ASSIGN(Console); }; @@ -66,4 +104,4 @@ private: NS_CC_END -#endif /* defined(__cocos2d_libs__CCConsole__) */ +#endif /* defined(__CCCONSOLE_H__) */ diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp index ec20c15d52..e9e3903c4d 100644 --- a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -133,7 +133,6 @@ ConsoleTCP::ConsoleTCP() ConsoleTCP::~ConsoleTCP() { - _console->cancel(); _console->release(); } @@ -162,14 +161,13 @@ ConsoleStdin::ConsoleStdin() ConsoleStdin::~ConsoleStdin() { - _console->cancel(); _console->release(); } void ConsoleStdin::onEnter() { BaseTestConsole::onEnter(); - _console->listenOnStdin(); +// _console->listenOnStdin(); } std::string ConsoleStdin::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..0fec05298f 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 +d88c60ebf07ab1a9b0db9d032354310878f868a3 \ 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_ From e41deeee86757bd52de67e400feac8f183b473ee Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 16:57:44 -0800 Subject: [PATCH 046/107] Adds Scene Graph command --- cocos/CCConsole.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++++- cocos/CCConsole.h | 1 + 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/cocos/CCConsole.cpp b/cocos/CCConsole.cpp index 65af34ab94..c0171b4d7a 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/CCConsole.cpp @@ -39,6 +39,13 @@ #include "CCDirector.h" #include "CCScheduler.h" +#include "CCScene.h" +#include "CCSprite.h" +#include "CCLabelBMFont.h" +#include "CCMenu.h" +#include "CCMenuItem.h" +#include "CCLayer.h" + using namespace cocos2d; Console* Console::create() @@ -65,11 +72,12 @@ Console::Console() Scheduler *sched = dir->getScheduler(); sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, false)); } }, + { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1) }, { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1) }, { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, } { - _maxTokens = 4; + _maxTokens = 5; } Console::~Console() @@ -175,6 +183,45 @@ void Console::commandExit(int fd) close(fd); } +void printSceneGraph(int fd, Node* node, int level) +{ + for(int i=0; i(node) ) + type = "Scene"; + else if( dynamic_cast(node) ) + type = "Sprite"; + else if( dynamic_cast(node) ) + type = "Label"; + else if( dynamic_cast(node) ) + type = "Menu"; + else if( dynamic_cast(node) ) + type = "MenuItem"; + + dprintf(fd, " %s: z=%d, tag=%d\n", type.c_str(), node->getZOrder(), node->getTag() ); + + auto children = node->getChildren(); + if( children ) { + for(const auto& child: *children ) + printSceneGraph(fd, (Node*)child, level+1); + } +} + +void printSceneGraphBoot(int fd) +{ + write(fd,"\n",1); + auto scene = Director::getInstance()->getRunningScene(); + printSceneGraph(fd, scene, 0); + write(fd,"\n",1); +} + +void Console::commandSceneGraph(int fd) +{ + Scheduler *sched = Director::getInstance()->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) ); +} + bool Console::parseToken(int fd) { auto r = readline(fd); diff --git a/cocos/CCConsole.h b/cocos/CCConsole.h index 9d5667d109..9714b438d5 100644 --- a/cocos/CCConsole.h +++ b/cocos/CCConsole.h @@ -77,6 +77,7 @@ protected: // Add commands here void commandHelp(int fd); void commandExit(int fd); + void commandSceneGraph(int fd); // file descriptor: socket, console, etc. int _listenfd; From c2a88154af2a14878e49efb555fc64d8a203718d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 17:38:11 -0800 Subject: [PATCH 047/107] Custom commands are working OK --- cocos/CCConsole.cpp | 69 +++++++++++-------- cocos/CCConsole.h | 19 +++-- .../Classes/ConsoleTest/ConsoleTest.cpp | 26 ++++--- .../TestCpp/Classes/ConsoleTest/ConsoleTest.h | 10 +-- 4 files changed, 75 insertions(+), 49 deletions(-) diff --git a/cocos/CCConsole.cpp b/cocos/CCConsole.cpp index c0171b4d7a..62cd20e1c6 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/CCConsole.cpp @@ -40,11 +40,6 @@ #include "CCScheduler.h" #include "CCScene.h" -#include "CCSprite.h" -#include "CCLabelBMFont.h" -#include "CCMenu.h" -#include "CCMenuItem.h" -#include "CCLayer.h" using namespace cocos2d; @@ -61,7 +56,10 @@ Console::Console() : _listenfd(-1) , _running(false) , _endThread(false) -, _tokens{ +, _userCommands(nullptr) +, _maxUserCommands(0) +, _maxCommands(5) +, _commands{ { "fps on", [](int anFd) { Director *dir = Director::getInstance(); Scheduler *sched = dir->getScheduler(); @@ -77,8 +75,7 @@ Console::Console() { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, } { - _maxTokens = 5; - } +} Console::~Console() { @@ -160,6 +157,12 @@ void Console::cancel() } } +void Console::setUserCommands(Command *commands, int numberOfCommands) +{ + _userCommands = commands; + _maxUserCommands = numberOfCommands; +} + // // commands @@ -169,11 +172,19 @@ void Console::commandHelp(int fd) { const char help[] = "\nAvailable commands:\n"; write(fd, help, sizeof(help)); - for(int i=0; i<_maxTokens; ++i) { + for(int i=0; i<_maxCommands; ++i) { write(fd,"\t",1); - write(fd, _tokens[i].func_name, strlen(_tokens[i].func_name)); + 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) @@ -187,19 +198,8 @@ void printSceneGraph(int fd, Node* node, int level) { for(int i=0; i(node) ) - type = "Scene"; - else if( dynamic_cast(node) ) - type = "Sprite"; - else if( dynamic_cast(node) ) - type = "Label"; - else if( dynamic_cast(node) ) - type = "Menu"; - else if( dynamic_cast(node) ) - type = "MenuItem"; - dprintf(fd, " %s: z=%d, tag=%d\n", type.c_str(), node->getZOrder(), node->getTag() ); + dprintf(fd, " %s: z=%d, tag=%d\n", node->description(), node->getZOrder(), node->getTag() ); auto children = node->getChildren(); if( children ) { @@ -222,24 +222,35 @@ void Console::commandSceneGraph(int fd) sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) ); } -bool Console::parseToken(int fd) +bool Console::parseCommand(int fd) { auto r = readline(fd); if(r < 1) return false; - int i=0; - for( ; i < _maxTokens; ++i) { - if( strncmp(_buffer, _tokens[i].func_name,strlen(_tokens[i].func_name)) == 0 ) { + 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 - _tokens[i].callback(fd); + _commands[i].callback(fd); + found = true; break; } } - if(i == _maxTokens) { + + // 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); + found = true; + break; + } + } + + if(!found) { const char err[] = "Unknown command. Type 'help' for options\n"; write(fd, err, sizeof(err)); } @@ -352,7 +363,7 @@ void Console::loop() std::vector to_remove; for(const auto &fd: _fds) { if(FD_ISSET(fd,©_set)) { - if( ! parseToken(fd) ) { + if( ! parseCommand(fd) ) { to_remove.push_back(fd); } if(--nready <= 0) diff --git a/cocos/CCConsole.h b/cocos/CCConsole.h index 9714b438d5..6fa8157ef9 100644 --- a/cocos/CCConsole.h +++ b/cocos/CCConsole.h @@ -49,8 +49,13 @@ NS_CC_BEGIN */ class CC_DLL Console : public Object { - public: + + struct Command { + const char *name; + const std::function callback; + }; + /** creates a new instnace of the Console */ static Console* create(); @@ -63,6 +68,9 @@ public: /** 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(); @@ -70,7 +78,7 @@ protected: void loop(); ssize_t readline(int fd); - bool parseToken(int fd); + bool parseCommand(int fd); void sendPrompt(int fd); void addClient(); @@ -92,11 +100,8 @@ protected: char _buffer[512]; - struct Tokens { - const char * func_name; - const std::function callback; - } _tokens[15]; - int _maxTokens; + struct Command _commands[15], *_userCommands; + int _maxCommands, _maxUserCommands; private: CC_DISALLOW_COPY_AND_ASSIGN(Console); diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp index e9e3903c4d..353931cdfe 100644 --- a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -25,6 +25,8 @@ #include "ConsoleTest.h" #include "../testResource.h" +#include + //------------------------------------------------------------------ // // EaseSpriteDemo @@ -36,7 +38,7 @@ static int sceneIdx = -1; static std::function createFunctions[] = { CL(ConsoleTCP), - CL(ConsoleStdin), + CL(ConsoleCustomCommand), }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -149,28 +151,36 @@ std::string ConsoleTCP::title() //------------------------------------------------------------------ // -// ConsoleStdin +// ConsoleCustomCommand // //------------------------------------------------------------------ -ConsoleStdin::ConsoleStdin() +ConsoleCustomCommand::ConsoleCustomCommand() { _console = Console::create(); _console->retain(); + + static struct Console::Command commands[] = { + {"hello", [](int fd) { + const char msg[] = "how are you?\n"; + write(fd, msg, sizeof(msg)); + }}, + }; + _console->setUserCommands(&commands[0],1); } -ConsoleStdin::~ConsoleStdin() +ConsoleCustomCommand::~ConsoleCustomCommand() { _console->release(); } -void ConsoleStdin::onEnter() +void ConsoleCustomCommand::onEnter() { BaseTestConsole::onEnter(); -// _console->listenOnStdin(); + _console->listenOnTCP(5678); } -std::string ConsoleStdin::title() +std::string ConsoleCustomCommand::title() { - return "Console STDIN"; + return "Console Custom Commands"; } diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h index e10bd12482..e1c2801628 100644 --- a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h @@ -63,21 +63,21 @@ private: CC_DISALLOW_COPY_AND_ASSIGN(ConsoleTCP); }; -class ConsoleStdin : public BaseTestConsole +class ConsoleCustomCommand : public BaseTestConsole { public: - CREATE_FUNC(ConsoleStdin); + CREATE_FUNC(ConsoleCustomCommand); void onEnter() override; virtual std::string title() override; protected: - ConsoleStdin(); - virtual ~ConsoleStdin(); + ConsoleCustomCommand(); + virtual ~ConsoleCustomCommand(); cocos2d::Console *_console; private: - CC_DISALLOW_COPY_AND_ASSIGN(ConsoleStdin); + CC_DISALLOW_COPY_AND_ASSIGN(ConsoleCustomCommand); }; class ConsoleTestScene : public TestScene From f42aef0af86225fd26b517dd29a5ca7436aee9a7 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 18:09:23 -0800 Subject: [PATCH 048/107] Moves CCConsole.* to base/ --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/cocos2d.h | 2 +- cocos/{ => base}/CCConsole.cpp | 2 +- cocos/{ => base}/CCConsole.h | 0 samples/Cpp/TestCpp/Classes/controller.cpp | 2 -- 5 files changed, 3 insertions(+), 5 deletions(-) rename cocos/{ => base}/CCConsole.cpp (99%) rename cocos/{ => base}/CCConsole.h (100%) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 195d2a651e..023c804295 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -dfa173be6dd2c75b38aa6a33c6e53d9d013bd1d4 \ No newline at end of file +952fb6950a128b17bdd2a4ffb998c22319a95bf0 \ No newline at end of file diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index c33dddf82d..c531f62965 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -199,7 +199,7 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCNotificationCenter.h" #include "CCProfiling.h" -#include "CCConsole.h" +#include "base/CCConsole.h" #include "CCUserDefault.h" #include "CCVertex.h" diff --git a/cocos/CCConsole.cpp b/cocos/base/CCConsole.cpp similarity index 99% rename from cocos/CCConsole.cpp rename to cocos/base/CCConsole.cpp index 62cd20e1c6..927d79bec4 100644 --- a/cocos/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCConsole.h" +#include "base/CCConsole.h" #include diff --git a/cocos/CCConsole.h b/cocos/base/CCConsole.h similarity index 100% rename from cocos/CCConsole.h rename to cocos/base/CCConsole.h diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index 8cebe13e43..f6236eda73 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -15,8 +15,6 @@ struct { std::function callback; } g_aTestNames[] = { - { "ConsoleTest", []() { return new ConsoleTestScene(); } }, - // // TESTS MUST BE ORDERED ALPHABETICALLY // violators will be prosecuted From b52d535a4250b2011f0723335652f2b41e794a71 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 18:19:51 -0800 Subject: [PATCH 049/107] fixes indentation issues and some compilations issues on Linux --- cocos/base/CCConsole.cpp | 67 +++++++++++++++--------------- cocos/base/CMakeLists.txt | 1 + cocos/scripting/auto-generated | 2 +- samples/Cpp/TestCpp/CMakeLists.txt | 1 + 4 files changed, 36 insertions(+), 35 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 927d79bec4..9d57342e35 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -86,7 +86,7 @@ bool Console::listenOnTCP(int port) { int listenfd, n; const int on = 1; - struct addrinfo hints, *res, *ressave; + struct addrinfo hints, *res, *ressave; char serv[30]; snprintf(serv,sizeof(serv)-1,"%d",(unsigned int) port ); @@ -107,13 +107,13 @@ bool Console::listenOnTCP(int port) do { listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (listenfd < 0) - continue; /* error, try next one */ + continue; /* error, try next one */ setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0) - break; /* success */ + break; /* success */ - close(listenfd); /* bind error, close and try next one */ + close(listenfd); /* bind error, close and try next one */ } while ( (res = res->ai_next) != NULL); if (res == NULL) { @@ -272,33 +272,33 @@ void Console::sendPrompt(int fd) ssize_t Console::readline(int fd) { int maxlen = sizeof(_buffer)-1; - ssize_t n, rc; - char c, *ptr; + ssize_t n, rc; + char c, *ptr; ptr = _buffer; - for( n=1; n Date: Wed, 4 Dec 2013 18:28:09 -0800 Subject: [PATCH 050/107] fixes compiler errors on Linux --- cocos/base/CCConsole.cpp | 10 +++++----- cocos/base/CCConsole.h | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 9d57342e35..5cc85b6690 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -25,6 +25,7 @@ #include "base/CCConsole.h" #include +#include #include #include @@ -56,9 +57,6 @@ Console::Console() : _listenfd(-1) , _running(false) , _endThread(false) -, _userCommands(nullptr) -, _maxUserCommands(0) -, _maxCommands(5) , _commands{ { "fps on", [](int anFd) { Director *dir = Director::getInstance(); @@ -72,8 +70,10 @@ Console::Console() } }, { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1) }, { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1) }, - { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, -} + { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, } +, _maxCommands(5) +, _userCommands(nullptr) +, _maxUserCommands(0) { } diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 6fa8157ef9..4dc873671c 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -100,8 +100,10 @@ protected: char _buffer[512]; - struct Command _commands[15], *_userCommands; - int _maxCommands, _maxUserCommands; + struct Command _commands[15]; + int _maxCommands; + struct Command *_userCommands; + int _maxUserCommands; private: CC_DISALLOW_COPY_AND_ASSIGN(Console); From 499a0404d4974b27c9c2a81f5925241fdef7a2cd Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 10:35:10 +0800 Subject: [PATCH 051/107] issue #2790: Renames some functions in Vector. Makes it more like stl vector. --- cocos/2d/CCActionInterval.cpp | 26 ++-- cocos/2d/CCAnimation.cpp | 4 +- cocos/2d/CCAnimationCache.cpp | 8 +- cocos/2d/CCEventDispatcher.cpp | 6 +- cocos/2d/CCLabelBMFont.cpp | 2 +- cocos/2d/CCLayer.cpp | 30 ++--- cocos/2d/CCMenu.cpp | 4 +- cocos/2d/CCMenuItem.cpp | 22 +-- cocos/2d/CCNode.cpp | 24 ++-- cocos/2d/CCParticleBatchNode.cpp | 30 ++--- cocos/2d/CCSprite.cpp | 4 +- cocos/2d/CCSpriteBatchNode.cpp | 28 ++-- cocos/2d/CCSpriteFrameCache.cpp | 2 +- cocos/2d/CCTMXLayer.cpp | 2 +- cocos/2d/CCTMXTiledMap.cpp | 4 +- cocos/2d/CCTMXXMLParser.cpp | 34 ++--- cocos/base/CCMap.h | 6 +- cocos/base/CCVector.h | 126 ++++++++---------- .../cocosbuilder/CCBAnimationManager.cpp | 18 +-- .../cocostudio/CCActionNode.cpp | 4 +- .../editor-support/cocostudio/CCArmature.cpp | 4 +- cocos/editor-support/cocostudio/CCBone.cpp | 8 +- .../cocostudio/CCColliderDetector.cpp | 6 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 8 +- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 6 +- .../Classes/ParticleTest/ParticleTest.cpp | 6 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/TextInputTest/TextInputTest.cpp | 4 +- .../Classes/TileMapTest/TileMapTest.cpp | 4 +- 29 files changed, 212 insertions(+), 220 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 69071b7fbb..a197ccf3d2 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -203,16 +203,16 @@ Sequence* Sequence::create(const Vector& arrayOfActions) Sequence* pRet = NULL; do { - long count = arrayOfActions.count(); + long count = arrayOfActions.size(); CC_BREAK_IF(count == 0); - auto prev = arrayOfActions.getObjectAtIndex(0); + auto prev = arrayOfActions.at(0); if (count > 1) { for (long i = 1; i < count; ++i) { - prev = createWithTwoActions(prev, arrayOfActions.getObjectAtIndex(i)); + prev = createWithTwoActions(prev, arrayOfActions.at(i)); } } else @@ -576,14 +576,14 @@ Spawn* Spawn::create(const Vector& arrayOfActions) Spawn* pRet = NULL; do { - long count = arrayOfActions.count(); + long count = arrayOfActions.size(); CC_BREAK_IF(count == 0); - auto prev = 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, arrayOfActions.getObjectAtIndex(i)); + prev = createWithTwoActions(prev, arrayOfActions.at(i)); } } else @@ -2016,7 +2016,7 @@ bool Animate::initWithAnimation(Animation* animation) _origFrame = NULL; _executedLoops = 0; - _splitTimes->reserve(animation->getFrames().count()); + _splitTimes->reserve(animation->getFrames().size()); float accumUnitsOfTime = 0; float newUnitOfTimeValue = singleDuration / animation->getTotalDelayUnits(); @@ -2097,14 +2097,14 @@ void Animate::update(float t) } auto frames = _animation->getFrames(); - long numberOfFrames = frames.count(); + long numberOfFrames = frames.size(); SpriteFrame *frameToDisplay = NULL; for( int i=_nextFrame; i < numberOfFrames; i++ ) { float splitTime = _splitTimes->at(i); if( splitTime <= t ) { - AnimationFrame* frame = frames.getObjectAtIndex(i); + AnimationFrame* frame = frames.at(i); frameToDisplay = frame->getSpriteFrame(); static_cast(_target)->setDisplayFrame(frameToDisplay); @@ -2125,9 +2125,9 @@ void Animate::update(float t) Animate* Animate::reverse() const { auto oldArray = _animation->getFrames(); - Vector newArray(oldArray.count()); + Vector newArray(oldArray.size()); - if (oldArray.count() > 0) + if (oldArray.size() > 0) { for (auto iter = oldArray.crbegin(); iter != oldArray.crend(); ++iter) { @@ -2137,7 +2137,7 @@ Animate* Animate::reverse() const break; } - newArray.addObject(animFrame->clone()); + newArray.pushBack(animFrame->clone()); } } diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index eb79075f44..1f742cf6db 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -125,7 +125,7 @@ bool Animation::initWithSpriteFrames(const Vector& frames, float d for (auto& spriteFrame : frames) { auto animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap()); - _frames.addObject(animFrame); + _frames.pushBack(animFrame); _totalDelayUnits++; } @@ -164,7 +164,7 @@ Animation::~Animation(void) void Animation::addSpriteFrame(SpriteFrame* spriteFrame) { AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, 1.0f, ValueMap()); - _frames.addObject(animFrame); + _frames.pushBack(animFrame); // update duration _totalDelayUnits++; diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index c76ccec235..9cd3db6687 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -115,15 +115,15 @@ void AnimationCache::parseVersion1(const ValueMap& animations) } AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap()); - frames.addObject(animFrame); + frames.pushBack(animFrame); } - if ( frames.count() == 0 ) + 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.size() ) + 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()); } @@ -174,7 +174,7 @@ void AnimationCache::parseVersion2(const ValueMap& animations) AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asValueMap()); - array.addObject(animFrame); + array.pushBack(animFrame); } float delayPerUnit = animationDict.at("delayPerUnit").asFloat(); diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index a0831ce9ab..c71a26afaf 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -192,7 +192,7 @@ void EventDispatcher::visitTarget(Node* node) long i = 0; auto& children = node->getChildren(); - long childrenCount = children.count(); + long childrenCount = children.size(); if(childrenCount > 0) { @@ -200,7 +200,7 @@ void EventDispatcher::visitTarget(Node* node) // visit children zOrder < 0 for( ; i < childrenCount; i++ ) { - child = 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 = children.getObjectAtIndex(i); + child = children.at(i); if (child) visitTarget(child); } diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 64faa442e8..99303afa96 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -911,7 +911,7 @@ void LabelBMFont::updateLabel() int skip = 0; auto children = getChildren(); - for (int j = 0; j < children.count(); j++) + for (int j = 0; j < children.size(); j++) { Sprite* characterSprite; unsigned int justSkipped = 0; diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index c9b9d0c38d..59ed0e1841 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -978,7 +978,7 @@ LayerMultiplex* LayerMultiplex::createWithArray(const Vector& arrayOfLay void LayerMultiplex::addLayer(Layer* layer) { - _layers.addObject(layer); + _layers.pushBack(layer); } bool LayerMultiplex::init() @@ -995,17 +995,17 @@ bool LayerMultiplex::initWithLayers(Layer *layer, va_list params) { if (Layer::init()) { - _layers.setCapacity(5); - _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(_layers.getObjectAtIndex(_enabledLayer)); + this->addChild(_layers.at(_enabledLayer)); return true; } @@ -1016,11 +1016,11 @@ bool LayerMultiplex::initWithArray(const Vector& arrayOfLayers) { if (Layer::init()) { - _layers.setCapacity(arrayOfLayers.count()); - _layers.addObjectsFromArray(arrayOfLayers); + _layers.reserve(arrayOfLayers.size()); + _layers.insert(arrayOfLayers); _enabledLayer = 0; - this->addChild(_layers.getObjectAtIndex(_enabledLayer)); + this->addChild(_layers.at(_enabledLayer)); return true; } return false; @@ -1028,26 +1028,26 @@ bool LayerMultiplex::initWithArray(const Vector& 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(_layers.getObjectAtIndex(_enabledLayer), true); + this->removeChild(_layers.at(_enabledLayer), true); _enabledLayer = n; - this->addChild(_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(_layers.getObjectAtIndex(_enabledLayer), true); + this->removeChild(_layers.at(_enabledLayer), true); - _layers.replaceObjectAtIndex(_enabledLayer, nullptr); + _layers.replace(_enabledLayer, nullptr); _enabledLayer = n; - this->addChild(_layers.getObjectAtIndex(n)); + this->addChild(_layers.at(n)); } NS_CC_END diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index ac62437636..825a73a25f 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -88,11 +88,11 @@ Menu* Menu::createWithItems(MenuItem* item, va_list args) Vector items; if( item ) { - items.addObject(item); + items.pushBack(item); MenuItem *i = va_arg(args, MenuItem*); while(i) { - items.addObject(i); + items.pushBack(i); i = va_arg(args, MenuItem*); } } diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index b6f98ea424..75a32dbaf2 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -814,7 +814,7 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems.addObject(menuItem); + ret->_subItems.pushBack(menuItem); } ret->_selectedIndex = UINT_MAX; @@ -830,7 +830,7 @@ MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callba for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems.addObject(menuItem); + ret->_subItems.pushBack(menuItem); } ret->_selectedIndex = UINT_MAX; @@ -886,7 +886,7 @@ bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem * while(i) { z++; - _subItems.addObject(i); + _subItems.pushBack(i); i = va_arg(args, MenuItem*); } _selectedIndex = UINT_MAX; @@ -908,7 +908,7 @@ bool MenuItemToggle::initWithItem(MenuItem *item) if (item) { - _subItems.addObject(item); + _subItems.pushBack(item); } _selectedIndex = UINT_MAX; this->setSelectedIndex(0); @@ -921,7 +921,7 @@ bool MenuItemToggle::initWithItem(MenuItem *item) void MenuItemToggle::addSubItem(MenuItem *item) { - _subItems.addObject(item); + _subItems.pushBack(item); } MenuItemToggle::~MenuItemToggle() @@ -933,7 +933,7 @@ MenuItemToggle::~MenuItemToggle() 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); @@ -942,7 +942,7 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) currentItem->removeFromParentAndCleanup(false); } - MenuItem* item = _subItems.getObjectAtIndex(_selectedIndex); + MenuItem* item = _subItems.at(_selectedIndex); this->addChild(item, 0, kCurrentItem); Size s = item->getContentSize(); this->setContentSize(s); @@ -953,13 +953,13 @@ void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::selected() { MenuItem::selected(); - _subItems.getObjectAtIndex(_selectedIndex)->selected(); + _subItems.at(_selectedIndex)->selected(); } void MenuItemToggle::unselected() { MenuItem::unselected(); - _subItems.getObjectAtIndex(_selectedIndex)->unselected(); + _subItems.at(_selectedIndex)->unselected(); } void MenuItemToggle::activate() @@ -967,7 +967,7 @@ void MenuItemToggle::activate() // update index if( _enabled ) { - unsigned int newIndex = (_selectedIndex + 1) % _subItems.count(); + unsigned int newIndex = (_selectedIndex + 1) % _subItems.size(); this->setSelectedIndex(newIndex); } MenuItem::activate(); @@ -986,7 +986,7 @@ void MenuItemToggle::setEnabled(bool enabled) MenuItem* MenuItemToggle::getSelectedItem() { - return _subItems.getObjectAtIndex(_selectedIndex); + return _subItems.at(_selectedIndex); } NS_CC_END diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 3d200903df..c1e14d5cd1 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -397,7 +397,7 @@ void Node::setPositionY(float y) long Node::getChildrenCount() const { - return _children.count(); + return _children.size(); } /// camera getter: lazy alloc @@ -589,7 +589,7 @@ const char* Node::description() const // lazy allocs void Node::childrenAlloc(void) { - _children.setCapacity(4); + _children.reserve(4); } Node* Node::getChildByTag(int aTag) @@ -683,7 +683,7 @@ void Node::removeChild(Node* child, bool cleanup /* = true */) return; } - long index = _children.getIndexOfObject(child); + long index = _children.getIndex(child); if( index != CC_INVALID_INDEX ) this->detachChild( child, index, cleanup ); } @@ -736,7 +736,7 @@ void Node::removeAllChildrenWithCleanup(bool cleanup) } } - _children.removeAllObjects(); + _children.clear(); } } @@ -770,7 +770,7 @@ void Node::detachChild(Node *child, long childIndex, bool doCleanup) // set parent nil at the end child->setParent(nullptr); - _children.removeObjectAtIndex(childIndex); + _children.remove(childIndex); } @@ -778,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); } @@ -795,14 +795,14 @@ 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 ) ) ) @@ -810,7 +810,7 @@ void Node::sortAllChildren() _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); } @@ -858,9 +858,9 @@ void Node::visit() { sortAllChildren(); // draw children zOrder < 0 - for( ; i < _children.count(); i++ ) + for( ; i < _children.size(); i++ ) { - auto node = _children.getObjectAtIndex(i); + auto node = _children.at(i); if ( node && node->_ZOrder < 0 ) node->visit(); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index b3ecc28fa1..c722c73f31 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -95,7 +95,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity) _textureAtlas = new TextureAtlas(); _textureAtlas->initWithTexture(tex, capacity); - _children.setCapacity(capacity); + _children.reserve(capacity); _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; @@ -184,7 +184,7 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag) if (pos != 0) { - ParticleSystem* p = static_cast(_children.getObjectAtIndex(pos-1)); + ParticleSystem* p = static_cast(_children.at(pos-1)); atlasIndex = p->getAtlasIndex() + p->getTotalParticles(); } else @@ -207,12 +207,12 @@ long ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) CCASSERT( child != NULL, "Argument must be non-nil"); CCASSERT( child->getParent() == NULL, "child already added. It can't be added again"); - _children.setCapacity(4); + _children.reserve(4); //don't use a lazy insert long pos = searchNewPositionInChildrenForZ(z); - _children.insertObject(child, pos); + _children.insert(pos, child); child->setTag(aTag); child->_setZOrder(z); @@ -232,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); @@ -253,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 @@ -265,9 +265,9 @@ 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* node = static_cast(_children.getObjectAtIndex(i)); + ParticleSystem* node = static_cast(_children.at(i)); if( node == child ) { newAtlasIndex = child->getAtlasIndex(); @@ -291,11 +291,11 @@ void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* newIndex, Node* ch bool foundNewIdx = false; int minusOne = 0; - long count = _children.count(); + long count = _children.size(); for( long i=0; i < count; i++ ) { - Node* pNode = _children.getObjectAtIndex(i); + Node* pNode = _children.at(i); // new index if( pNode->getZOrder() > z && ! foundNewIdx ) @@ -338,11 +338,11 @@ void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* newIndex, Node* ch long ParticleBatchNode::searchNewPositionInChildrenForZ(int z) { - long count = _children.count(); + long count = _children.size(); for( long i=0; i < count; i++ ) { - Node *child = _children.getObjectAtIndex(i); + Node *child = _children.at(i); if (child->getZOrder() > z) { return i; @@ -359,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); @@ -378,7 +378,7 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup) void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) { - removeChild(_children.getObjectAtIndex(index), doCleanup); + removeChild(_children.at(index), doCleanup); } void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index c8b328dcb0..995a58426e 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -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()) { @@ -1060,7 +1060,7 @@ void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - AnimationFrame* frame = 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 c6ca01d03c..95f1fbd4c4 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -92,7 +92,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) updateBlendFunc(); - _children.setCapacity(capacity); + _children.reserve(capacity); _descendants.reserve(capacity); @@ -185,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()) { @@ -207,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); @@ -217,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(_children.getObjectAtIndex(index), doCleanup); + CCASSERT(index>=0 && index < _children.size(), "Invalid index"); + removeChild(_children.at(index), doCleanup); } void SpriteBatchNode::removeAllChildrenWithCleanup(bool doCleanup) @@ -291,7 +291,7 @@ void SpriteBatchNode::sortAllChildren() void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { auto& array = sprite->getChildren(); - long count = array.count(); + long count = array.size(); int oldIndex = 0; @@ -309,7 +309,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { bool needNewIndex=true; - if (array.getObjectAtIndex(0)->getZOrder() >= 0) + if (array.at(0)->getZOrder() >= 0) { //all children are in front of the parent oldIndex = sprite->getAtlasIndex(); @@ -422,7 +422,7 @@ 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"); auto& children = parent->getChildren(); @@ -456,13 +456,13 @@ int SpriteBatchNode::highestAtlasIndexInChild(Sprite *sprite) { auto& children = sprite->getChildren(); - if (children.count() == 0) + if (children.size() == 0) { return sprite->getAtlasIndex(); } else { - return highestAtlasIndexInChild( static_cast(children.getLastObject())); + return highestAtlasIndexInChild( static_cast(children.back())); } } @@ -470,27 +470,27 @@ int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite) { auto& children = sprite->getChildren(); - if (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) { auto& siblings = sprite->getParent()->getChildren(); - long childIndex = siblings.getIndexOfObject(sprite); + long childIndex = siblings.getIndex(sprite); // ignore parent Z if parent is spriteSheet bool ignoreParent = (SpriteBatchNode*)(sprite->getParent()) == this; Sprite *prev = NULL; if (childIndex > 0 && childIndex != -1) { - prev = static_cast(siblings.getObjectAtIndex(childIndex - 1)); + prev = static_cast(siblings.at(childIndex - 1)); } // first child of the sprite sheet diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index d16802ffec..f81f2f19ad 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -64,7 +64,7 @@ void SpriteFrameCache::destroyInstance() bool SpriteFrameCache::init(void) { - _spriteFrames.setCapacity(20); + _spriteFrames.reserve(20); _spriteFramesAliases.reserve(20); _loadedFileNames = new std::set(); return true; diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index ed11ad55f6..d4f8659a6a 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -556,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]; diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 5b16a3c43c..5df77a56e7 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -114,7 +114,7 @@ TMXTilesetInfo * TMXTiledMap::tilesetForLayer(TMXLayerInfo *layerInfo, TMXMapInf { Size size = layerInfo->_layerSize; auto& tilesets = mapInfo->getTilesets(); - if (tilesets.count()>0) + if (tilesets.size()>0) { TMXTilesetInfo* tileset = nullptr; for (auto iter = tilesets.crbegin(); iter != tilesets.crend(); ++iter) @@ -211,7 +211,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const { CCASSERT(groupName.size() > 0, "Invalid group name!"); - if (_objectGroups.count()>0) + if (_objectGroups.size()>0) { TMXObjectGroup* objectGroup = nullptr; for (auto iter = _objectGroups.cbegin(); iter != _objectGroups.cend(); ++iter) diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index f58a2c2a5a..6bf2945563 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -134,7 +134,7 @@ void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& _resources = resourcePath; } - _objectGroups.setCapacity(4); + _objectGroups.reserve(4); // tmp vars _currentString = ""; @@ -289,7 +289,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) s.height = attributeDict["tileheight"].asFloat(); tileset->_tileSize = s; - pTMXMapInfo->getTilesets().addObject(tileset); + pTMXMapInfo->getTilesets().pushBack(tileset); tileset->release(); } } @@ -297,7 +297,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { if (pTMXMapInfo->getParentElement() == TMXPropertyLayer) { - TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; unsigned int gid = (unsigned int)attributeDict["gid"].asInt(); int tilesAmount = layerSize.width*layerSize.height; @@ -331,10 +331,10 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) } else { - TMXTilesetInfo* info = pTMXMapInfo->getTilesets().getLastObject(); + TMXTilesetInfo* info = pTMXMapInfo->getTilesets().back(); pTMXMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt()); //FIXME:XXX Why insert an empty dict? - pTMXMapInfo->getTileProperties().insert(std::make_pair(pTMXMapInfo->getParentGID(), Value())); + pTMXMapInfo->getTileProperties()[pTMXMapInfo->getParentGID()] = Value(ValueMap()); pTMXMapInfo->setParentElement(TMXPropertyTile); } } @@ -365,7 +365,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) 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" @@ -381,7 +381,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) 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" @@ -390,7 +390,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) } else if (elementName == "image") { - TMXTilesetInfo* tileset = pTMXMapInfo->getTilesets().getLastObject(); + TMXTilesetInfo* tileset = pTMXMapInfo->getTilesets().back(); // build full path std::string imagename = attributeDict["source"].asString(); @@ -414,7 +414,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { pTMXMapInfo->setLayerAttribs(pTMXMapInfo->getLayerAttribs() | TMXLayerAttribNone); - TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; int tilesAmount = layerSize.width*layerSize.height; @@ -459,7 +459,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) } else if (elementName == "object") { - TMXObjectGroup* objectGroup = 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 @@ -511,7 +511,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer ) { // The parent element is the last layer - TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().back(); Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); // Add the property to the layer @@ -520,7 +520,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup ) { // The parent element is the last object group - TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().getLastObject(); + TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().back(); Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); objectGroup->getProperties().insert(std::make_pair(key, value)); @@ -528,7 +528,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject ) { // The parent element is the last object - TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().getLastObject(); + TMXObjectGroup* objectGroup = pTMXMapInfo->getObjectGroups().back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); std::string propertyName = attributeDict["name"].asString(); @@ -545,7 +545,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if (elementName == "polygon") { // find parent object's dict and add polygon-points to it - TMXObjectGroup* objectGroup = _objectGroups.getLastObject(); + TMXObjectGroup* objectGroup = _objectGroups.back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string @@ -590,7 +590,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) else if (elementName == "polyline") { // find parent object's dict and add polyline-points to it - TMXObjectGroup* objectGroup = _objectGroups.getLastObject(); + TMXObjectGroup* objectGroup = _objectGroups.back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string @@ -648,7 +648,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name) { pTMXMapInfo->setStoringCharacters(false); - TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().back(); std::string currentString = pTMXMapInfo->getCurrentString(); unsigned char *buffer; @@ -689,7 +689,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name) } else if (pTMXMapInfo->getLayerAttribs() & TMXLayerAttribNone) { - TMXLayerInfo* layer = pTMXMapInfo->getLayers().getLastObject(); + TMXLayerInfo* layer = pTMXMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; int tilesAmount = layerSize.width * layerSize.height; diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index eb7a970feb..3ee4e6cb27 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -73,18 +73,18 @@ public: } /** Sets capacity of current array */ - void setCapacity(long capacity) + void reserve(long capacity) { _data.reserve(capacity); } /** Returns capacity of the array */ - long getCapacity() const + size_t capacity() const { return _data.capacity(); } - long count() const + size_t size() const { return _data.size(); } diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index fdeadc6026..3dee475171 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -46,13 +46,13 @@ public: : _data() { CCLOGINFO("In the default constructor with capacity of Vector."); - setCapacity(capacity); + reserve(capacity); } virtual ~Vector() { CCLOGINFO("In the destructor of Vector."); - removeAllObjects(); + clear(); } Vector(const Vector& other) @@ -72,7 +72,7 @@ public: Vector& operator=(const Vector& other) { CCLOGINFO("In the copy assignment operator!"); - removeAllObjects(); + clear(); _data = other._data; addRefForAllObjects(); return *this; @@ -85,6 +85,7 @@ public: return *this; } +// Don't uses operator since we could not decide whether it needs 'retain'/'release'. // T& operator[](long index) // { // return _data[index]; @@ -96,13 +97,13 @@ public: // } /** Sets capacity of current array */ - void setCapacity(long capacity) + void reserve(long capacity) { _data.reserve(capacity); } /** Returns capacity of the array */ - long getCapacity() const + long capacity() const { return _data.capacity(); } @@ -110,7 +111,7 @@ public: // Querying an Array /** Returns element count of the array */ - long count() const + size_t size() const { return _data.size(); } @@ -121,9 +122,9 @@ public: } /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ - long getIndexOfObject(T object) const + long getIndex(T object) const { - long i=0; + long i = 0; for (auto it = _data.begin(); it != _data.end(); ++it, ++i) { if (*it == object) @@ -136,14 +137,19 @@ public: } /** Returns an element with a certain index */ - T getObjectAtIndex(long index) const + T at(long index) const { - CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); + 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 getLastObject() const + T back() const { return _data.back(); } @@ -160,17 +166,21 @@ public: } /** Returns a Boolean value that indicates whether object is present in array. */ - bool containsObject(T object) const + bool contains(T object) const { return( std::find(_data.begin(), _data.end(), object) != _data.end() ); } /** returns true if the the arrays are equal */ - bool isEqualToArray(const Vector &otherArray) + bool equals(const Vector &other) { - for (long i = 0; i< this->count(); i++) + size_t s = this->size(); + if (s != other.size()) + return false; + + for (long i = 0; i < s; i++) { - if (!this->getObjectAtIndex(i)->isEqual(otherArray.getObjectAtIndex(i))) + if (!this->at(i)->isEqual(other.at(i))) { return false; } @@ -181,49 +191,37 @@ public: // Adding Objects /** Add a certain object */ - void addObject(T 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 addObjectsFromArray(const Vector& otherArray) + void insert(const Vector& other) { - for( auto it = otherArray.begin(); it != otherArray.end(); ++it ) { + for( auto it = other.begin(); it != other.end(); ++it ) { _data.push_back( *it ); (*it)->retain(); } } /** Insert a certain object at a certain index */ - void insertObject(T object, long index) + void insert(long index, T object) { - CCASSERT(index >= 0 && index <= count(), "Invalid index!"); + 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(); } - - /** sets a certain object at a certain index */ - void setObject(T object, long index) - { - CCASSERT(index >= 0 && index < count(), "Invalid index!"); - _data[index]->release(); - _data[index] = object; - object->retain(); - } - /** sets a certain object at a certain index without retaining. Use it with caution */ - void fastSetObject(T object, long index) - { - _data[index] = object; - } - + // Removing Objects /** Remove last object */ - void removeLastObject() + void popBack() { - CCASSERT(_data.size(), "no objects added"); + CCASSERT(!_data.empty(), "no objects added"); auto last = _data.back(); _data.pop_back(); last->release(); @@ -232,20 +230,24 @@ public: /** Remove a certain object */ void removeObject(T object) { - _data.erase( std::remove( _data.begin(), _data.end(), object ) ); + CCASSERT(object != nullptr, "The object should not be nullptr"); + auto iter = std::find(_data.begin(), _data.end(), object); + if (iter != _data.end()) + _data.erase(iter); object->release(); } /** Removes an element with a certain index */ - void removeObjectAtIndex(long index) + void remove(long index) { + CCASSERT(!_data.empty() && index >=0 && index < size(), "Invalid index!"); auto it = std::next( begin(), index ); (*it)->release(); _data.erase(it); } /** Removes all objects */ - void removeAllObjects() + void clear() { for( auto it = std::begin(_data); it != std::end(_data); ++it ) { (*it)->release(); @@ -253,26 +255,15 @@ public: _data.clear(); } - /** Fast way to remove a certain object */ - void fastRemoveObject(T object) { - removeObjectAtIndex(index); - } - - /** Fast way to remove an element with a certain index */ - void fastRemoveObjectAtIndex(long index) - { - removeObjectAtIndex(index); - } - // Rearranging Content /** Swap two elements */ - void swapObjects(T object1, T object2) + void swap(T object1, T object2) { - long idx1 = getIndexOfObject(object1); - long idx2 = getIndexOfObject(object2); + long idx1 = getIndex(object1); + long idx2 = getIndex(object2); - CCASSERT(idx1>=0 && idx2>=2, "invalid object index"); + CCASSERT(idx1>=0 && idx2>=0, "invalid object index"); std::swap( _data[idx1], _data[idx2] ); } @@ -280,36 +271,37 @@ public: /** Swap two elements with certain indexes */ void swap(long index1, long index2) { - CCASSERT(index1 >=0 && index1 < count() && index2 >= 0 && index2 < count(), "Invalid indices"); + 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 replaceObjectAtIndex(long index, T object) + void replace(long index, T object) { - if( object != _data[index] ) { - object->retain(); - _data[index]->release(); - _data[index] = 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 reverseObjects() + void reverse() { std::reverse( std::begin(_data), std::end(_data) ); } /** Shrinks the array so the memory footprint corresponds with the number of items */ - void reduceMemoryFootprint() + void shrinkToFit() { _data.shrink_to_fit(); } void forEach(std::function callback) { - if (count() <= 0) + if (size() <= 0) return; std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){ @@ -319,7 +311,7 @@ public: void forEachReverse(std::function callback) { - if (count() <= 0) + if (size() <= 0) return; std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){ diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index 5fa169014f..3229c12582 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp @@ -631,7 +631,7 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime; lastKeyframeTime = keyframe->getTime(); if(timeSinceLastKeyframe > 0) { - actions.addObject(DelayTime::create(timeSinceLastKeyframe)); + actions.pushBack(DelayTime::create(timeSinceLastKeyframe)); } Array* keyVal = static_cast(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); } @@ -709,7 +709,7 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime; lastKeyframeTime = keyframe->getTime(); if(timeSinceLastKeyframe > 0) { - actions.addObject(DelayTime::create(timeSinceLastKeyframe)); + actions.pushBack(DelayTime::create(timeSinceLastKeyframe)); } stringstream ss (stringstream::in | stringstream::out); @@ -729,10 +729,10 @@ 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 Sequence::create(actions); } @@ -754,7 +754,7 @@ void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, if (timeFirst > 0) { - actions.addObject(DelayTime::create(timeFirst)); + actions.pushBack(DelayTime::create(timeFirst)); } for (int i = 0; i < numKeyframes - 1; ++i) @@ -768,7 +768,7 @@ void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, // Apply easing action = getEaseAction(action, kf0->getEasingType(), kf0->getEasingOpt()); - actions.addObject(action); + actions.pushBack(action); } } diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index f094c10038..36f4b3a505 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -299,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(static_cast(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 10dffd52b2..2585f00bfb 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -672,12 +672,12 @@ Rect Armature::getBoundingBox() const Bone *Armature::getBoneAtPoint(float x, float y) const { - long length = _children.count(); + long length = _children.size(); Bone *bs; 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; diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index c25089b6bf..18b14e40b2 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -305,19 +305,19 @@ void Bone::addChildBone(Bone *child) if(_children.empty()) { - _children.setCapacity(4); + _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.empty() && _children.getIndexOfObject(bone) != CC_INVALID_INDEX ) + if (!_children.empty() && _children.getIndex(bone) != CC_INVALID_INDEX ) { if(recursion) { 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/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 0d2d3610b4..2a61d5223e 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -562,9 +562,9 @@ void ScrollView::visit() int i=0; // draw children zOrder < 0 - for( ; i < _children.count(); i++ ) + for( ; i < _children.size(); i++ ) { - Node *child = _children.getObjectAtIndex(i); + Node *child = _children.at(i); if ( child->getZOrder() < 0 ) { child->visit(); @@ -579,9 +579,9 @@ void ScrollView::visit() this->draw(); // draw children zOrder >= 0 - for( ; i < _children.count(); i++ ) + for( ; i < _children.size(); i++ ) { - Node *child = _children.getObjectAtIndex(i); + Node *child = _children.at(i); child->visit(); } diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index 352e2f4db2..eb8aaa9448 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -398,9 +398,9 @@ MenuLayer4::MenuLayer4() 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 cce6ac09f5..4425ef3974 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1642,12 +1642,12 @@ void AddAndDeleteParticleSystems::onEnter() void AddAndDeleteParticleSystems::removeSystem(float dt) { - int nChildrenCount = _batchNode->getChildren().count(); + int nChildrenCount = _batchNode->getChildren().size(); if (nChildrenCount > 0) { CCLOG("remove random system"); unsigned int uRand = rand() % (nChildrenCount - 1); - _batchNode->removeChild(_batchNode->getChildren().getObjectAtIndex(uRand), true); + _batchNode->removeChild(_batchNode->getChildren().at(uRand), true); auto particleSystem = ParticleSystemQuad::create("Particles/Spiral.plist"); //add new @@ -1794,7 +1794,7 @@ void ReorderParticleSystems::onEnter() void ReorderParticleSystems::reorderSystem(float time) { - auto system = static_cast(_batchNode->getChildren().getObjectAtIndex(1)); + auto system = static_cast(_batchNode->getChildren().at(1)); _batchNode->reorderChild(system, system->getZOrder() - 1); } 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 3b1651912b..163ae87ce4 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 @@ -c26021c35e371ded3c70784e0809493cddad7908 \ No newline at end of file +9019076e23d685080a41fb65944f914bb9268c97 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index a9b3c32f54..6a75f45470 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp @@ -166,11 +166,11 @@ void KeyboardNotificationLayer::keyboardWillShow(IMEKeyboardNotificationInfo& in // move all the children node of KeyboardNotificationLayer auto& children = getChildren(); Node * node = 0; - int count = children.count(); + int count = children.size(); Point pos; for (int i = 0; i < count; ++i) { - 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 4390b52f33..b1d455c7ea 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -752,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))); @@ -820,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)); From 4aae44f1e98ec612558ec094752b334adbb1c3bd Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 18:54:15 -0800 Subject: [PATCH 052/107] fixes cocos2d.h include --- cocos/2d/cocos2d.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index c531f62965..c33dddf82d 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -199,7 +199,7 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCNotificationCenter.h" #include "CCProfiling.h" -#include "base/CCConsole.h" +#include "CCConsole.h" #include "CCUserDefault.h" #include "CCVertex.h" From 944160210cf9896985eaa8ec84254e62abcd96e5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 10:59:43 +0800 Subject: [PATCH 053/107] issue #2790: Renames functions in Map. --- cocos/2d/CCAnimationCache.cpp | 6 +++--- cocos/2d/CCSpriteFrameCache.cpp | 28 ++++++++++++++-------------- cocos/base/CCMap.h | 33 +++++++++++++++++---------------- 3 files changed, 34 insertions(+), 33 deletions(-) diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 9cd3db6687..f0828aaa6d 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -69,7 +69,7 @@ AnimationCache::~AnimationCache() void AnimationCache::addAnimation(Animation *animation, const std::string& name) { - _animations.setObject(animation, name); + _animations.insert(name, animation); } void AnimationCache::removeAnimation(const std::string& name) @@ -77,12 +77,12 @@ 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 _animations.getObjectForKey(name); + return _animations.at(name); } void AnimationCache::parseVersion1(const ValueMap& animations) diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index f81f2f19ad..089760fe51 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -103,7 +103,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu { ValueMap& frameDict = iter->second.asValueMap(); std::string spriteFrameName = iter->first; - SpriteFrame* spriteFrame = _spriteFrames.getObjectForKey(spriteFrameName); + SpriteFrame* spriteFrame = _spriteFrames.at(spriteFrameName); if (spriteFrame) { continue; @@ -191,7 +191,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu } // add sprite frame - _spriteFrames.setObject(spriteFrame, spriteFrameName); + _spriteFrames.insert(spriteFrameName, spriteFrame); spriteFrame->release(); } } @@ -271,14 +271,14 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) } } -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() { - _spriteFrames.removeAllObjects(); + _spriteFrames.clear(); _spriteFramesAliases.clear(); _loadedFileNames->clear(); } @@ -299,7 +299,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames() } } - _spriteFrames.removeObjectsForKeys(toRemoveFrames); + _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 ) @@ -320,12 +320,12 @@ void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) if (!key.empty()) { - _spriteFrames.removeObjectForKey(key); + _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 @@ -358,13 +358,13 @@ void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueMap& dictionary) for (auto iter = framesDict.cbegin(); iter != framesDict.cend(); ++iter) { - if (_spriteFrames.getObjectForKey(iter->first)) + if (_spriteFrames.at(iter->first)) { keysToRemove.push_back(iter->first); } } - _spriteFrames.removeObjectsForKeys(keysToRemove); + _spriteFrames.remove(keysToRemove); } void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) @@ -374,26 +374,26 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) for (auto iter = _spriteFrames.cbegin(); iter != _spriteFrames.cend(); ++iter) { std::string key = iter->first; - SpriteFrame* frame = _spriteFrames.getObjectForKey(key); + SpriteFrame* frame = _spriteFrames.at(key); if (frame && (frame->getTexture() == texture)) { keysToRemove.push_back(key); } } - _spriteFrames.removeObjectsForKeys(keysToRemove); + _spriteFrames.remove(keysToRemove); } SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) { - SpriteFrame* frame = _spriteFrames.getObjectForKey(name); + SpriteFrame* frame = _spriteFrames.at(name); if (!frame) { // try alias dictionary std::string key = _spriteFramesAliases[name].asString(); if (!key.empty()) { - frame = _spriteFrames.getObjectForKey(key); + frame = _spriteFrames.at(key); if (!frame) { CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str()); diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 3ee4e6cb27..d9220646f4 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -69,7 +69,7 @@ public: ~Map() { CCLOGINFO("In the destructor of Map!"); - removeAllObjects(); + clear(); } /** Sets capacity of current array */ @@ -94,7 +94,7 @@ public: return _data.empty(); } - std::vector getAllKeys() const + std::vector keys() const { std::vector keys; @@ -105,10 +105,10 @@ public: keys.push_back(iter->first); } } - return keys; + return std::move(keys); } - std::vector getAllKeysForObject(V object) const + std::vector keys(V object) const { std::vector keys; @@ -120,10 +120,10 @@ public: } } - return keys; + return std::move(keys); } - V getObjectForKey(const K& key) const + V at(const K& key) const { auto iter = _data.find(key); if (iter != _data.end()) @@ -132,14 +132,15 @@ public: return nullptr; } - void setObject(V object, const K& key) + void insert(const K& key, V object) { - removeObjectForKey(key); + CCASSERT(object != nullptr, "Object is nullptr!"); + remove(key); _data.insert(std::make_pair(key, object)); object->retain(); } - void removeObjectForKey(const K& key) + void remove(const K& key) { auto iter = _data.find(key); if (iter != _data.end()) @@ -149,18 +150,18 @@ public: } } - void removeObjectsForKeys(const std::vector& keys) + void remove(const std::vector& keys) { std::for_each(keys.cbegin(), keys.cend(), [this](const K& key){ - removeObjectForKey(key); + remove(key); }); } - void removeAllObjects() + void clear() { for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) { - CC_SAFE_RELEASE(iter->second); + iter->second->release(); } _data.clear(); @@ -193,7 +194,7 @@ public: const_iterator cbegin() const { return _data.cbegin(); } const_iterator cend() const { return _data.cend(); } - // Operator +// Don't uses operator since we could not decide whether it needs 'retain'/'release'. // V& operator[] ( const K& key ) // { // CCLOG("copy: [] ref"); @@ -221,7 +222,7 @@ public: Map& operator= ( const Map& other ) { CCLOG("In the copy assignment operator of Map!"); - removeAllObjects(); + clear(); _data = other._data; addRefForAllObjects(); } @@ -229,7 +230,7 @@ public: Map& operator= ( Map&& other ) { CCLOG("In the move assignment operator of Map!"); - _data = other._data; + _data = std::move(other._data); } protected: From 856a82d4b86284ce8060070032aaa5383d6461c0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 11:03:22 +0800 Subject: [PATCH 054/107] =?UTF-8?q?issue=20#2790:=20Don=E2=80=99t=20build?= =?UTF-8?q?=20script=20bindings=20projects=20for=20travis.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/travis-scripts/run-script.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index b609c7cc43..ccf9582825 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -28,7 +28,7 @@ if [ "$GEN_JSB"x = "YES"x ]; then fi export NDK_ROOT=$HOME/bin/android-ndk cd $COCOS2DX_ROOT/tools/travis-scripts - ./generate-jsbindings.sh + # ./generate-jsbindings.sh elif [ "$PLATFORM"x = "android"x ]; then export NDK_ROOT=$HOME/bin/android-ndk @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n "NDK_BUG=0 -j10" all + ./android-build.py -n "NDK_BUG=0 -j10" hellocpp testcpp simplegame # Build template # echo "Building template ..." @@ -79,9 +79,9 @@ elif [ "$PLATFORM"x = "linux"x ]; then 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 From 49b25231f2492b559115ff1e3716672c750b1704 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 19:16:01 -0800 Subject: [PATCH 055/107] Compiles on Android --- cocos/2d/Android.mk | 1 + cocos/base/CCConsole.h | 2 +- samples/Cpp/TestCpp/Android.mk | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 854d56829d..d181a79b91 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -131,6 +131,7 @@ platform/CCThread.cpp \ ../base/CCString.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/base/CCConsole.h b/cocos/base/CCConsole.h index 4dc873671c..6e4d4f352c 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -33,7 +33,7 @@ #include #include "ccMacros.h" -#include "base/CCObject.h" +#include "CCObject.h" NS_CC_BEGIN 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 \ From e0bf32d88101eef5cfddf83faee81e11a961eaa5 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 19:33:50 -0800 Subject: [PATCH 056/107] dprintf is not defined on Android using my own dprintf --- cocos/base/CCConsole.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 5cc85b6690..8f25a39baf 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "base/CCConsole.h" +#include "CCConsole.h" #include #include @@ -194,12 +194,25 @@ void Console::commandExit(int fd) close(fd); } +static int 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)); +} + + void printSceneGraph(int fd, Node* node, int level) { for(int i=0; idescription(), node->getZOrder(), node->getTag() ); + mydprintf(fd, " %s: z=%d, tag=%d\n", node->description(), node->getZOrder(), node->getTag() ); auto children = node->getChildren(); if( children ) { From e5ada6f3774922558666ee549d3daa43b8564e56 Mon Sep 17 00:00:00 2001 From: martell Date: Thu, 5 Dec 2013 03:37:27 +0000 Subject: [PATCH 057/107] added support for msys2 mingwtoolchains and fix x64 cocos/audio on windows platform for MSVC and Mingw. Also fixed a few very bad type casts very important for future Arm64 bit processors --- CMakeLists.txt | 25 +++++++++++++ build/build-mingw32-gcc-make.sh | 62 ++++++++++++++++++++++++++++++++ cocos/2d/CCSprite.cpp | 2 +- cocos/2d/ZipUtils.cpp | 2 +- cocos/2d/platform/win32/CCStdC.h | 10 +++++- cocos/audio/win32/MciPlayer.cpp | 22 ++++++------ cocos/base/CCPlatformConfig.h | 4 ++- 7 files changed, 112 insertions(+), 15 deletions(-) create mode 100644 build/build-mingw32-gcc-make.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index 08c2eddb1f..dfa9ac305e 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) 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/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 36577238b0..d0ec167bcc 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 diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index ebde2f9963..5c47939152 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -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 ) 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/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__ From 373c3b01bfcfa9d33f23d8ac932d5a655fb39c93 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 5 Dec 2013 11:44:37 +0800 Subject: [PATCH 058/107] issue #2790: Fixing compilation errors on linux. --- cocos/2d/CCSpriteFrameCache.cpp | 1 + cocos/2d/platform/CCFileUtils.cpp | 4 ++-- cocos/base/CCArray.cpp | 2 +- cocos/base/CCMap.h | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 089760fe51..a089484f8c 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -404,3 +404,4 @@ SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) } NS_CC_END + diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 3959ee98f5..4c06f23ecb 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -403,11 +403,11 @@ static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XM //FIXME:XXX How to deal with Boolean ?? // object is Array - if (value.getType() == Value::Type::ARRAY) + if (value.getType() == Value::Type::VECTOR) return generateElementForArray(value.asValueVector(), pDoc); // object is Dictionary - if (value.getType() == Value::Type::DICTIONARY) + if (value.getType() == Value::Type::MAP) return generateElementForDict(value.asValueMap(), pDoc); CCLOG("This type cannot appear in property list"); diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index 27b04422a6..4257e3f38a 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -26,10 +26,10 @@ THE SOFTWARE. #include "CCArray.h" #include "CCString.h" #include "platform/CCFileUtils.h" +#include // std::for_each NS_CC_BEGIN - #if CC_USE_ARRAY_VECTOR // ---------------------------------------------------------------------------------- diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index d9220646f4..7a928a5cc0 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -153,7 +153,7 @@ public: void remove(const std::vector& keys) { std::for_each(keys.cbegin(), keys.cend(), [this](const K& key){ - remove(key); + this->remove(key); }); } From 68e376db2f2b41bfcc0c7edfcda20353b0b789b5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 11:51:09 +0800 Subject: [PATCH 059/107] issue #2790: Disables build lua projects for linux --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index ccf9582825..469db7b066 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -74,7 +74,7 @@ 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 . From e0523c73f52968c48284e3afccb1d87f066d3546 Mon Sep 17 00:00:00 2001 From: martell Date: Thu, 5 Dec 2013 03:53:25 +0000 Subject: [PATCH 060/107] fixed CCImage for MSVC someone added std:tolower which broke it --- cocos/2d/platform/win32/CCImage.cpp | 3 +++ 1 file changed, 3 insertions(+) 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 From 8f574272ee8f189cd95e88e68b6b00b40cf6c390 Mon Sep 17 00:00:00 2001 From: martell Date: Thu, 5 Dec 2013 03:54:44 +0000 Subject: [PATCH 061/107] removed unneeded directories for Mingw cmake --- CMakeLists.txt | 6 ------ 1 file changed, 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index dfa9ac305e..c68536b314 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -195,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() From d04f777351852969c3573287f1544119e929e2ad Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 5 Dec 2013 04:02:07 +0000 Subject: [PATCH 062/107] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 567077c985..e4ce0d5a62 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 567077c9856e175cc867be4687c089e3a8dc33bc +Subproject commit e4ce0d5a6240c303a591a4476564bd7080ab06c2 From 73321199b9347897474e9d10477db0798c9fe9e4 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 21:51:08 -0800 Subject: [PATCH 063/107] Console: commands receives the char* The char* is passed in case the commands need to sub-parse the arguments. Very useful for QA. For example, the could create a command called "click", and the command could receive arguments. --- cocos/2d/CCScheduler.cpp | 2 +- cocos/base/CCConsole.cpp | 117 ++++++++++-------- cocos/base/CCConsole.h | 8 +- .../Classes/ConsoleTest/ConsoleTest.cpp | 6 +- 4 files changed, 75 insertions(+), 58 deletions(-) diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 69172607a9..88f067f666 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -976,7 +976,7 @@ void Scheduler::update(float dt) // Testing size is faster than locking / unlocking. // And almost never there will be functions scheduled to be called. - if( _functionsToPerform.size() > 0 ) { + if( !_functionsToPerform.empty() ) { _performMutex.lock(); for( const auto &function : _functionsToPerform ) { function(); diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 8f25a39baf..4994c46f59 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -44,6 +44,50 @@ using namespace cocos2d; + +// 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()); + + auto children = node->getChildren(); + if( children ) { + for(const auto& child: *children) + printSceneGraph(fd, static_cast(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; @@ -58,19 +102,19 @@ Console::Console() , _running(false) , _endThread(false) , _commands{ - { "fps on", [](int anFd) { + { "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 anFd) { + { "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) }, - { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1) }, - { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, } + { "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) }, } , _maxCommands(5) , _userCommands(nullptr) , _maxUserCommands(0) @@ -89,12 +133,12 @@ bool Console::listenOnTCP(int port) struct addrinfo hints, *res, *ressave; char serv[30]; - snprintf(serv,sizeof(serv)-1,"%d",(unsigned int) port ); + 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_UNSPEC; + hints.ai_family = AF_INET; // AF_UNSPEC: Do we need IPv6 ? hints.ai_socktype = SOCK_STREAM; if ( (n = getaddrinfo(NULL, serv, &hints, &res)) != 0) { @@ -125,16 +169,22 @@ bool Console::listenOnTCP(int port) listen(listenfd, 50); if (res->ai_family == AF_INET) { - char buf2[256] = ""; - gethostname(buf2, sizeof(buf2)-1); char buf[INET_ADDRSTRLEN] = ""; struct sockaddr_in *sin = (struct sockaddr_in*) res->ai_addr; - if( inet_ntop(res->ai_family, sin , buf, sizeof(buf)) != NULL ) - CCLOG("Console: listening on %s : %d", buf2, ntohs(sin->sin_port)); + 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); @@ -168,7 +218,7 @@ void Console::setUserCommands(Command *commands, int numberOfCommands) // commands // -void Console::commandHelp(int fd) +void Console::commandHelp(int fd, const char* command) { const char help[] = "\nAvailable commands:\n"; write(fd, help, sizeof(help)); @@ -187,49 +237,14 @@ void Console::commandHelp(int fd) } -void Console::commandExit(int fd) +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); } -static int 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)); -} - - -void printSceneGraph(int fd, Node* node, int level) -{ - for(int i=0; idescription(), node->getZOrder(), node->getTag() ); - - auto children = node->getChildren(); - if( children ) { - for(const auto& child: *children ) - printSceneGraph(fd, (Node*)child, level+1); - } -} - -void printSceneGraphBoot(int fd) -{ - write(fd,"\n",1); - auto scene = Director::getInstance()->getRunningScene(); - printSceneGraph(fd, scene, 0); - write(fd,"\n",1); -} - -void Console::commandSceneGraph(int fd) +void Console::commandSceneGraph(int fd, const char *command) { Scheduler *sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) ); @@ -248,7 +263,7 @@ bool Console::parseCommand(int fd) // 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); + _commands[i].callback(fd, _buffer); found = true; break; } @@ -257,7 +272,7 @@ bool Console::parseCommand(int fd) // 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); + _userCommands[i].callback(fd, _buffer); found = true; break; } diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 6e4d4f352c..0ee953dc83 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -53,7 +53,7 @@ public: struct Command { const char *name; - const std::function callback; + const std::function callback; }; /** creates a new instnace of the Console */ @@ -83,9 +83,9 @@ protected: void addClient(); // Add commands here - void commandHelp(int fd); - void commandExit(int fd); - void commandSceneGraph(int fd); + 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; diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp index 353931cdfe..dd44a0ec60 100644 --- a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -161,9 +161,11 @@ ConsoleCustomCommand::ConsoleCustomCommand() _console->retain(); static struct Console::Command commands[] = { - {"hello", [](int fd) { - const char msg[] = "how are you?\n"; + {"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); From c617eee505464ff198e155ba59546db84d4c957b Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 4 Dec 2013 22:07:23 -0800 Subject: [PATCH 064/107] Uses the new Vector<>. Code is more robust! --- cocos/base/CCConsole.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 4994c46f59..e88afd17b5 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -68,11 +68,8 @@ static void printSceneGraph(int fd, Node* node, int level) mydprintf(fd, " %s: z=%d, tag=%d\n", node->description(), node->getZOrder(), node->getTag()); - auto children = node->getChildren(); - if( children ) { - for(const auto& child: *children) - printSceneGraph(fd, static_cast(child), level+1); - } + for(const auto& child: node->getChildren()) + printSceneGraph(fd, child, level+1); } static void printSceneGraphBoot(int fd) From 2b857ebb522391b44d6c457ddd1a7365144b5170 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 16:09:38 +0800 Subject: [PATCH 065/107] Fixing compilation errors on windows. --- cocos/2d/cocos2d.vcxproj | 11 ++++++- cocos/2d/cocos2d.vcxproj.filters | 23 ++++++++++++++ cocos/2d/cocos2dx.props | 2 +- cocos/base/CCConsole.cpp | 54 +++++++++++++++++++++----------- cocos/base/CCConsole.h | 10 +++++- cocos/base/CCVector.h | 2 +- 6 files changed, 80 insertions(+), 22 deletions(-) diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 62ea897c70..6e99922e3a 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -29,7 +29,7 @@ Unicode v100 v110 - v110_xp + v110 @@ -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 + + + @@ -511,6 +517,9 @@ 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..c5b2b27816 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -560,6 +560,12 @@ physics\chipmunk + + base + + + base + @@ -1125,5 +1131,22 @@ physics\chipmunk + + base + + + 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/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 8f25a39baf..b6f959e002 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -28,21 +28,29 @@ #include #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" -using namespace cocos2d; +NS_CC_BEGIN Console* Console::create() { @@ -52,13 +60,16 @@ Console* Console::create() return ret; } - Console::Console() : _listenfd(-1) , _running(false) , _endThread(false) -, _commands{ - { "fps on", [](int anFd) { +, _maxCommands(5) +, _userCommands(nullptr) +, _maxUserCommands(0) +{ + Command commands[] = { + { "fps on", [](int anFd) { Director *dir = Director::getInstance(); Scheduler *sched = dir->getScheduler(); sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, true)); @@ -70,11 +81,12 @@ Console::Console() } }, { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1) }, { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1) }, - { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) }, } -, _maxCommands(5) -, _userCommands(nullptr) -, _maxUserCommands(0) -{ + { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) } }; + + for (size_t i = 0; i < sizeof(commands)/sizeof(commands[0]) && i < sizeof(_commands)/sizeof(_commands[0]); ++i) + { + _commands[i] = commands[i]; + } } Console::~Console() @@ -97,6 +109,11 @@ bool Console::listenOnTCP(int port) hints.ai_family = AF_UNSPEC; 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; @@ -109,7 +126,7 @@ bool Console::listenOnTCP(int port) if (listenfd < 0) continue; /* error, try next one */ - setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); + setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)); if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0) break; /* success */ @@ -214,11 +231,10 @@ void printSceneGraph(int fd, Node* node, int level) mydprintf(fd, " %s: z=%d, tag=%d\n", node->description(), node->getZOrder(), node->getTag() ); - auto children = node->getChildren(); - if( children ) { - for(const auto& child: *children ) - printSceneGraph(fd, (Node*)child, level+1); - } + auto& children = node->getChildren(); + children.forEach([&fd, &level](Node* child){ + printSceneGraph(fd, child, level+1); + }); } void printSceneGraphBoot(int fd) @@ -397,3 +413,5 @@ void Console::loop() _running = false; } + +NS_CC_END diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 6e4d4f352c..efb4adc449 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -26,7 +26,15 @@ #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 @@ -53,7 +61,7 @@ public: struct Command { const char *name; - const std::function callback; + std::function callback; }; /** creates a new instnace of the Console */ diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 3dee475171..280a1854f4 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -137,7 +137,7 @@ public: } /** Returns an element with a certain index */ - T at(long index) const + T at(size_t index) const { CCASSERT( index >= 0 && index < size(), "index out of range in getObjectAtIndex()"); return _data[index]; From b0c09cd291a0466e18f09d205c22f912352e9092 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 16:12:04 +0800 Subject: [PATCH 066/107] Includes on windows for ConsoleTest. --- samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp index 353931cdfe..d69518979f 100644 --- a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -25,7 +25,11 @@ #include "ConsoleTest.h" #include "../testResource.h" +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) #include +#else +#include +#endif //------------------------------------------------------------------ // From b4b50f3491e5f6e007155e2a49287c5e780a7971 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 16:33:13 +0800 Subject: [PATCH 067/107] Compilation fix for windows. --- cocos/base/CCConsole.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 7529b9eaa7..ce52ef37a2 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -120,9 +120,9 @@ Console::Console() Scheduler *sched = dir->getScheduler(); sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, false)); } }, - { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1) }, - { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1) }, - { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1) } }; + { "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) { From b520941c5c9054cf9bf05d36978febda6e5180e7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 16:37:50 +0800 Subject: [PATCH 068/107] Reverts config of VS project. --- cocos/2d/cocos2d.vcxproj | 5 +---- cocos/2d/cocos2d.vcxproj.filters | 5 ----- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 6e99922e3a..a026926c95 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -29,7 +29,7 @@ Unicode v100 v110 - v110 + v110_xp @@ -517,9 +517,6 @@ 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 c5b2b27816..69900696e1 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -1144,9 +1144,4 @@ base - - - base - - \ No newline at end of file From 6aa2e5b257a3b42ad3dfbcd8d5409870915f39f9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 5 Dec 2013 16:49:05 +0800 Subject: [PATCH 069/107] =?UTF-8?q?Updates=20comments=20that=20vs2012=20do?= =?UTF-8?q?esn=E2=80=99t=20support=20initializer=20list.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCConsole.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index ce52ef37a2..c15ba3383b 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -109,6 +109,7 @@ Console::Console() , _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(); From b67d567a79cd906c6fef26e3fa4aa216ec2a1780 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 5 Dec 2013 17:19:01 +0800 Subject: [PATCH 070/107] replace long with int or ssize_t --- cocos/2d/CCActionCatmullRom.cpp | 22 +-- cocos/2d/CCActionCatmullRom.h | 14 +- cocos/2d/CCActionInterval.cpp | 8 +- cocos/2d/CCActionManager.cpp | 14 +- cocos/2d/CCActionManager.h | 6 +- cocos/2d/CCAtlasNode.cpp | 10 +- cocos/2d/CCAtlasNode.h | 20 +-- cocos/2d/CCDirector.cpp | 4 +- cocos/2d/CCDirector.h | 2 +- cocos/2d/CCDrawNode.cpp | 16 +-- cocos/2d/CCDrawNode.h | 6 +- cocos/2d/CCEventDispatcher.cpp | 10 +- cocos/2d/CCEventDispatcher.h | 6 +- cocos/2d/CCFontFreeType.cpp | 2 +- cocos/2d/CCGrid.cpp | 6 +- cocos/2d/CCGrid.h | 2 +- cocos/2d/CCLabel.cpp | 4 +- cocos/2d/CCLabelAtlas.cpp | 22 +-- cocos/2d/CCLabelAtlas.h | 8 +- cocos/2d/CCLabelBMFont.cpp | 20 +-- cocos/2d/CCMenuItem.cpp | 18 +-- cocos/2d/CCMenuItem.h | 24 ++-- cocos/2d/CCNode.cpp | 10 +- cocos/2d/CCNode.h | 8 +- cocos/2d/CCParticleBatchNode.cpp | 38 ++--- cocos/2d/CCParticleBatchNode.h | 12 +- cocos/2d/CCParticleSystem.cpp | 2 +- cocos/2d/CCRenderTexture.cpp | 6 +- cocos/2d/CCSpriteBatchNode.cpp | 14 +- cocos/2d/CCSpriteBatchNode.h | 6 +- cocos/2d/CCTexture2D.cpp | 132 +++++++++--------- cocos/2d/CCTexture2D.h | 74 +++++----- cocos/2d/CCTextureAtlas.cpp | 64 ++++----- cocos/2d/CCTextureAtlas.h | 42 +++--- cocos/2d/CCTextureCache.cpp | 4 +- cocos/2d/CCUserDefault.cpp | 2 +- cocos/2d/CCUserDefault.mm | 6 +- cocos/2d/CCUserDefaultAndroid.cpp | 2 +- cocos/2d/ZipUtils.cpp | 2 +- cocos/2d/ZipUtils.h | 2 +- cocos/2d/ccCArray.cpp | 91 ++++++------ cocos/2d/ccCArray.h | 34 ++--- cocos/2d/ccUtils.cpp | 2 +- cocos/2d/ccUtils.h | 2 +- cocos/2d/platform/CCEGLViewProtocol.cpp | 18 +-- cocos/2d/platform/CCEGLViewProtocol.h | 10 +- cocos/2d/platform/CCFileUtils.cpp | 8 +- cocos/2d/platform/CCFileUtils.h | 4 +- cocos/2d/platform/CCImage.h | 48 +++---- cocos/2d/platform/CCImageCommon_cpp.h | 50 +++---- cocos/2d/platform/CCSAXParser.cpp | 2 +- cocos/2d/platform/CCThread.cpp | 6 +- cocos/2d/platform/CCThread.h | 4 +- .../platform/android/CCFileUtilsAndroid.cpp | 6 +- .../2d/platform/android/CCFileUtilsAndroid.h | 6 +- cocos/2d/platform/android/nativeactivity.cpp | 18 +-- cocos/2d/platform/apple/CCThread.mm | 6 +- cocos/2d/platform/ios/EAGLView.mm | 8 +- cocos/2d/platform/linux/CCEGLView.cpp | 6 +- cocos/2d/platform/mac/CCEGLView.mm | 6 +- cocos/2d/platform/mac/EAGLView.mm | 6 +- cocos/2d/platform/win32/CCEGLView.cpp | 6 +- cocos/base/CCData.cpp | 4 +- cocos/base/CCData.h | 8 +- cocos/base/CCMap.h | 4 +- cocos/base/CCString.cpp | 6 +- cocos/base/CCString.h | 2 +- .../cocostudio/CCActionNode.cpp | 2 +- cocos/editor-support/spine/Atlas.cpp | 2 +- cocos/editor-support/spine/SkeletonJson.cpp | 2 +- cocos/editor-support/spine/extension.h | 2 +- cocos/editor-support/spine/spine-cocos2dx.cpp | 4 +- cocos/network/HttpClient.cpp | 2 +- cocos/physics/CCPhysicsContact.h | 2 +- cocos/physics/CCPhysicsShape.cpp | 6 +- cocos/physics/CCPhysicsShape.h | 8 +- cocos/physics/CCPhysicsWorld.h | 10 +- 77 files changed, 538 insertions(+), 543 deletions(-) diff --git a/cocos/2d/CCActionCatmullRom.cpp b/cocos/2d/CCActionCatmullRom.cpp index 2ae9a2b77d..7c3cc2f81c 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)); 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; + ssize_t 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 a197ccf3d2..9aca314728 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -203,14 +203,14 @@ Sequence* Sequence::create(const Vector& arrayOfActions) Sequence* pRet = NULL; do { - long count = arrayOfActions.size(); + auto count = arrayOfActions.size(); CC_BREAK_IF(count == 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, arrayOfActions.at(i)); } @@ -576,7 +576,7 @@ Spawn* Spawn::create(const Vector& arrayOfActions) Spawn* pRet = NULL; do { - long count = arrayOfActions.size(); + auto count = arrayOfActions.size(); CC_BREAK_IF(count == 0); auto prev = arrayOfActions.at(0); if (count > 1) @@ -2097,7 +2097,7 @@ void Animate::update(float t) } auto frames = _animation->getFrames(); - long numberOfFrames = frames.size(); + auto numberOfFrames = frames.size(); SpriteFrame *frameToDisplay = NULL; for( int i=_nextFrame; i < numberOfFrames; i++ ) { diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index dd2b528bce..d4981053c6 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -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]; @@ -253,7 +253,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); @@ -275,8 +275,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]; @@ -304,8 +304,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 +327,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 Object *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..53d0fe1109 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -102,10 +102,10 @@ public: * - 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 Object *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(Object *target) const { return getNumberOfRunningActionsInTarget(target); } /** Pauses the target: all running actions and newly added actions will be paused. */ @@ -126,7 +126,7 @@ public: 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/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/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 36f72c81c5..55f3e9ebc4 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -857,7 +857,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 +880,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(); diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 880117a2a3..9ff23333a1 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.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(); 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 c71a26afaf..f01328f50e 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -189,10 +189,10 @@ EventDispatcher::~EventDispatcher() void EventDispatcher::visitTarget(Node* node) { - long i = 0; + int i = 0; auto& children = node->getChildren(); - long childrenCount = children.size(); + auto childrenCount = children.size(); if(childrenCount > 0) { @@ -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) 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/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 25063eb023..7c7ad41f5a 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; 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 54427e9c43..0310f69cba 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -640,7 +640,7 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity) }); V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - long count = _textureAtlas->getTotalQuads(); + auto count = _textureAtlas->getTotalQuads(); Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); if (_isOpacityModifyRGB) { @@ -706,7 +706,7 @@ void Label::updateDisplayedColor(const Color3B& parentColor) }); V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - long 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..c2ca9158f6 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,13 +54,13 @@ 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())) { @@ -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,8 +177,8 @@ void LabelAtlas::updateAtlasValues() } if (n > 0 ){ _textureAtlas->setDirty(true); - long totalQuads = _textureAtlas->getTotalQuads(); - if (static_cast(n) > totalQuads) { + auto totalQuads = _textureAtlas->getTotalQuads(); + if (n > totalQuads) { _textureAtlas->increaseTotalQuadsWith(n - totalQuads); } } @@ -187,8 +187,8 @@ 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); } @@ -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 99303afa96..02aee2b734 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); diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 75a32dbaf2..f893e60f38 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -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; } diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index e07c1a6b94..c9184feba6 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: diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index c1e14d5cd1..3a31d7efdf 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -395,7 +395,7 @@ void Node::setPositionY(float y) setPosition(Point(_position.x, y)); } -long Node::getChildrenCount() const +int Node::getChildrenCount() const { return _children.size(); } @@ -683,7 +683,7 @@ void Node::removeChild(Node* child, bool cleanup /* = true */) return; } - long index = _children.getIndex(child); + auto index = _children.getIndex(child); if( index != CC_INVALID_INDEX ) this->detachChild( child, index, cleanup ); } @@ -741,7 +741,7 @@ void Node::removeAllChildrenWithCleanup(bool cleanup) } -void Node::detachChild(Node *child, long childIndex, bool doCleanup) +void Node::detachChild(Node *child, int childIndex, bool doCleanup) { // IMPORTANT: // -1st do onExit @@ -852,7 +852,7 @@ void Node::visit() } this->transform(); - long i = 0; + int i = 0; if(!_children.empty()) { @@ -1055,7 +1055,7 @@ Action * Node::getActionByTag(int tag) return _actionManager->getActionByTag(tag, this); } -long Node::getNumberOfRunningActions() const +int Node::getNumberOfRunningActions() const { return _actionManager->getNumberOfRunningActionsInTarget(this); } diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index c1fa60b23c..c9de3a916c 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -621,7 +621,7 @@ public: * * @return The amount of children. */ - long getChildrenCount() const; + int getChildrenCount() const; /** * Sets the parent node @@ -1042,10 +1042,10 @@ public: * * @return The number of actions that are running plus the ones that are schedule to run */ - long 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 @@ -1402,7 +1402,7 @@ protected: 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; diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index c722c73f31..74df4b4ad0 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -177,7 +177,7 @@ 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 - long pos = addChildHelper(child,zOrder,tag); + auto pos = addChildHelper(child,zOrder,tag); //get new atlasIndex int atlasIndex = 0; @@ -202,7 +202,7 @@ 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 -long 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"); @@ -210,7 +210,7 @@ long ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) _children.reserve(4); //don't use a lazy insert - long pos = searchNewPositionInChildrenForZ(z); + auto pos = searchNewPositionInChildrenForZ(z); _children.insert(pos, child); @@ -244,7 +244,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) // no reordering if only 1 child if (!_children.empty()) { - long newIndex = 0, oldIndex = 0; + int newIndex = 0, oldIndex = 0; getCurrentIndex(&oldIndex, &newIndex, child, zOrder); @@ -285,15 +285,15 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) child->_setZOrder(zOrder); } -void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* 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; - long count = _children.size(); + auto count = _children.size(); - for( long i=0; i < count; i++ ) + for( int i=0; i < count; i++ ) { Node* pNode = _children.at(i); @@ -330,17 +330,17 @@ void ParticleBatchNode::getCurrentIndex(long* oldIndex, long* newIndex, Node* ch if( ! foundNewIdx ) { - *newIndex = count; + *newIndex = static_cast(count); } *newIndex += minusOne; } -long ParticleBatchNode::searchNewPositionInChildrenForZ(int z) +int ParticleBatchNode::searchNewPositionInChildrenForZ(int z) { - long count = _children.size(); + auto count = _children.size(); - for( long i=0; i < count; i++ ) + for( int i=0; i < count; i++ ) { Node *child = _children.at(i); if (child->getZOrder() > z) @@ -348,7 +348,7 @@ long ParticleBatchNode::searchNewPositionInChildrenForZ(int z) return i; } } - return count; + return static_cast(count); } // override removeChild: @@ -376,7 +376,7 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup) updateAllAtlasIndexes(); } -void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) +void ParticleBatchNode::removeChildAtIndex(int index, bool doCleanup) { removeChild(_children.at(index), doCleanup); } @@ -412,7 +412,7 @@ void ParticleBatchNode::draw(void) -void ParticleBatchNode::increaseAtlasCapacityTo(long quantity) +void ParticleBatchNode::increaseAtlasCapacityTo(int quantity) { CCLOG("cocos2d: ParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", (long)_textureAtlas->getCapacity(), @@ -426,7 +426,7 @@ void ParticleBatchNode::increaseAtlasCapacityTo(long 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; @@ -462,7 +462,7 @@ void ParticleBatchNode::insertChild(ParticleSystem* system, int index) //rebuild atlas indexes void ParticleBatchNode::updateAllAtlasIndexes() { - unsigned int index = 0; + int index = 0; _children.forEach([&index](Node* child){ ParticleSystem* partiSys = static_cast(child); @@ -473,7 +473,7 @@ void ParticleBatchNode::updateAllAtlasIndexes() // ParticleBatchNode - CocosNodeTexture protocol -void ParticleBatchNode::updateBlendFunc(void) +void ParticleBatchNode::updateBlendFunc() { if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha()) _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED; @@ -490,7 +490,7 @@ void ParticleBatchNode::setTexture(Texture2D* texture) } } -Texture2D* ParticleBatchNode::getTexture(void) const +Texture2D* ParticleBatchNode::getTexture() const { return _textureAtlas->getTexture(); } @@ -500,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 d7b6b93e42..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(long quantity); - long searchNewPositionInChildrenForZ(int z); - void getCurrentIndex(long* oldIndex, long* newIndex, Node* child, int z); - long addChildHelper(ParticleSystem* child, int z, int aTag); + void 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 9c58e15c9a..42514df77f 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -385,7 +385,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& std::string textureData = dictionary["textureImageData"].asString(); CCASSERT(!textureData.empty(), ""); - long dataLen = textureData.size(); + auto dataLen = textureData.size(); if (dataLen != 0) { // if it fails, try to get it from the base64-gzipped data diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 3a2e0be1e4..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); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 95f1fbd4c4..ef70a53267 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"); @@ -110,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); @@ -291,7 +291,7 @@ void SpriteBatchNode::sortAllChildren() void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex) { auto& array = sprite->getChildren(); - long count = array.size(); + auto count = array.size(); int oldIndex = 0; @@ -406,7 +406,7 @@ void SpriteBatchNode::increaseAtlasCapacity(void) // if we're going beyond the current TextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive - long quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; + auto quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", _textureAtlas->getCapacity(), @@ -483,7 +483,7 @@ int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *sprite) int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) { auto& siblings = sprite->getParent()->getChildren(); - long childIndex = siblings.getIndex(sprite); + auto childIndex = siblings.getIndex(sprite); // ignore parent Z if parent is spriteSheet bool ignoreParent = (SpriteBatchNode*)(sprite->getParent()) == this; @@ -551,7 +551,7 @@ void SpriteBatchNode::appendChild(Sprite* sprite) } _descendants.push_back(sprite); - long index = _descendants.size()-1; + auto index = _descendants.size()-1; sprite->setAtlasIndex(index); 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/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index d8c0bfbaf8..3a0ef96f6a 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) { @@ -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 39b2cd7d30..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 - long 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..9853a71d28 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -446,7 +446,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 +607,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..b50aeb7fc6 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) 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..e508fb32e6 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) diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index ebde2f9963..206f0408e1 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -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) diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index c322f8300a..42147cb025 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -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/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/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index c6623a234f..2e7fd6314d 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; @@ -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; @@ -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 4c06f23ecb..6522d88317 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -492,7 +492,7 @@ 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 = nullptr; CCASSERT(filename != nullptr && size != nullptr && mode != nullptr, "Invalid parameters."); @@ -522,7 +522,7 @@ 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 = nullptr; unzFile pFile = nullptr; @@ -548,7 +548,7 @@ unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char 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; @@ -756,7 +756,7 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename 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( dict["filenames"].asValueMap()); diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index be2f3f2af7..e5925e2818 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -84,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. @@ -94,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. 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 210f3c3cb2..8435777384 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -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 @@ -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,7 +1414,7 @@ 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; @@ -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); @@ -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 b1e815866c..ca75ca70ab 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -114,7 +114,7 @@ bool SAXParser::parse(const char* pXMLData, size_t 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/CCThread.cpp b/cocos/2d/platform/CCThread.cpp index 7d4a23a216..a7dfb54609 100644 --- a/cocos/2d/platform/CCThread.cpp +++ b/cocos/2d/platform/CCThread.cpp @@ -31,7 +31,7 @@ NS_CC_BEGIN std::list>* ThreadHelper::_callbackList = new std::list>(); std::mutex* ThreadHelper::_mutex = new std::mutex; -long ThreadHelper::_callbackNumberPerFrame = 5; +int ThreadHelper::_callbackNumberPerFrame = 5; void* ThreadHelper::createAutoreleasePool() @@ -56,7 +56,7 @@ void ThreadHelper::doCallback() { _mutex->lock(); auto iter = _callbackList->begin(); - long i = 0; + int i = 0; while (iter != _callbackList->end()) { auto f = *iter; @@ -75,7 +75,7 @@ void ThreadHelper::doCallback() _mutex->unlock(); } -void ThreadHelper::setCallbackNumberPerFrame(long callbackNumberPerFrame) +void ThreadHelper::setCallbackNumberPerFrame(int callbackNumberPerFrame) { _callbackNumberPerFrame = callbackNumberPerFrame; } diff --git a/cocos/2d/platform/CCThread.h b/cocos/2d/platform/CCThread.h index b0998eeb59..1443303312 100644 --- a/cocos/2d/platform/CCThread.h +++ b/cocos/2d/platform/CCThread.h @@ -72,7 +72,7 @@ public: * @lua NA @since v3.0 */ - static void setCallbackNumberPerFrame(long callbackNumberPerFrame); + static void setCallbackNumberPerFrame(int callbackNumberPerFrame); private: // This function will be call by Director to call some call back function on gl thread @@ -81,7 +81,7 @@ private: static std::list> *_callbackList; static std::mutex *_mutex; // How many callback functions invoked per frame - static long _callbackNumberPerFrame; + static int _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/CCThread.mm b/cocos/2d/platform/apple/CCThread.mm index 4e138fb889..f8c84bb77f 100644 --- a/cocos/2d/platform/apple/CCThread.mm +++ b/cocos/2d/platform/apple/CCThread.mm @@ -28,7 +28,7 @@ NS_CC_BEGIN std::list>* ThreadHelper::_callbackList = new std::list>(); std::mutex* ThreadHelper::_mutex = new std::mutex; -long ThreadHelper::_callbackNumberPerFrame = 5; +int ThreadHelper::_callbackNumberPerFrame = 5; void* ThreadHelper::createAutoreleasePool() { @@ -53,7 +53,7 @@ void ThreadHelper::doCallback() { _mutex->lock(); auto iter = _callbackList->begin(); - long i = 0; + int i = 0; while (iter != _callbackList->end()) { auto f = *iter; @@ -72,7 +72,7 @@ void ThreadHelper::doCallback() _mutex->unlock(); } -void ThreadHelper::setCallbackNumberPerFrame(long callbackNumberPerFrame) +void ThreadHelper::setCallbackNumberPerFrame(int callbackNumberPerFrame) { _callbackNumberPerFrame = callbackNumberPerFrame; } 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/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/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/CCMap.h b/cocos/base/CCMap.h index 7a928a5cc0..8630dff9f3 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -46,7 +46,7 @@ public: CCLOGINFO("In the default constructor of Map!"); } - explicit Map(long capacity) + explicit Map(int capacity) : _data() { CCLOGINFO("In the constructor with capacity of Map!"); @@ -73,7 +73,7 @@ public: } /** Sets capacity of current array */ - void reserve(long capacity) + void reserve(int capacity) { _data.reserve(capacity); } diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index 046e8f2e7a..922fc6e60e 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -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..d009a2efb7 100644 --- a/cocos/base/CCString.h +++ b/cocos/base/CCString.h @@ -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/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index 36f4b3a505..1947eeb0bf 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -287,7 +287,7 @@ Spawn * ActionNode::refreshActionProperty() } Vector cSequenceArray; - long frameCount = cArray->count(); + auto frameCount = cArray->count(); for (int i = 0; i < frameCount; i++) { ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i)); diff --git a/cocos/editor-support/spine/Atlas.cpp b/cocos/editor-support/spine/Atlas.cpp index e3d6d799b4..2c75107af5 100644 --- a/cocos/editor-support/spine/Atlas.cpp +++ b/cocos/editor-support/spine/Atlas.cpp @@ -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; 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/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/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 5a05b02497..f734574565 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -45,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/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index b045c433a6..2e1f094568 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,7 +712,7 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -long PhysicsShapeEdgePolygon::getPointsCount() const +int PhysicsShapeEdgePolygon::getPointsCount() const { return _info->getShapes().size() + 1; } @@ -773,7 +773,7 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -long PhysicsShapeEdgeChain::getPointsCount() const +int PhysicsShapeEdgeChain::getPointsCount() const { return _info->getShapes().size() + 1; } diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index a72f155765..1fb86e14d7 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -207,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); @@ -250,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); @@ -272,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); @@ -294,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.h b/cocos/physics/CCPhysicsWorld.h index d1433d97fc..384ee6250e 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -83,11 +83,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 = 0x00; + static const int DEBUGDRAW_SHAPE = 0x01; + static const int DEBUGDRAW_JOINT = 0x02; + static const int DEBUGDRAW_CONTACT = 0x04; + static const int DEBUGDRAW_ALL = DEBUGDRAW_SHAPE | DEBUGDRAW_JOINT | DEBUGDRAW_CONTACT; public: /** Adds a joint to the physics world.*/ From 9676821479d6939cf9db116b06c32a604a078cb4 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 5 Dec 2013 17:38:08 +0800 Subject: [PATCH 071/107] use int in Vector --- cocos/base/CCVector.h | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 280a1854f4..2eab619e16 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -42,7 +42,7 @@ public: } /** creates an emptry Vector */ - explicit Vector(long capacity) + explicit Vector(int capacity) : _data() { CCLOGINFO("In the default constructor with capacity of Vector."); @@ -86,24 +86,24 @@ public: } // Don't uses operator since we could not decide whether it needs 'retain'/'release'. -// T& operator[](long index) +// T& operator[](int index) // { // return _data[index]; // } // -// const T& operator[](long index) const +// const T& operator[](int index) const // { // return _data[index]; // } /** Sets capacity of current array */ - void reserve(long capacity) + void reserve(int capacity) { _data.reserve(capacity); } /** Returns capacity of the array */ - long capacity() const + int capacity() const { return _data.capacity(); } @@ -111,7 +111,7 @@ public: // Querying an Array /** Returns element count of the array */ - size_t size() const + int size() const { return _data.size(); } @@ -122,9 +122,9 @@ public: } /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ - long getIndex(T object) const + int getIndex(T object) const { - long i = 0; + int i = 0; for (auto it = _data.begin(); it != _data.end(); ++it, ++i) { if (*it == object) @@ -137,7 +137,7 @@ public: } /** Returns an element with a certain index */ - T at(size_t index) const + T at(int index) const { CCASSERT( index >= 0 && index < size(), "index out of range in getObjectAtIndex()"); return _data[index]; @@ -178,7 +178,7 @@ public: if (s != other.size()) return false; - for (long i = 0; i < s; i++) + for (int i = 0; i < s; i++) { if (!this->at(i)->isEqual(other.at(i))) { @@ -208,7 +208,7 @@ public: } /** Insert a certain object at a certain index */ - void insert(long index, T object) + void insert(int index, T object) { CCASSERT(index >= 0 && index <= size(), "Invalid index!"); CCASSERT(object != nullptr, "The object should not be nullptr"); @@ -238,7 +238,7 @@ public: } /** Removes an element with a certain index */ - void remove(long index) + void remove(int index) { CCASSERT(!_data.empty() && index >=0 && index < size(), "Invalid index!"); auto it = std::next( begin(), index ); @@ -260,8 +260,8 @@ public: /** Swap two elements */ void swap(T object1, T object2) { - long idx1 = getIndex(object1); - long idx2 = getIndex(object2); + auto idx1 = getIndex(object1); + auto idx2 = getIndex(object2); CCASSERT(idx1>=0 && idx2>=0, "invalid object index"); @@ -269,7 +269,7 @@ public: } /** Swap two elements with certain indexes */ - void swap(long index1, long index2) + void swap(int index1, int index2) { CCASSERT(index1 >=0 && index1 < size() && index2 >= 0 && index2 < size(), "Invalid indices"); @@ -277,7 +277,7 @@ public: } /** Replace object at index with another object. */ - void replace(long index, T object) + void replace(int index, T object) { CCASSERT(index >= 0 && index < size(), "Invalid index!"); CCASSERT(object != nullptr, "The object should not be nullptr"); From f02d15d71f1e938896d99bfa53da68e7b3fd33e8 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 6 Dec 2013 11:46:13 +0800 Subject: [PATCH 072/107] initialize static member variable in cpp --- cocos/physics/CCPhysicsWorld.cpp | 6 ++++++ cocos/physics/CCPhysicsWorld.h | 10 +++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 70bae33eff..41d6f08f9c 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 diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 384ee6250e..05999d990d 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -83,11 +83,11 @@ typedef PhysicsRectQueryCallbackFunc PhysicsPointQueryCallbackFunc; class PhysicsWorld { public: - static const int DEBUGDRAW_NONE = 0x00; - static const int DEBUGDRAW_SHAPE = 0x01; - static const int DEBUGDRAW_JOINT = 0x02; - static const int DEBUGDRAW_CONTACT = 0x04; - static const int 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.*/ From 29bd5001aee72016d4e122e3c1d04c11edf76dda Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Fri, 6 Dec 2013 11:53:43 +0800 Subject: [PATCH 073/107] UserDefault::setDataForKey on android will cause memory leak --- cocos/2d/CCUserDefaultAndroid.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp index 8f6895f572..ded6b7eaeb 100644 --- a/cocos/2d/CCUserDefaultAndroid.cpp +++ b/cocos/2d/CCUserDefaultAndroid.cpp @@ -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); From 1502fef7e4e402f68ef447d17a292f284cec44d9 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 6 Dec 2013 14:15:01 +0800 Subject: [PATCH 074/107] use Schedule::performFunctionInCocosThread --- cocos/2d/CCDirector.cpp | 3 -- cocos/2d/CCTextureCache.cpp | 13 ------- cocos/2d/platform/CCThread.cpp | 40 --------------------- cocos/2d/platform/CCThread.h | 23 ------------ cocos/2d/platform/apple/CCThread.mm | 40 --------------------- extensions/assets-manager/AssetsManager.cpp | 16 ++++----- 6 files changed, 8 insertions(+), 127 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 55f3e9ebc4..bce116b491 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -1037,9 +1037,6 @@ void DisplayLinkDirector::mainLoop() } else if (! _invalid) { - // invoke call back from other thread - ThreadHelper::doCallback(); - drawScene(); // release the objects diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 9853a71d28..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; diff --git a/cocos/2d/platform/CCThread.cpp b/cocos/2d/platform/CCThread.cpp index a7dfb54609..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; -int 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(); - int 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(int callbackNumberPerFrame) -{ - _callbackNumberPerFrame = callbackNumberPerFrame; -} - #endif NS_CC_END diff --git a/cocos/2d/platform/CCThread.h b/cocos/2d/platform/CCThread.h index 1443303312..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(int 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 int _callbackNumberPerFrame; }; // end of platform group diff --git a/cocos/2d/platform/apple/CCThread.mm b/cocos/2d/platform/apple/CCThread.mm index f8c84bb77f..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; -int 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(); - int 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(int callbackNumberPerFrame) -{ - _callbackNumberPerFrame = callbackNumberPerFrame; -} - NS_CC_END 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); }); From fa7c97171bfe29f3a4c1e9fb8b9d2ab62e92f2aa Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 6 Dec 2013 16:32:06 +0800 Subject: [PATCH 075/107] fix some warnings --- cocos/2d/CCActionCatmullRom.cpp | 4 +- cocos/2d/CCAnimationCache.cpp | 4 +- cocos/2d/CCEventDispatcher.cpp | 2 +- cocos/2d/CCFontAtlas.cpp | 2 +- cocos/2d/CCFontFNT.cpp | 2 +- cocos/2d/CCFontFreeType.cpp | 8 ++-- cocos/2d/CCLabelAtlas.cpp | 6 +-- cocos/2d/CCLabelBMFont.cpp | 4 +- cocos/2d/CCLabelTextFormatter.cpp | 8 ++-- cocos/2d/CCMenuItem.cpp | 2 +- cocos/2d/CCParticleSystem.cpp | 2 +- cocos/2d/CCSpriteBatchNode.cpp | 6 +-- cocos/2d/CCTMXLayer.cpp | 2 +- cocos/2d/CCTMXXMLParser.cpp | 4 +- cocos/2d/CCTextFieldTTF.cpp | 6 +-- cocos/2d/CCTextImage.cpp | 6 +-- cocos/2d/CCTextImage.h | 6 +-- cocos/2d/CCTexture2D.cpp | 2 +- cocos/2d/CCUserDefault.cpp | 2 +- cocos/2d/ZipUtils.cpp | 26 +++++------ cocos/2d/ZipUtils.h | 26 +++++------ cocos/2d/ccUTF8.cpp | 42 +++++++++-------- cocos/2d/platform/CCEGLViewProtocol.cpp | 4 +- cocos/2d/platform/CCImageCommon_cpp.h | 6 +-- cocos/2d/platform/CCSAXParser.cpp | 2 +- cocos/2d/platform/mac/CCImage.mm | 12 ++--- cocos/base/CCArray.cpp | 46 +++++++++---------- cocos/base/CCArray.h | 32 ++++++------- cocos/base/CCDictionary.cpp | 4 +- cocos/base/CCNS.cpp | 18 ++++---- cocos/base/CCString.cpp | 6 +-- cocos/base/CCString.h | 2 +- cocos/base/CCVector.h | 2 +- cocos/editor-support/spine/Atlas.cpp | 12 ++--- cocos/gui/UITextField.cpp | 2 +- cocos/network/SocketIO.cpp | 28 +++++------ cocos/network/WebSocket.cpp | 16 +++---- cocos/network/WebSocket.h | 4 +- cocos/physics/CCPhysicsShape.cpp | 4 +- .../PerformanceNodeChildrenTest.cpp | 2 +- 40 files changed, 188 insertions(+), 186 deletions(-) diff --git a/cocos/2d/CCActionCatmullRom.cpp b/cocos/2d/CCActionCatmullRom.cpp index 7c3cc2f81c..bab094f288 100644 --- a/cocos/2d/CCActionCatmullRom.cpp +++ b/cocos/2d/CCActionCatmullRom.cpp @@ -134,7 +134,7 @@ void PointArray::insertControlPoint(Point &controlPoint, 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)); } @@ -291,7 +291,7 @@ CardinalSplineTo* CardinalSplineTo::clone() const void CardinalSplineTo::update(float time) { - ssize_t p; + int p; float lt; // eg. diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index f0828aaa6d..a1d0ddd1ec 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -102,7 +102,7 @@ void AnimationCache::parseVersion1(const ValueMap& animations) continue; } - Vector frames(frameNames.size()); + Vector frames(static_cast(frameNames.size())); for (auto& frameName : frameNames) { @@ -155,7 +155,7 @@ void AnimationCache::parseVersion2(const ValueMap& animations) } // Array of AnimationFrames - Vector array(frameArray.size()); + Vector array(static_cast(frameArray.size())); for (auto& obj : frameArray) { diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index f01328f50e..fbbe534cde 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -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/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 7c7ad41f5a..08e8d0304d 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -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/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index c2ca9158f6..8ec15a3c1c 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -62,7 +62,7 @@ bool LabelAtlas::initWithString(const std::string& string, const std::string& ch 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); @@ -179,7 +179,7 @@ void LabelAtlas::updateAtlasValues() _textureAtlas->setDirty(true); auto totalQuads = _textureAtlas->getTotalQuads(); if (n > totalQuads) { - _textureAtlas->increaseTotalQuadsWith(n - totalQuads); + _textureAtlas->increaseTotalQuadsWith(static_cast(n - totalQuads)); } } } @@ -190,7 +190,7 @@ void LabelAtlas::setString(const std::string &label) auto len = label.size(); if (len > _textureAtlas->getTotalQuads()) { - _textureAtlas->resizeCapacity(len); + _textureAtlas->resizeCapacity(static_cast(len)); } _string.clear(); _string = label; diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 02aee2b734..05e85eb95b 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -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; @@ -1085,7 +1085,7 @@ void LabelBMFont::updateLabel() 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/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index f893e60f38..c97cd7a2fa 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; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 42514df77f..91e05caa05 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -393,7 +393,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData"); CC_BREAK_IF(!buffer); - int deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated); + ssize_t deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated); CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index ef70a53267..748a248f58 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -406,9 +406,9 @@ void SpriteBatchNode::increaseAtlasCapacity(void) // if we're going beyond the current TextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive - auto quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; + int quantity = (_textureAtlas->getCapacity() + 1) * 4 / 3; - CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", + CCLOG("cocos2d: SpriteBatchNode: resizing TextureAtlas capacity from [%d] to [%d].", _textureAtlas->getCapacity(), quantity); @@ -551,7 +551,7 @@ void SpriteBatchNode::appendChild(Sprite* sprite) } _descendants.push_back(sprite); - auto index = _descendants.size()-1; + int index = static_cast(_descendants.size()-1); sprite->setAtlasIndex(index); diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index d4f8659a6a..8515989a6f 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -379,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); diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 6bf2945563..4fa31b4683 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -664,9 +664,9 @@ void TMXMapInfo::endElement(void *ctx, const char *name) 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 CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint); + ssize_t CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint); CCASSERT(inflatedLen == sizeHint, ""); free(buffer); 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 3a0ef96f6a..50338299c7 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -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(); diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index b50aeb7fc6..c01db753bf 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -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/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index b6e4a74289..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); @@ -614,7 +614,7 @@ unsigned char *ZipFile::getFileData(const std::string &fileName, ssize_t *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 42147cb025..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]; 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/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 2e7fd6314d..2eb4e3495e 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -280,7 +280,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys else { // It is error, should return. - CCLOG("Moving touches with id: %ld error", id); + CCLOG("Moving touches with id: %d error", id); return; } } @@ -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; } diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index 8435777384..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; @@ -941,7 +941,7 @@ bool Image::initWithPngData(const unsigned char * data, ssize_t 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); @@ -1418,7 +1418,7 @@ bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen) 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"); diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index ca75ca70ab..ccbd11a9f1 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -81,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; } 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/base/CCArray.cpp b/cocos/base/CCArray.cpp index 4257e3f38a..adb09c237a 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -105,7 +105,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(size_t capacity) +Array* Array::createWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -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"); @@ -196,11 +196,11 @@ bool Array::initWithArray(Array* otherArray) 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) { @@ -238,7 +238,7 @@ bool Array::containsObject(Object* object) const 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))) { @@ -258,12 +258,12 @@ 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); } @@ -279,7 +279,7 @@ 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); @@ -295,7 +295,7 @@ void Array::removeAllObjects() data.erase(std::begin(data), std::end(data)); } -void Array::fastRemoveObjectAtIndex(size_t index) +void Array::fastRemoveObjectAtIndex(int index) { removeObjectAtIndex(index); } @@ -315,12 +315,12 @@ 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; } @@ -448,7 +448,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(size_t capacity) +Array* Array::createWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -480,7 +480,7 @@ Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) { ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName); - Array* ret = Array::createWithCapacity(arr.size()); + 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())); @@ -539,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"); @@ -563,7 +563,7 @@ bool Array::initWithArray(Array* otherArray) return ret; } -size_t Array::getIndexOfObject(Object* object) const +int Array::getIndexOfObject(Object* object) const { return ccArrayGetIndexOfObject(data, object); } @@ -582,7 +582,7 @@ 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 @@ -592,7 +592,7 @@ bool Array::containsObject(Object* object) const 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))) { @@ -614,13 +614,13 @@ void Array::addObjectsFromArray(Array* otherArray) 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"); @@ -643,7 +643,7 @@ 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); } @@ -658,7 +658,7 @@ void Array::removeAllObjects() ccArrayRemoveAllObjects(data); } -void Array::fastRemoveObjectAtIndex(size_t index) +void Array::fastRemoveObjectAtIndex(int index) { ccArrayFastRemoveObjectAtIndex(data, index); } @@ -685,12 +685,12 @@ 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); diff --git a/cocos/base/CCArray.h b/cocos/base/CCArray.h index 32b57d8a4d..7f67569faa 100644 --- a/cocos/base/CCArray.h +++ b/cocos/base/CCArray.h @@ -250,7 +250,7 @@ public: /** 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 */ @@ -295,7 +295,7 @@ 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 @@ -307,7 +307,7 @@ public: /** 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 */ @@ -401,17 +401,17 @@ public: /** 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,7 +447,7 @@ 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 */ @@ -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 diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 107203285f..de9abbb31f 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -109,7 +109,7 @@ Array* Dictionary::allKeys() { HASH_ITER(hh, _elements, pElement, tmp) { - Integer* pOneKey = new Integer(pElement->_intKey); + Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); pArray->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } @@ -144,7 +144,7 @@ Array* Dictionary::allKeysForObject(Object* object) { if (object == pElement->_object) { - Integer* pOneKey = new Integer(pElement->_intKey); + Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); pArray->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } diff --git a/cocos/base/CCNS.cpp b/cocos/base/CCNS.cpp index f2f39e1173..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); @@ -65,8 +65,8 @@ static bool splitWithForm(const std::string& str, strArray& strs) 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 std::string& str, 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); @@ -107,8 +107,8 @@ Rect RectFromString(const std::string& str) 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 std::string& str) 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); diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index 922fc6e60e..c2a6ec6bd1 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 @@ -182,7 +182,7 @@ Array* String::componentsSeparatedByString(const char *delimiter) { Array* result = Array::create(); - int cutAt; + size_t cutAt; while( (cutAt = _string.find_first_of(delimiter)) != _string.npos ) { if(cutAt > 0) diff --git a/cocos/base/CCString.h b/cocos/base/CCString.h index d009a2efb7..09d558f827 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 diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 2eab619e16..2a12c66d76 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -113,7 +113,7 @@ public: /** Returns element count of the array */ int size() const { - return _data.size(); + return static_cast(_data.size()); } bool empty() const diff --git a/cocos/editor-support/spine/Atlas.cpp b/cocos/editor-support/spine/Atlas.cpp index 2c75107af5..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); @@ -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/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/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/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 2e1f094568..a77072e9bd 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -714,7 +714,7 @@ Point PhysicsShapeEdgePolygon::getCenter() int PhysicsShapeEdgePolygon::getPointsCount() const { - return _info->getShapes().size() + 1; + return static_cast(_info->getShapes().size() + 1); } // PhysicsShapeEdgeChain @@ -775,7 +775,7 @@ Point PhysicsShapeEdgeChain::getCenter() int PhysicsShapeEdgeChain::getPointsCount() const { - return _info->getShapes().size() + 1; + return static_cast(_info->getShapes().size() + 1); } void PhysicsShape::setGroup(int group) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp index 127a0e8dc8..ee81b7d36b 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp @@ -321,7 +321,7 @@ 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()); From b5978eeee6a810553f98800fb5d01b97781e5082 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 6 Dec 2013 16:46:19 +0800 Subject: [PATCH 076/107] issue #2790: Bindings-generator supports binding Vector and some bug fixes. --- cocos/2d/CCSpriteFrameCache.cpp | 9 +- .../javascript/bindings/ScriptingCore.cpp | 6 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../bindings/js_manual_conversions.cpp | 560 +++++++++++++++++- .../bindings/js_manual_conversions.h | 100 ++++ tools/bindings-generator | 2 +- 6 files changed, 667 insertions(+), 12 deletions(-) diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index a089484f8c..23c702bb00 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -86,13 +86,14 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+ */ - ValueMap& metadataDict = dictionary["metadata"].asValueMap(); + ValueMap& framesDict = dictionary["frames"].asValueMap(); int format = 0; // get the format - if (!metadataDict.empty()) + if (dictionary.find("metadata") != dictionary.end()) { + ValueMap& metadataDict = dictionary["metadata"].asValueMap(); format = metadataDict["format"].asInt(); } @@ -230,9 +231,9 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) string texturePath(""); - ValueMap& metadataDict = dict["metadata"].asValueMap(); - if (!metadataDict.empty()) + if (dict.find("metadata") != dict.end()) { + ValueMap& metadataDict = dict["metadata"].asValueMap(); // try to read texture file name from meta data texturePath = metadataDict["textureFileName"].asString(); } 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..46cb2c9d29 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 +cd3a15ee39c63c93b40e323eda6fa43f584742aa \ 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/tools/bindings-generator b/tools/bindings-generator index 3e215fc486..eb2bc8934b 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 3e215fc4865a75e25db6f45115350ef2d7a256ca +Subproject commit eb2bc8934b01f6cdc7661648f883e2e6374a5cf7 From ed7c3f717acba8c5f89b2f55063cc5bcdd7547a8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 6 Dec 2013 16:49:17 +0800 Subject: [PATCH 077/107] issue #2790: Travis-ci builds JSB projects again. --- tools/travis-scripts/run-script.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 469db7b066..6deb44beec 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -28,7 +28,7 @@ if [ "$GEN_JSB"x = "YES"x ]; then fi export NDK_ROOT=$HOME/bin/android-ndk cd $COCOS2DX_ROOT/tools/travis-scripts - # ./generate-jsbindings.sh + ./generate-jsbindings.sh elif [ "$PLATFORM"x = "android"x ]; then export NDK_ROOT=$HOME/bin/android-ndk @@ -50,13 +50,13 @@ 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" hellocpp testcpp simplegame + ./android-build.py -n "NDK_BUG=0 -j10" hellocpp testcpp simplegame testjavascipt # Build template - # echo "Building template ..." - # cd $COCOS2DX_ROOT/template - # build_android multi-platform-cpp - # build_android multi-platform-js + echo "Building template ..." + cd $COCOS2DX_ROOT/template + build_android multi-platform-cpp + build_android multi-platform-js # build_android multi-platform-lua elif [ "$PLATFORM"x = "nacl"x ]; then From 7aff958063752dcab22f99304009e9f3d33a8921 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 6 Dec 2013 17:09:36 +0800 Subject: [PATCH 078/107] issue #2790: A typo fix. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 6deb44beec..c43a6d53d1 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" hellocpp testcpp simplegame testjavascipt + ./android-build.py -n "NDK_BUG=0 -j10" hellocpp testcpp simplegame testjavascript # Build template echo "Building template ..." From c9163779701f059aefb55845daa7ec39c864e2a9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 6 Dec 2013 17:23:31 +0800 Subject: [PATCH 079/107] issue #2790: Comments building template for android. --- tools/travis-scripts/run-script.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index c43a6d53d1..89f66668a3 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -53,10 +53,10 @@ elif [ "$PLATFORM"x = "android"x ]; then ./android-build.py -n "NDK_BUG=0 -j10" hellocpp testcpp simplegame testjavascript # Build template - echo "Building template ..." - cd $COCOS2DX_ROOT/template - build_android multi-platform-cpp - build_android multi-platform-js + # echo "Building template ..." + # cd $COCOS2DX_ROOT/template + # build_android multi-platform-cpp + # build_android multi-platform-js # build_android multi-platform-lua elif [ "$PLATFORM"x = "nacl"x ]; then From 8442f17259c9d60c9d307cdf19e39c3c21760442 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 6 Dec 2013 09:31:16 +0000 Subject: [PATCH 080/107] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index e4ce0d5a62..db718e871a 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit e4ce0d5a6240c303a591a4476564bd7080ab06c2 +Subproject commit db718e871a7b59acdbefb679796c824d7a2b3ebf From 6cd573fa7f21fa4b42aaa0eaf106d9c62de3c60a Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 6 Dec 2013 18:16:58 +0800 Subject: [PATCH 081/107] issue #2790: Deprecates CCSet. --- cocos/2d/CCActionManager.cpp | 39 ++++++++++++++---------------- cocos/2d/CCActionManager.h | 24 +++++++++---------- cocos/2d/CCDeprecated.h | 8 ++++--- cocos/2d/CCLayer.h | 8 +++---- cocos/2d/CCScheduler.cpp | 27 ++++++++++----------- cocos/2d/CCScheduler.h | 15 ++++++------ cocos/base/CCDataVisitor.cpp | 8 +++---- cocos/base/CCDataVisitor.h | 6 ++--- cocos/base/CCSet.cpp | 46 ++++++++++++++++++------------------ cocos/base/CCSet.h | 20 ++++++++-------- 10 files changed, 97 insertions(+), 104 deletions(-) diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index d4981053c6..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; @@ -120,7 +120,7 @@ void ActionManager::removeActionAtIndex(int 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) @@ -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, ""); @@ -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, ""); @@ -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 -int 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 53d0fe1109..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,50 +76,50 @@ 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. */ - int getNumberOfRunningActionsInTarget(const Object *target) const; + int getNumberOfRunningActionsInTarget(const Node *target) const; /** @deprecated use getNumberOfRunningActionsInTarget() instead */ - CC_DEPRECATED_ATTRIBUTE inline 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 diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index 323be9f642..d7b60f8074 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -540,7 +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; @@ -549,7 +548,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 +566,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 +1025,11 @@ 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/CCLayer.h b/cocos/2d/CCLayer.h index 2284e7bf46..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. diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 88f067f666..f1b1c9e59c 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -764,22 +764,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 @@ -791,7 +790,7 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) if(entry->priority >= minPriority) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } } @@ -801,7 +800,7 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) DL_FOREACH_SAFE( _updates0List, entry, tmp ) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } @@ -810,20 +809,18 @@ 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) diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index cfda2732d7..64325ae32f 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -27,13 +27,13 @@ THE SOFTWARE. #ifndef __CCSCHEDULER_H__ #define __CCSCHEDULER_H__ -#include +#include "CCObject.h" +#include "CCVector.h" +#include "uthash.h" + #include #include -#include "CCObject.h" -#include "uthash.h" - NS_CC_BEGIN /** @@ -41,7 +41,6 @@ NS_CC_BEGIN * @{ */ -class Set; // // Timer // @@ -247,19 +246,19 @@ 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); /** calls a function on the cocos2d thread. Useful when you need to call a cocos2d function from another thread. This function is thread safe. diff --git a/cocos/base/CCDataVisitor.cpp b/cocos/base/CCDataVisitor.cpp index 2d2a1f8121..a62b130cfa 100644 --- a/cocos/base/CCDataVisitor.cpp +++ b/cocos/base/CCDataVisitor.cpp @@ -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); } @@ -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..ba8b83726f 100644 --- a/cocos/base/CCDataVisitor.h +++ b/cocos/base/CCDataVisitor.h @@ -38,7 +38,7 @@ class Double; class String; class Array; class Dictionary; -class Set; +class __Set; class Data; /** @@ -79,7 +79,7 @@ public: virtual void visit(const String *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); }; @@ -100,7 +100,7 @@ public: virtual void visit(const String *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/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. */ From f34083e87f810af67f722e7bd7e3781479a84598 Mon Sep 17 00:00:00 2001 From: signmotion Date: Fri, 6 Dec 2013 22:08:32 +0200 Subject: [PATCH 082/107] - Fixed some slips. --- cocos/2d/platform/win32/CCEGLView.cpp | 4 ++-- extensions/GUI/CCControlExtension/CCScale9Sprite.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index 3a18b81917..ce9b7f43d8 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -413,7 +413,7 @@ EGLView::EGLView() { g_keyCodeMap.insert(std::make_pair(item.glfwKeyCode, item.keyCode)); } - strcpy(_viewName, "Cocos2dxWin32"); + _viewName = "Cocos2dxWin32"; glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError); glfwInit(); } @@ -433,7 +433,7 @@ bool EGLView::init(const char* viewName, float width, float height, float frameZ setFrameZoomFactor(frameZoomFactor); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); - _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName, nullptr, nullptr); + _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); glfwMakeContextCurrent(_mainWindow); glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]); diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 8ad857fd7c..7e9be764b1 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); From 23ad9f4e1a4489c3315803397bc1adc8049bd946 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 10:46:40 +0800 Subject: [PATCH 083/107] issue #2790: Adds const version of Vector::forEach. --- cocos/base/CCVector.h | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 2a12c66d76..2314e325ba 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -25,10 +25,12 @@ THE SOFTWARE. #ifndef __CCVECTOR_H__ #define __CCVECTOR_H__ -#include -#include // std::for_each #include "ccMacros.h" +#include +#include +#include // std::for_each + NS_CC_BEGIN template @@ -299,9 +301,19 @@ public: _data.shrink_to_fit(); } - void forEach(std::function callback) + void forEach(const std::function& callback) { - if (size() <= 0) + 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){ @@ -309,9 +321,19 @@ public: }); } - void forEachReverse(std::function callback) + void forEachReverse(const std::function& callback) { - if (size() <= 0) + 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){ From 165cdf7fe62469c8a5305b190fe5f1b7ffda3a58 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 10:48:02 +0800 Subject: [PATCH 084/107] issue #2790: Deprecates CCArray. --- cocos/2d/CCDeprecated.h | 2 +- cocos/2d/CCDirector.h | 4 +- cocos/2d/CCScheduler.h | 2 - cocos/base/CCArray.cpp | 170 +++++++++++++++---------------- cocos/base/CCArray.h | 33 +++--- cocos/base/CCDataVisitor.cpp | 4 +- cocos/base/CCDataVisitor.h | 6 +- cocos/base/CCDictionary.h | 16 +-- cocos/base/CCString.h | 2 +- cocos/physics/CCPhysicsBody.cpp | 22 ++-- cocos/physics/CCPhysicsBody.h | 11 +- cocos/physics/CCPhysicsWorld.cpp | 64 +++++------- cocos/physics/CCPhysicsWorld.h | 17 ++-- 13 files changed, 167 insertions(+), 186 deletions(-) diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index d7b60f8074..bae29435be 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -540,7 +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 Array CCArray; CC_DEPRECATED_ATTRIBUTE typedef Dictionary CCDictionary; CC_DEPRECATED_ATTRIBUTE typedef DataVisitor CCDataVisitor; CC_DEPRECATED_ATTRIBUTE typedef PrettyPrinter CCPrettyPrinter; @@ -1030,6 +1029,7 @@ 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.h b/cocos/2d/CCDirector.h index 9ff23333a1..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" @@ -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/CCScheduler.h b/cocos/2d/CCScheduler.h index 64325ae32f..247b773d00 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -108,8 +108,6 @@ struct _listEntry; struct _hashSelectorEntry; struct _hashUpdateEntry; -class Array; - /** @brief Scheduler is responsible for triggering the scheduled callbacks. You should not use NSTimer. Instead use this class. diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index adb09c237a..333183a822 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -36,15 +36,15 @@ NS_CC_BEGIN // 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(int 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(int 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(int capacity) +bool __Array::initWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -190,13 +190,13 @@ bool Array::initWithCapacity(int capacity) return true; } -bool Array::initWithArray(Array* otherArray) +bool __Array::initWithArray(__Array* otherArray) { data = otherArray->data; return true; } -int Array::getIndexOfObject(Object* object) const +int __Array::getIndexOfObject(Object* object) const { auto it = data.begin(); @@ -211,7 +211,7 @@ int Array::getIndexOfObject(Object* object) const return -1; } -Object* Array::getRandomObject() +Object* __Array::getRandomObject() { if (data.size()==0) { @@ -230,13 +230,13 @@ 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 (int i = 0; i < this->count(); ++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, int index) +void __Array::insertObject(Object* object, int index) { data.insert(std::begin(data) + index, RCPtr(object)); } -void Array::setObject(Object* object, int 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(int 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(int 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(int index1, int index2) +void __Array::exchangeObjectAtIndex(int index1, int index2) { std::swap(data[index1], data[index2]); } -void Array::replaceObjectAtIndex(int 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(int 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(int 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,11 +476,11 @@ Array* Array::createWithContentsOfFile(const char* fileName) return ret; } -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +__Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName) { ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName); - Array* ret = Array::createWithCapacity(static_cast(arr.size())); + __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())); @@ -489,14 +489,14 @@ Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) 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"); @@ -509,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"); @@ -539,7 +539,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool __Array::initWithCapacity(int capacity) { CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); @@ -547,7 +547,7 @@ bool Array::initWithCapacity(int capacity) return true; } -bool Array::initWithArray(Array* otherArray) +bool __Array::initWithArray(__Array* otherArray) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -563,12 +563,12 @@ bool Array::initWithArray(Array* otherArray) return ret; } -int 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) { @@ -585,12 +585,12 @@ Object* Array::getRandomObject() 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 (int i = 0; i < this->count(); ++i) { @@ -602,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, int index) +void __Array::insertObject(Object* object, int index) { CCASSERT(data, "Array not initialized"); ccArrayInsertObjectAtIndex(data, object, index); } -void Array::setObject(Object* object, int index) +void __Array::setObject(Object* object, int index) { CCASSERT(index >= 0 && index < count(), "Invalid index"); @@ -632,43 +632,43 @@ void Array::setObject(Object* object, int 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(int 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(int 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) @@ -685,18 +685,18 @@ void Array::exchangeObject(Object* object1, Object* object2) ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void __Array::exchangeObjectAtIndex(int index1, int index2) { ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::replaceObjectAtIndex(int 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) { @@ -712,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); @@ -752,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 7f67569faa..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(int 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 @@ -300,7 +300,7 @@ public: * @js NA * @lua NA */ - bool initWithArray(Array* otherArray); + bool initWithArray(__Array* otherArray); // Querying an Array @@ -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,7 +397,7 @@ 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 */ @@ -451,7 +451,7 @@ public: /** Remove all elements * @js NA */ - void removeObjectsInArray(Array* otherArray); + void removeObjectsInArray(__Array* otherArray); /** Remove all objects * @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/CCDataVisitor.cpp b/cocos/base/CCDataVisitor.cpp index a62b130cfa..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); } @@ -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; diff --git a/cocos/base/CCDataVisitor.h b/cocos/base/CCDataVisitor.h index ba8b83726f..9abb1f1424 100644 --- a/cocos/base/CCDataVisitor.h +++ b/cocos/base/CCDataVisitor.h @@ -36,7 +36,7 @@ class Integer; class Float; class Double; class String; -class Array; +class __Array; class Dictionary; class __Set; class Data; @@ -77,7 +77,7 @@ 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 Data *p); @@ -98,7 +98,7 @@ 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 Data *p); 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/CCString.h b/cocos/base/CCString.h index 09d558f827..19af0302e2 100644 --- a/cocos/base/CCString.h +++ b/cocos/base/CCString.h @@ -137,7 +137,7 @@ public: * @js NA * @lua NA */ - Array* componentsSeparatedByString(const char *delimiter); + __Array* componentsSeparatedByString(const char *delimiter); /* override functions * @js NA diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index d351444abd..7b78ee4664 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->getIndexOfObject(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() diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index bc72aff57b..58145b75d2 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -30,11 +30,8 @@ #include "CCObject.h" #include "CCGeometry.h" -#include "CCArray.h" - #include "CCPhysicsShape.h" - -#include +#include "CCVector.h" NS_CC_BEGIN class Sprite; @@ -103,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; @@ -305,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/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 41d6f08f9c..96a42c7797 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -97,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; @@ -176,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) @@ -201,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)); } @@ -392,16 +392,16 @@ 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; } @@ -562,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; @@ -606,7 +597,7 @@ void PhysicsWorld::addBody(PhysicsBody* body) } addBodyOrDelay(body); - _bodies->addObject(body); + _bodies.pushBack(body); body->_world = this; } @@ -627,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)); } @@ -637,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 @@ -663,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); @@ -722,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 diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 05999d990d..dfd85e5744 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -28,12 +28,12 @@ #include "ccConfig.h" #ifdef CC_USE_PHYSICS -#include -#include - +#include "CCVector.h" #include "CCObject.h" #include "CCGeometry.h" +#include + NS_CC_BEGIN class PhysicsBody; @@ -41,7 +41,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class Array; typedef Point Vect; @@ -104,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*/ @@ -156,7 +155,7 @@ protected: float _speed; PhysicsWorldInfo* _info; - Array* _bodies; + Vector _bodies; std::list _joints; Scene* _scene; @@ -165,8 +164,8 @@ protected: int _debugDrawMask; - Array* _delayAddBodies; - Array* _delayRemoveBodies; + Vector _delayAddBodies; + Vector _delayRemoveBodies; std::vector _delayAddJoints; std::vector _delayRemoveJoints; From a12a1015488f02c8f5852bae01adc916260dc379 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:17:47 +0800 Subject: [PATCH 085/107] issue #2790: Removes CCSorting.h/.cpp, uses Vector for storing used and freed cells. --- extensions/GUI/CCScrollView/CCSorting.cpp | 170 ------------------ extensions/GUI/CCScrollView/CCSorting.h | 114 ------------ extensions/GUI/CCScrollView/CCTableView.cpp | 164 +++++++++-------- extensions/GUI/CCScrollView/CCTableView.h | 28 +-- extensions/GUI/CCScrollView/CCTableViewCell.h | 6 +- 5 files changed, 105 insertions(+), 377 deletions(-) delete mode 100644 extensions/GUI/CCScrollView/CCSorting.cpp delete mode 100644 extensions/GUI/CCScrollView/CCSorting.h 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..55e1079196 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 "ExtensionMacros.h" NS_CC_EXT_BEGIN /** * Abstract class for SWTableView cell node */ -class TableViewCell: public Node, public SortableObject +class TableViewCell: public Node { public: TableViewCell() {} From 6f13a111ae6e3d96b4294a6f0f6af97a1c47b0db Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:18:42 +0800 Subject: [PATCH 086/107] issue #2790: Adds Vector::sort method, adds Vector::removeObject(object, toRemoved). --- cocos/base/CCVector.h | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 2314e325ba..3ea40ccc8a 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -230,13 +230,14 @@ public: } /** Remove a certain object */ - void removeObject(T 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); - object->release(); + if (toRelease) + object->release(); } /** Removes an element with a certain index */ @@ -341,6 +342,16 @@ public: }); } + 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 // ------------------------------------------ From d8061477c129ec89db59ba2705eccd241b252806 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:21:01 +0800 Subject: [PATCH 087/107] issue #2790: Removes CCSort.h/.cpp from projects. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- extensions/Android.mk | 1 - extensions/CMakeLists.txt | 1 - extensions/proj.win32/libExtensions.vcxproj | 2 -- extensions/proj.win32/libExtensions.vcxproj.filters | 6 ------ 5 files changed, 1 insertion(+), 11 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 8646685fa1..8f1be0f32e 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -c3b97117ff38c9347b34f01a67fd7206af29194d \ No newline at end of file +42f742346aec806886a8fd399aa42f689cafa71c \ No newline at end of file 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/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 From 0091ca2b6f5bc3acbd30305d189c797e4ecf2d4c Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:22:03 +0800 Subject: [PATCH 088/107] issue #2790: Uses non-const ValueMap for simplifying codes in CCAnimationCache.cpp. --- cocos/2d/CCAnimationCache.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index a1d0ddd1ec..2c528f0320 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -141,12 +141,12 @@ void AnimationCache::parseVersion2(const ValueMap& animations) for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter) { std::string name = iter->first; - const ValueMap& animationDict = iter->second.asValueMap(); + ValueMap& animationDict = const_cast(iter->second.asValueMap()); - const Value& loops = animationDict.at("loops"); - bool restoreOriginalFrame = animationDict.at("restoreOriginalFrame").asBool(); + const Value& loops = animationDict["loops"]; + bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].asBool(); - const ValueVector& frameArray = animationDict.at("frames").asValueVector(); + ValueVector& frameArray = animationDict["frames"].asValueVector(); if ( frameArray.empty() ) { @@ -159,8 +159,8 @@ void AnimationCache::parseVersion2(const ValueMap& animations) for (auto& obj : frameArray) { - const ValueMap& entry = obj.asValueMap(); - std::string spriteFrameName = entry.at("spriteframe").asString(); + ValueMap& entry = obj.asValueMap(); + std::string spriteFrameName = entry["spriteframe"].asString(); SpriteFrame *spriteFrame = frameCache->getSpriteFrameByName(spriteFrameName); if( ! spriteFrame ) { @@ -169,15 +169,15 @@ void AnimationCache::parseVersion2(const ValueMap& animations) continue; } - float delayUnits = entry.at("delayUnits").asFloat(); - const Value& userInfo = entry.at("notification"); + float delayUnits = entry["delayUnits"].asFloat(); + Value& userInfo = entry["notification"]; AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asValueMap()); array.pushBack(animFrame); } - float delayPerUnit = animationDict.at("delayPerUnit").asFloat(); + float delayPerUnit = animationDict["delayPerUnit"].asFloat(); Animation *animation = Animation::create(array, delayPerUnit, loops.getType() != Value::Type::NONE ? loops.asInt() : 1); animation->setRestoreOriginalFrame(restoreOriginalFrame); From b0cb7c230a8347ab94e2dc424ff420af6e6fae22 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:22:51 +0800 Subject: [PATCH 089/107] #issue #2790: Uses Vector for scenesStack in CCDirector. --- cocos/2d/CCDirector.cpp | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index bce116b491..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(); From cd7281338945725c9edba968b7c9508b16733d10 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:23:29 +0800 Subject: [PATCH 090/107] issue #2790: Autorelease pool is using Vector now. --- cocos/base/CCAutoreleasePool.cpp | 64 ++++++++++++-------------------- cocos/base/CCAutoreleasePool.h | 6 +-- 2 files changed, 27 insertions(+), 43 deletions(-) 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(); From d7997cf0cc450621bc61b92e579edecffa446430 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:24:31 +0800 Subject: [PATCH 091/107] issue #2790: Updates MenuItemToggole --- cocos/2d/CCMenuItem.cpp | 20 ++++---------------- cocos/2d/CCMenuItem.h | 23 ++++++++++++----------- 2 files changed, 16 insertions(+), 27 deletions(-) diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index c97cd7a2fa..f4709c5156 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -806,33 +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); - - for (int z=0; z < menuItems->count(); z++) - { - MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems.pushBack(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); - - for (int z=0; z < menuItems->count(); z++) - { - MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems.pushBack(menuItem); - } - + ret->_subItems = menuItems; ret->_selectedIndex = UINT_MAX; ret->setSelectedIndex(0); return ret; diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index c9184feba6..57ce4dad9e 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -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 */ @@ -496,16 +507,6 @@ 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 */ From 6b0589679b295549f409c40f84e28ec296086e53 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:25:24 +0800 Subject: [PATCH 092/107] issue #2790: Vector instead of CCArray* in CCScheduler --- cocos/2d/CCScheduler.cpp | 27 +++++++++------------------ cocos/2d/CCScheduler.h | 3 ++- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index f1b1c9e59c..a617a4b693 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -256,7 +256,7 @@ 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); @@ -265,7 +265,6 @@ Scheduler::Scheduler(void) Scheduler::~Scheduler(void) { unscheduleAll(); - CC_SAFE_RELEASE(_scriptHandlerEntries); } void Scheduler::removeHashElement(_hashSelectorEntry *element) @@ -630,10 +629,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) } } - if (_scriptHandlerEntries) - { - _scriptHandlerEntries->removeAllObjects(); - } + _scriptHandlerEntries.clear(); } void Scheduler::unscheduleAllForTarget(Object *target) @@ -675,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(); @@ -951,14 +942,14 @@ void Scheduler::update(float dt) // // Iterate over all the script callbacks - if (_scriptHandlerEntries) + if (!_scriptHandlerEntries.empty()) { - for (auto i = _scriptHandlerEntries->count() - 1; i >= 0; i--) + for (auto i = _scriptHandlerEntries.size() - 1; i >= 0; i--) { - SchedulerScriptHandlerEntry* eachEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + SchedulerScriptHandlerEntry* eachEntry = _scriptHandlerEntries.at(i); if (eachEntry->isMarkedForDeletion()) { - _scriptHandlerEntries->removeObjectAtIndex(i); + _scriptHandlerEntries.remove(i); } else if (!eachEntry->isPaused()) { diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 247b773d00..3146729205 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -107,6 +107,7 @@ protected: struct _listEntry; struct _hashSelectorEntry; struct _hashUpdateEntry; +class SchedulerScriptHandlerEntry; /** @brief Scheduler is responsible for triggering the scheduled callbacks. You should not use NSTimer. Instead use this class. @@ -290,7 +291,7 @@ 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; From 06e6d38ab09f534b43ce38d04b9c4cc76163c1e5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:26:17 +0800 Subject: [PATCH 093/107] issue #2790: Initializes Value when empty constructor was invoked. --- cocos/base/CCValue.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 41f18db6b3..fa6e457425 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -28,9 +28,9 @@ NS_CC_BEGIN Value::Value() -: _vectorData(nullptr) -, _mapData(nullptr) -, _intKeyMapData(nullptr) +: _vectorData(new ValueVector()) +, _mapData(new ValueMap()) +, _intKeyMapData(new IntValueMap()) , _type(Type::NONE) { From 365f6faabbb3b94be7e1d383c79242d0de89e35e Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:26:52 +0800 Subject: [PATCH 094/107] issue #2790: Warning fixes for CCDictionary.cpp and CCString.cpp --- cocos/base/CCDictionary.cpp | 30 +++++++++++++++--------------- cocos/base/CCString.cpp | 4 ++-- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index de9abbb31f..ceb0333823 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -88,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) @@ -101,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); } } @@ -110,19 +110,19 @@ Array* Dictionary::allKeys() HASH_ITER(hh, _elements, pElement, tmp) { Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); - pArray->addObject(pOneKey); + 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; @@ -133,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); } } @@ -145,12 +145,12 @@ Array* Dictionary::allKeysForObject(Object* object) if (object == pElement->_object) { Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } } - return pArray; + return array; } Object* Dictionary::objectForKey(const std::string& key) @@ -303,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()); @@ -378,7 +378,7 @@ Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) return srcDict->clone(); } -static Array* visitArray(const ValueVector& array); +static __Array* visitArray(const ValueVector& array); static Dictionary* visitDict(const ValueMap& dict) { @@ -411,9 +411,9 @@ static Dictionary* visitDict(const ValueMap& dict) return ret; } -static Array* visitArray(const ValueVector& array) +static __Array* visitArray(const ValueVector& array) { - Array* ret = new Array(); + __Array* ret = new __Array(); ret->init(); std::for_each(array.begin(), array.end(), [&ret](const Value& value){ diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index c2a6ec6bd1..97e1261f48 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -178,9 +178,9 @@ 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(); size_t cutAt; while( (cutAt = _string.find_first_of(delimiter)) != _string.npos ) From 16cd61f024176f4c338237bce7cc31b88e9007aa Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:28:14 +0800 Subject: [PATCH 095/107] issue #2790: Vector for physics and remove lots of unneeded dynamic_cast. --- cocos/physics/CCPhysicsBody.cpp | 18 +++++++++--------- cocos/physics/CCPhysicsWorld.cpp | 30 +++++++++++------------------- 2 files changed, 20 insertions(+), 28 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 7b78ee4664..69a197b9b7 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -652,7 +652,7 @@ void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = true*/) { - if (_shapes->getIndexOfObject(shape) != -1) + if (_shapes.getIndex(shape) != -1) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -751,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); } } @@ -761,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); } } @@ -771,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/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 96a42c7797..4d3f5066ac 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -933,7 +933,7 @@ void PhysicsWorld::doRemoveBody(PhysicsBody* body) } // remove shaps - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { removeShape(dynamic_cast(shape)); } @@ -949,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) @@ -970,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; } } @@ -990,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()) { @@ -1016,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); } @@ -1036,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) { } @@ -1051,8 +1045,6 @@ PhysicsWorld::~PhysicsWorld() { removeAllJoints(true); removeAllBodies(); - CC_SAFE_RELEASE(_delayRemoveBodies); - CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); CC_SAFE_DELETE(_debugDraw); } From ba56bf6ecdd71881292be5b734e08de5d65249f7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:28:37 +0800 Subject: [PATCH 096/107] issue #2790: Updates Tests. --- .../Classes/ActionsTest/ActionsTest.cpp | 6 ++---- .../TestCpp/Classes/ActionsTest/ActionsTest.h | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 11 +++++------ .../Classes/SchedulerTest/SchedulerTest.cpp | 18 +++++++----------- .../Classes/SchedulerTest/SchedulerTest.h | 4 ++-- 5 files changed, 17 insertions(+), 24 deletions(-) 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/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 867f58f98e..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() 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 From 713d89b6d80e420383d9415f65dc44a03513755d Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:36:07 +0800 Subject: [PATCH 097/107] issue #2790: Uses Vector instead of CCArray* for CCControl. Uses std::unordered_map*> instead of CCDictionary*. --- .../GUI/CCControlExtension/CCControl.cpp | 83 ++++++++++--------- extensions/GUI/CCControlExtension/CCControl.h | 5 +- 2 files changed, 44 insertions(+), 44 deletions(-) diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 4b3edfa1f9..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); + } + }); } } @@ -254,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; From be7c62a2b97c16ae58b7490adfc248fcc010b07c Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:44:21 +0800 Subject: [PATCH 098/107] issue #2790: Removes unused CCSet binding glue codes. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 46cb2c9d29..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 @@ -cd3a15ee39c63c93b40e323eda6fa43f584742aa \ No newline at end of file +7a245db1098d7ced5947aca62f43e67f06d1492d \ No newline at end of file From f1fac73bb48fe5b166275be143bc500e446a3d36 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 16:14:00 +0800 Subject: [PATCH 099/107] issue #2790: Fix wrong include. --- extensions/GUI/CCScrollView/CCTableViewCell.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 55e1079196..96ab28d67d 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -27,7 +27,7 @@ #define __CCTABLEVIEWCELL_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN From beb6bb6c8d2df55e846ffd440929213ca80f1ae4 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 16:14:22 +0800 Subject: [PATCH 100/107] issue #2790: Bug fix in CCMap.h --- cocos/base/CCMap.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 8630dff9f3..d62e72dbea 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -225,12 +225,14 @@ public: clear(); _data = other._data; addRefForAllObjects(); + return *this; } Map& operator= ( Map&& other ) { CCLOG("In the move assignment operator of Map!"); _data = std::move(other._data); + return *this; } protected: @@ -239,7 +241,7 @@ protected: { for (auto iter = _data.begin(); iter != _data.end(); ++iter) { - _data->second->retain(); + iter->second->retain(); } } From 908f5ed51562f801ec14d312a88c4734c28312a5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 16:38:50 +0800 Subject: [PATCH 101/107] issue #2790: Fix for TMXObjectGroup::getObject. --- cocos/2d/CCTMXObjectGroup.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index 672dc0509f..3cc08a0473 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -44,14 +44,15 @@ TMXObjectGroup::~TMXObjectGroup() ValueMap TMXObjectGroup::getObject(const std::string& objectName) const { - if (_objects.size() > 0) + if (!_objects.empty()) { - for (auto& v : _objects) + for (const auto& v : _objects) { - ValueMap dict = v.asValueMap(); - if (dict["name"].asString() == objectName) + const ValueMap& dict = v.asValueMap(); + if (dict.find("name") != dict.end()) { - return dict; + if (dict.at("name").asString() == objectName) + return dict; } } } From abbcd45c589d797ded9224ccb3e4ac3852400423 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 23:32:29 +0800 Subject: [PATCH 102/107] =?UTF-8?q?issue=20#2790:=20CCLOG=20=E2=80=94>=20C?= =?UTF-8?q?CLOGINFO=20in=20CCMap.h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCMap.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index d62e72dbea..df39fc80d0 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -221,7 +221,7 @@ public: Map& operator= ( const Map& other ) { - CCLOG("In the copy assignment operator of Map!"); + CCLOGINFO("In the copy assignment operator of Map!"); clear(); _data = other._data; addRefForAllObjects(); @@ -230,7 +230,7 @@ public: Map& operator= ( Map&& other ) { - CCLOG("In the move assignment operator of Map!"); + CCLOGINFO("In the move assignment operator of Map!"); _data = std::move(other._data); return *this; } From 45cb79c5f42f9b7192cc41c5150761b194b743fa Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 8 Dec 2013 22:10:14 +0800 Subject: [PATCH 103/107] issue #2790: Updates bindings-generator. Fixes issue at https://github.com/cocos2d/bindings-generator/pull/53 .Matches typedef name firstly in conversion.yaml. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index eb2bc8934b..53cfcb95f4 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit eb2bc8934b01f6cdc7661648f883e2e6374a5cf7 +Subproject commit 53cfcb95f4d06af5f484eeda77c9eb5e8b835ec9 From e07f2bdddd32ee57264543535dbdc81cd0d170a8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 8 Dec 2013 22:17:54 +0800 Subject: [PATCH 104/107] issue #2790: Vector and Map for CCBReader. Not finished yet. --- .../cocosbuilder/CCBAnimationManager.cpp | 32 +-- .../editor-support/cocosbuilder/CCBReader.cpp | 189 ++++++++---------- cocos/editor-support/cocosbuilder/CCBReader.h | 32 +-- .../cocosbuilder/CCBSequenceProperty.cpp | 6 +- .../cocosbuilder/CCBSequenceProperty.h | 4 +- .../cocosbuilder/CCNodeLoader.cpp | 30 ++- 6 files changed, 128 insertions(+), 165 deletions(-) diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index 3229c12582..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); } } @@ -621,13 +621,13 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann float lastKeyframeTime = 0; Vector actions; - Array *keyframes = channel->getKeyframes(); - long numKeyframes = keyframes->count(); + 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) { @@ -700,12 +700,12 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) float lastKeyframeTime = 0; Vector actions; - Array *keyframes = channel->getKeyframes(); - long numKeyframes = keyframes->count(); + 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) { @@ -741,15 +741,15 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration) { - Array *keyframes = pSeqProp->getKeyframes(); - long numKeyframes = keyframes->count(); + auto& keyframes = pSeqProp->getKeyframes(); + int numKeyframes = keyframes.size(); if (numKeyframes > 1) { // Make an animation! Vector actions; - CCBKeyframe *keyframeFirst = (CCBKeyframe*)keyframes->getObjectAtIndex(0); + CCBKeyframe *keyframeFirst = keyframes.at(0); float timeFirst = keyframeFirst->getTime() + fTweenDuration; if (timeFirst > 0) @@ -759,8 +759,8 @@ void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, 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) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 1f778248f2..5f0cd809ee 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,6 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & _actionManager->setRootContainerSize(parentSize); _actionManager->_owner = _owner; - Dictionary* animationManagers = Dictionary::create(); Node *pNodeGraph = readFileWithCleanUp(true, animationManagers); if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1) @@ -280,25 +254,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 +273,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) @@ -333,28 +299,28 @@ void CCBReader::cleanUpNodeGraph(Node *node) }); } -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) { @@ -377,7 +343,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; } @@ -567,7 +533,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); @@ -611,7 +577,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()); @@ -628,7 +594,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) { @@ -645,7 +611,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) _actionManager->moveAnimationsFromNode(ccbFileNode, embeddedNode); - ccbFileNode->setCCBFileNode(NULL); + ccbFileNode->setCCBFileNode(nullptr); node = embeddedNode; } @@ -661,7 +627,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { if(!_jsControlled) { - Object * target = NULL; + Object * target = nullptr; if(memberVarAssignmentType == TargetType::DOCUMENT_ROOT) { target = _actionManager->getRootNode(); @@ -671,19 +637,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); } @@ -700,7 +666,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) else { _ownerOutletNames.push_back(memberVarAssignmentName); - _ownerOutletNodes->addObject(node); + _ownerOutletNodes.pushBack(node); } } } @@ -713,10 +679,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; @@ -724,7 +690,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())); } @@ -737,7 +703,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); @@ -754,11 +720,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); } @@ -775,7 +741,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 @@ -818,7 +784,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) value = Array::create(CCBValue::create(a), CCBValue::create(b), - NULL); + nullptr); } else if (type == PropertyType::SPRITEFRAME) { @@ -889,7 +855,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); @@ -922,7 +888,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(); } @@ -933,7 +899,7 @@ bool CCBReader::readSoundKeyframesForSeq(CCBSequence* seq) { Node * CCBReader::readNodeGraph() { - return this->readNodeGraph(NULL); + return this->readNodeGraph(nullptr); } bool CCBReader::readSequences() @@ -1008,12 +974,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) @@ -1031,50 +997,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; } @@ -1086,10 +1055,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)); } } } From 13111c2cd971a7881686cd3283f7cd1e814d80cd Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 9 Dec 2013 09:54:04 +0800 Subject: [PATCH 105/107] issue #2790: Error fix in CCBReader. --- cocos/editor-support/cocosbuilder/CCBReader.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 5f0cd809ee..2ab5ca1c79 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -245,6 +245,7 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & _actionManager->setRootContainerSize(parentSize); _actionManager->_owner = _owner; + Map animationManagers; Node *pNodeGraph = readFileWithCleanUp(true, animationManagers); if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1) From a2e90f1fca70bda19c791d2b207e9cc4b9cb1f8a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 9 Dec 2013 10:54:22 +0800 Subject: [PATCH 106/107] issue #2790: Small fixes for physics, uses reference and std::move. --- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 58145b75d2..8d31d82e61 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -100,7 +100,7 @@ public: /* remove all shapes */ void removeAllShapes(bool reduceMassAndMoment = true); /* get the body shapes. */ - inline const Vector 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.size() >= 1 ? _shapes.at(0) : nullptr; } /* get the shape of the body. */ diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 4d3f5066ac..da07a5590b 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -403,7 +403,7 @@ Vector PhysicsWorld::getShapes(const Point& point) const (cpSpaceNearestPointQueryFunc)PhysicsWorldCallback::getShapesAtPointFunc, &arr); - return arr; + return std::move(arr); } PhysicsShape* PhysicsWorld::getShape(const Point& point) const From b2e796613773e918718bba7442592e39c22d5196 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 9 Dec 2013 03:53:01 +0000 Subject: [PATCH 107/107] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index db718e871a..4001693a86 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit db718e871a7b59acdbefb679796c824d7a2b3ebf +Subproject commit 4001693a86e1887ab2a9036aa678ad3b14b2f1b2