diff --git a/AUTHORS b/AUTHORS index 0a7ef1b315..4281304da3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -669,6 +669,25 @@ Developers: zhiqiangxu Fixed a logic error in ControlUtils::RectUnion. + yinkaile (2youyouo2) + Maintainer of Armature Bone Animation. + + dmurtagh + Fixed a bug that UserDefault::getDoubleForKey() doesn't pass default value to Java. + + seobyeongky + Updates spine runtime. + Fixed a potential bug in Data's copy constructor. + + luocker + Fix a bug that string itself is also modified in `String::componentsSeparatedByString`. + + omersaeed + Fix a bug that game will crash if connection breaks during download using AssetManager. + + SBKarr + AngelCode binary file format support for LabelBMFont. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, diff --git a/CHANGELOG b/CHANGELOG index 74875880c0..a15a536827 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,13 +4,33 @@ cocos2d-x-3.0beta0 ?? 2013 [NEW] SChedule::performFunctionInCocosThread() [NEW] Added tga format support again. [FIX] A Logic error in ControlUtils::RectUnion. + [FIX] Bug fixes for Armature, use Vector, Map instead of Array, Dictionary. + [FIX] Used c++11 range loop(highest performance) instead of other types of loop. + [FIX] Removed most hungarian notations. + [FIX] Merged NodeRGBA to Node. + [NEW] New renderer support. + [FIX] Potential hash collision fix. + [FIX] Updates spine runtime to the latest version. + [FIX] Uses `const std::string&` instead of `const char*`. + [FIX] LabelBMFont string can't be shown integrally. + [FIX] Deprecates FileUtils::getFileData, adds FileUtils::getStringFromFile/getDataFromFile. + [FIX] GUI refactoring: Removes UI prefix, Widget is inherited from Node, uses new containers(Vector, Map). + [FIX] String itself is also modified in `String::componentsSeparatedByString`. + [FIX] Sprites with PhysicsBody move to a wrong position when game resume from background. + [FIX] Crash if connection breaks during download using AssetManager. + [NEW] AngelCode binary file format support for LabelBMFont. [Android] [NEW] build/android-build.sh: add supporting to generate .apk file [FIX] XMLHttpRequest receives wrong binary array. [NEW] Bindings-generator supports to bind 'unsigned long'. [FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes. + [FIX] UserDefault::getDoubleForKey() doesn't pass default value to Java. [Windows] [NEW] CMake support for windows. +[Bindings] + [FIX] Don't bind override functions for JSB and LuaBining since they aren't needed at all. + [NEW] Adds spine JS binding support. + [FIX] The order of onEnter and onExit is wrong. cocos2d-x-3.0alpha1 Nov.19 2013 [all platforms] diff --git a/CMakeLists.txt b/CMakeLists.txt index c68536b314..55d599f781 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -143,6 +143,7 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/cocos ${CMAKE_CURRENT_SOURCE_DIR}/cocos/audio/include ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d + ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/renderer ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform ${CMAKE_CURRENT_SOURCE_DIR}/cocos/base ${CMAKE_CURRENT_SOURCE_DIR}/cocos/physics @@ -152,6 +153,7 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/external ${CMAKE_CURRENT_SOURCE_DIR}/external/tinyxml2 ${CMAKE_CURRENT_SOURCE_DIR}/external/unzip + ${CMAKE_CURRENT_SOURCE_DIR}/external/edtaa3func ${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER} @@ -267,8 +269,6 @@ endif(BUILD_EDITOR_COCOSBUILDER) if(BUILD_EDITOR_COCOSTUDIO) # cocostudio add_subdirectory(cocos/editor-support/cocostudio) -# jsoncpp library, cocostuido depends on jsoncpp -add_subdirectory(external/json) endif(BUILD_EDITOR_COCOSTUDIO) if(BUILD_LIBS_LUA) diff --git a/build/android-build.py b/build/android-build.py index 77189ee5f9..3285c690e9 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -12,18 +12,6 @@ LUA_SAMPLES = ['hellolua', 'testlua'] JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES - -def usage(): - - print """%s [-n ndk-build-parameter] [-p android-platform] [-b build-mode] target. - -Valid android-platform are:[10|11|12|13|14|15|16|17] -Valid build-mode are:[debug|release] -Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon - |crystalcraze|moonwarriors|testjavascript|watermelonwithme] - -You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" % sys.argv[0] - def check_environment_variables(): ''' Checking the environment NDK_ROOT, which will be used for building ''' @@ -253,14 +241,23 @@ def build_samples(target,ndk_build_param,android_platform,build_mode): if __name__ == '__main__': #parse the params - parser = OptionParser() - parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build') - parser.add_option("-p", "--platform", dest="android_platform", help='parameter for android-update') - parser.add_option("-b", "--build", dest="build_mode", help='the build mode for java project,debug or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html') + usage = """usage: %prog [options] target + + Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon|crystalcraze|moonwarriors|testjavascript|watermelonwithme] + + You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" + + parser = OptionParser(usage=usage) + parser.add_option("-n", "--ndk", dest="ndk_build_param", + help='parameter for ndk-build') + parser.add_option("-p", "--platform", dest="android_platform", + help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]') + parser.add_option("-b", "--build", dest="build_mode", + help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html') (opts, args) = parser.parse_args() if len(args) == 0: - usage() + parser.print_help() else: try: build_samples(args, opts.ndk_build_param,opts.android_platform,opts.build_mode) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b054635826..a237fdc780 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -77ef9ee3921db604edd06a2cc0b9f9a89259a431 \ No newline at end of file +812ab716d10a52b752f0d15b2393b2b0a7c8e969 \ 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 81e2a64b39..2d497c5e0b 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -133130a8ae8d6597399a7de05ba9b63ee55f5e2d \ No newline at end of file +b83c3a0fd60d6b1b1a032495615afd77fccd5050 \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 789cae2d91..4905f4d613 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -24,7 +24,6 @@ CCActionTween.cpp \ CCAnimation.cpp \ CCAnimationCache.cpp \ CCAtlasNode.cpp \ -CCCamera.cpp \ ccCArray.cpp \ CCClippingNode.cpp \ CCComponent.cpp \ @@ -60,6 +59,7 @@ CCGLProgram.cpp \ ccGLStateCache.cpp \ CCGrabber.cpp \ CCGrid.cpp \ +CCNodeGrid.cpp \ CCIMEDispatcher.cpp \ CCLabel.cpp \ CCLabelAtlas.cpp \ @@ -117,10 +117,19 @@ platform/CCEGLViewProtocol.cpp \ platform/CCFileUtils.cpp \ platform/CCSAXParser.cpp \ platform/CCThread.cpp \ +renderer/CCCustomCommand.cpp \ +renderer/CCFrustum.cpp \ +renderer/CCGroupCommand.cpp \ +renderer/CCMaterialManager.cpp \ +renderer/CCQuadCommand.cpp \ +renderer/CCRenderCommand.cpp \ +renderer/CCRenderer.cpp \ +renderer/CCRenderMaterial.cpp \ ../base/atitc.cpp \ ../base/CCAffineTransform.cpp \ ../base/CCArray.cpp \ ../base/CCAutoreleasePool.cpp \ +../base/CCConsole.cpp \ ../base/CCData.cpp \ ../base/CCDataVisitor.cpp \ ../base/CCDictionary.cpp \ @@ -132,7 +141,6 @@ platform/CCThread.cpp \ ../base/CCValue.cpp \ ../base/etc1.cpp \ ../base/s3tc.cpp \ -../base/CCConsole.cpp \ ../math/kazmath/src/aabb.c \ ../math/kazmath/src/mat3.c \ ../math/kazmath/src/mat4.c \ @@ -158,10 +166,12 @@ platform/CCThread.cpp \ ../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../../external/tinyxml2/tinyxml2.cpp \ ../../external/unzip/ioapi.cpp \ -../../external/unzip/unzip.cpp +../../external/unzip/unzip.cpp \ +../../external/edtaa3func/edtaa3func.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/renderer \ $(LOCAL_PATH)/../math/kazmath/include \ platform/android \ $(LOCAL_PATH)/../physics \ @@ -171,13 +181,15 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/renderer \ $(LOCAL_PATH)/../math/kazmath/include \ $(LOCAL_PATH)/platform/android \ $(LOCAL_PATH)/../physics \ $(LOCAL_PATH)/../base \ $(LOCAL_PATH)/../../external/tinyxml2 \ $(LOCAL_PATH)/../../external/unzip \ - $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk + $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk \ + $(LOCAL_PATH)/../../external/edtaa3func LOCAL_LDLIBS := -lGLESv2 \ @@ -193,6 +205,7 @@ LOCAL_EXPORT_LDLIBS := -lGLESv2 \ LOCAL_WHOLE_STATIC_LIBRARIES := cocos_freetype2_static LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static +LOCAL_WHOLE_STATIC_LIBRARIES += spine_static # define the macro to compile through support/zip_support/ioapi.c LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API @@ -205,3 +218,4 @@ include $(BUILD_STATIC_LIBRARY) $(call import-module,freetype2/prebuilt/android) $(call import-module,chipmunk) $(call import-module,2d/platform/android) +$(call import-module,editor-support/spine) diff --git a/cocos/2d/CCActionCamera.cpp b/cocos/2d/CCActionCamera.cpp index e913558973..0d8ef23606 100644 --- a/cocos/2d/CCActionCamera.cpp +++ b/cocos/2d/CCActionCamera.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. @@ -26,7 +26,6 @@ THE SOFTWARE. #include "CCActionCamera.h" #include "CCNode.h" -#include "CCCamera.h" #include "CCStdC.h" NS_CC_BEGIN @@ -36,11 +35,6 @@ NS_CC_BEGIN void ActionCamera::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); - - Camera *camera = target->getCamera(); - camera->getCenter(&_centerXOrig, &_centerYOrig, &_centerZOrig); - camera->getEye(&_eyeXOrig, &_eyeYOrig, &_eyeZOrig); - camera->getUp(&_upXOrig, &_upYOrig, &_upZOrig); } ActionCamera* ActionCamera::clone() const @@ -56,6 +50,88 @@ ActionCamera * ActionCamera::reverse() const // FIXME: This conversion isn't safe. return (ActionCamera*)ReverseTime::create(const_cast(this)); } + +void ActionCamera::restore() +{ + _eyeX = _eyeY = 0.0f; + _eyeZ = FLT_EPSILON; + + _centerX = _centerY = _centerZ = 0.0f; + + _upX = 0.0f; + _upY = 1.0f; + _upZ = 0.0f; +} + +void ActionCamera::setEye(float x, float y, float z) +{ + _eyeX = x; + _eyeY = y; + _eyeZ = z; + + updateTransform(); +} + +void ActionCamera::setCenter(float centerX, float centerY, float centerZ) +{ + _centerX = centerX; + _centerY = centerY; + _centerZ = centerZ; + + updateTransform(); +} + +void ActionCamera::setUp(float upX, float upY, float upZ) +{ + _upX = upX; + _upY = upY; + _upZ = upZ; + + updateTransform(); +} + +void ActionCamera::updateTransform() +{ + kmVec3 eye, center, up; + + kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ); + kmVec3Fill(¢er, _centerX, _centerY, _centerZ); + kmVec3Fill(&up, _upX, _upY, _upZ); + + kmMat4 lookupMatrix; + kmMat4LookAt(&lookupMatrix, &eye, ¢er, &up); + + Point anchorPoint = _target->getAnchorPointInPoints(); + + bool needsTranslation = !anchorPoint.equals(Point::ZERO); + + kmMat4 mv; + kmMat4Identity(&mv); + + if(needsTranslation) { + kmMat4 t; + kmMat4Translation(&t, anchorPoint.x, anchorPoint.y, 0); + kmMat4Multiply(&mv, &mv, &t); + } + + kmMat4Multiply(&mv, &mv, &lookupMatrix); + + if(needsTranslation) { + kmMat4 t; + kmMat4Translation(&t, -anchorPoint.x, -anchorPoint.y, 0); + kmMat4Multiply(&mv, &mv, &t); + } + + // XXX FIXME TODO + // Using the AdditionalTransform is a complete hack. + // This should be done by multipliying the lookup-Matrix with the Node's MV matrix + // And then setting the result as the new MV matrix + // But that operation needs to be done after all the 'updates'. + // So the Director should emit an 'director_after_update' event. + // And this object should listen to it + _target->setAdditionalTransform(mv); +} + // // OrbitCamera // @@ -69,7 +145,7 @@ OrbitCamera * OrbitCamera::create(float t, float radius, float deltaRadius, floa return obitCamera; } CC_SAFE_DELETE(obitCamera); - return NULL; + return nullptr; } OrbitCamera* OrbitCamera::clone() const @@ -101,7 +177,8 @@ bool OrbitCamera::initWithDuration(float t, float radius, float deltaRadius, flo void OrbitCamera::startWithTarget(Node *target) { - ActionInterval::startWithTarget(target); + ActionCamera::startWithTarget(target); + float r, zenith, azimuth; this->sphericalRadius(&r, &zenith, &azimuth); if( isnan(_radius) ) @@ -117,30 +194,25 @@ void OrbitCamera::startWithTarget(Node *target) void OrbitCamera::update(float dt) { - float r = (_radius + _deltaRadius * dt) * Camera::getZEye(); + float r = (_radius + _deltaRadius * dt) * FLT_EPSILON; float za = _radZ + _radDeltaZ * dt; float xa = _radX + _radDeltaX * dt; - float i = sinf(za) * cosf(xa) * r + _centerXOrig; - float j = sinf(za) * sinf(xa) * r + _centerYOrig; - float k = cosf(za) * r + _centerZOrig; + float i = sinf(za) * cosf(xa) * r + _centerX; + float j = sinf(za) * sinf(xa) * r + _centerY; + float k = cosf(za) * r + _centerZ; - _target->getCamera()->setEye(i,j,k); + setEye(i,j,k); } void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimuth) { - float ex, ey, ez, cx, cy, cz, x, y, z; float r; // radius float s; - Camera* camera = _target->getCamera(); - camera->getEye(&ex, &ey, &ez); - camera->getCenter(&cx, &cy, &cz); - - x = ex-cx; - y = ey-cy; - z = ez-cz; + float x = _eyeX - _centerX; + float y = _eyeY - _centerY; + float z = _eyeZ - _centerZ; r = sqrtf( powf(x,2) + powf(y,2) + powf(z,2)); s = sqrtf( powf(x,2) + powf(y,2)); @@ -155,7 +227,7 @@ void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimut else *azimuth = asinf(y/s); - *newRadius = r / Camera::getZEye(); + *newRadius = r / FLT_EPSILON; } NS_CC_END diff --git a/cocos/2d/CCActionCamera.h b/cocos/2d/CCActionCamera.h index 3b794b5073..c4cab0c0a1 100644 --- a/cocos/2d/CCActionCamera.h +++ b/cocos/2d/CCActionCamera.h @@ -27,6 +27,7 @@ THE SOFTWARE. #define __CCCAMERA_ACTION_H__ #include "CCActionInterval.h" +#include "kazmath/kazmath.h" NS_CC_BEGIN @@ -48,15 +49,15 @@ public: * @js ctor */ ActionCamera() - :_centerXOrig(0) - ,_centerYOrig(0) - ,_centerZOrig(0) - ,_eyeXOrig(0) - ,_eyeYOrig(0) - ,_eyeZOrig(0) - ,_upXOrig(0) - ,_upYOrig(0) - ,_upZOrig(0) + :_centerX(0) + ,_centerY(0) + ,_centerZ(0) + ,_eyeX(0) + ,_eyeY(0) + ,_eyeZ(FLT_EPSILON) + ,_upX(0) + ,_upY(1) + ,_upZ(0) {} /** * @js NA @@ -70,17 +71,22 @@ public: virtual ActionCamera *clone() const override; protected: - float _centerXOrig; - float _centerYOrig; - float _centerZOrig; - float _eyeXOrig; - float _eyeYOrig; - float _eyeZOrig; + void restore(); + void setEye(float x, float y, float z); + void setCenter(float x, float y, float z); + void setUp(float x, float y, float z); + void updateTransform(); - float _upXOrig; - float _upYOrig; - float _upZOrig; + float _centerX; + float _centerY; + float _centerZ; + float _eyeX; + float _eyeY; + float _eyeZ; + float _upX; + float _upY; + float _upZ; }; /** @@ -112,7 +118,7 @@ public: * @js NA * @lua NA */ - ~OrbitCamera(){} + virtual ~OrbitCamera(){} /** initializes a OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */ bool initWithDuration(float t, float radius, float deltaRadius, float angleZ, float deltaAngleZ, float angleX, float deltaAngleX); diff --git a/cocos/2d/CCActionCatmullRom.cpp b/cocos/2d/CCActionCatmullRom.cpp index bab094f288..0437eb90bf 100644 --- a/cocos/2d/CCActionCatmullRom.cpp +++ b/cocos/2d/CCActionCatmullRom.cpp @@ -43,7 +43,7 @@ NS_CC_BEGIN; * Implementation of PointArray */ -PointArray* PointArray::create(int capacity) +PointArray* PointArray::create(ssize_t capacity) { PointArray* pointArray = new PointArray(); if (pointArray) @@ -63,7 +63,7 @@ PointArray* PointArray::create(int capacity) } -bool PointArray::initWithCapacity(int capacity) +bool PointArray::initWithCapacity(ssize_t 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, int index) +void PointArray::insertControlPoint(Point &controlPoint, ssize_t index) { Point *temp = new Point(controlPoint.x, controlPoint.y); _controlPoints->insert(_controlPoints->begin() + index, temp); } -Point PointArray::getControlPointAtIndex(int index) +Point PointArray::getControlPointAtIndex(ssize_t index) { index = static_cast(MIN(_controlPoints->size()-1, MAX(index, 0))); return *(_controlPoints->at(index)); } -void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index) +void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, ssize_t index) { Point *temp = _controlPoints->at(index); @@ -146,17 +146,17 @@ void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index) temp->y = controlPoint.y; } -void PointArray::removeControlPointAtIndex(int index) +void PointArray::removeControlPointAtIndex(ssize_t index) { vector::iterator iter = _controlPoints->begin() + index; - Point* pRemovedPoint = *iter; + Point* removedPoint = *iter; _controlPoints->erase(iter); - delete pRemovedPoint; + delete removedPoint; } -int PointArray::count() const +ssize_t PointArray::count() const { - return static_cast(_controlPoints->size()); + return _controlPoints->size(); } PointArray* PointArray::reverse() const @@ -177,11 +177,11 @@ PointArray* PointArray::reverse() const void PointArray::reverseInline() { - auto l = _controlPoints->size(); + size_t l = _controlPoints->size(); Point *p1 = nullptr; Point *p2 = nullptr; - int x, y; - for (int i = 0; i < l/2; ++i) + float x, y; + for (size_t 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) { - int p; + ssize_t p; float lt; // eg. @@ -383,7 +383,7 @@ CardinalSplineBy* CardinalSplineBy::reverse() const // convert "absolutes" to "diffs" // Point p = copyConfig->getControlPointAtIndex(0); - for (unsigned int i = 1; i < copyConfig->count(); ++i) + for (ssize_t i = 1; i < copyConfig->count(); ++i) { Point current = copyConfig->getControlPointAtIndex(i); Point diff = current - p; @@ -405,7 +405,7 @@ CardinalSplineBy* CardinalSplineBy::reverse() const p = -p; pReverse->insertControlPoint(p, 0); - for (unsigned int i = 1; i < pReverse->count(); ++i) + for (ssize_t i = 1; i < pReverse->count(); ++i) { Point current = pReverse->getControlPointAtIndex(i); current = -current; @@ -475,8 +475,8 @@ CatmullRomTo* CatmullRomTo::clone() const CatmullRomTo* CatmullRomTo::reverse() const { - PointArray *pReverse = _points->reverse(); - return CatmullRomTo::create(_duration, pReverse); + PointArray *reverse = _points->reverse(); + return CatmullRomTo::create(_duration, reverse); } @@ -528,7 +528,7 @@ CatmullRomBy* CatmullRomBy::reverse() const // convert "absolutes" to "diffs" // Point p = copyConfig->getControlPointAtIndex(0); - for (unsigned int i = 1; i < copyConfig->count(); ++i) + for (ssize_t i = 1; i < copyConfig->count(); ++i) { Point current = copyConfig->getControlPointAtIndex(i); Point diff = current - p; @@ -550,7 +550,7 @@ CatmullRomBy* CatmullRomBy::reverse() const p = -p; reverse->insertControlPoint(p, 0); - for (unsigned int i = 1; i < reverse->count(); ++i) + for (ssize_t i = 1; i < reverse->count(); ++i) { Point current = reverse->getControlPointAtIndex(i); current = -current; diff --git a/cocos/2d/CCActionCatmullRom.h b/cocos/2d/CCActionCatmullRom.h index 5678407dc0..0c47a4137f 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(int capacity); + static PointArray* create(ssize_t capacity); /** * @js NA @@ -77,7 +77,7 @@ public: /** initializes a Catmull Rom config with a capacity hint * @js NA */ - bool initWithCapacity(int capacity); + bool initWithCapacity(ssize_t capacity); /** appends a control point * @js NA @@ -87,27 +87,27 @@ public: /** inserts a controlPoint at index * @js NA */ - void insertControlPoint(Point &controlPoint, int index); + void insertControlPoint(Point &controlPoint, ssize_t index); /** replaces an existing controlPoint at index * @js NA */ - void replaceControlPoint(Point &controlPoint, int index); + void replaceControlPoint(Point &controlPoint, ssize_t index); /** get the value of a controlPoint at a given index * @js NA */ - Point getControlPointAtIndex(int index); + Point getControlPointAtIndex(ssize_t index); /** deletes a control point at a given index * @js NA */ - void removeControlPointAtIndex(int index); + void removeControlPointAtIndex(ssize_t index); /** returns the number of objects of the control point array * @js NA */ - int count() const; + ssize_t count() const; /** returns a new copy of the array reversed. User is responsible for releasing this copy * @js NA diff --git a/cocos/2d/CCActionGrid.cpp b/cocos/2d/CCActionGrid.cpp index c2cddb2373..edd96ae0da 100644 --- a/cocos/2d/CCActionGrid.cpp +++ b/cocos/2d/CCActionGrid.cpp @@ -25,6 +25,7 @@ THE SOFTWARE. #include "CCActionGrid.h" #include "CCDirector.h" #include "CCGrid.h" +#include "CCNodeGrid.h" NS_CC_BEGIN // implementation of GridAction @@ -44,16 +45,16 @@ bool GridAction::initWithDuration(float duration, const Size& gridSize) void GridAction::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); + cacheTargetAsGridNode(); GridBase *newgrid = this->getGrid(); - Node *t = _target; - GridBase *targetGrid = t->getGrid(); + GridBase *targetGrid = _gridNodeTarget->getGrid(); if (targetGrid && targetGrid->getReuseGrid() > 0) { if (targetGrid->isActive() && targetGrid->getGridSize().width == _gridSize.width - && targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast(targetGrid) != NULL*/) + && targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast(targetGrid) != nullptr*/) { targetGrid->reuse(); } @@ -69,11 +70,17 @@ void GridAction::startWithTarget(Node *target) targetGrid->setActive(false); } - t->setGrid(newgrid); - t->getGrid()->setActive(true); + _gridNodeTarget->setGrid(newgrid); + _gridNodeTarget->getGrid()->setActive(true); } } +void GridAction::cacheTargetAsGridNode() +{ + _gridNodeTarget = dynamic_cast (_target); + CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid"); +} + GridAction* GridAction::reverse() const { // FIXME: This conversion isn't safe. @@ -97,19 +104,19 @@ GridBase* Grid3DAction::getGrid() Vertex3F Grid3DAction::getVertex(const Point& position) const { - Grid3D *g = (Grid3D*)_target->getGrid(); + Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid(); return g->getVertex(position); } Vertex3F Grid3DAction::getOriginalVertex(const Point& position) const { - Grid3D *g = (Grid3D*)_target->getGrid(); + Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid(); return g->getOriginalVertex(position); } void Grid3DAction::setVertex(const Point& position, const Vertex3F& vertex) { - Grid3D *g = (Grid3D*)_target->getGrid(); + Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid(); g->setVertex(position, vertex); } @@ -122,19 +129,19 @@ GridBase* TiledGrid3DAction::getGrid(void) Quad3 TiledGrid3DAction::getTile(const Point& pos) const { - TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); + TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid(); return g->getTile(pos); } Quad3 TiledGrid3DAction::getOriginalTile(const Point& pos) const { - TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); + TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid(); return g->getOriginalTile(pos); } void TiledGrid3DAction::setTile(const Point& pos, const Quad3& coords) { - TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); + TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid(); return g->setTile(pos, coords); } @@ -345,14 +352,20 @@ DeccelAmplitude* DeccelAmplitude::reverse() const void StopGrid::startWithTarget(Node *target) { ActionInstant::startWithTarget(target); - - GridBase *grid = _target->getGrid(); + cacheTargetAsGridNode(); + GridBase *grid = _gridNodeTarget->getGrid(); if (grid && grid->isActive()) { grid->setActive(false); } } +void StopGrid::cacheTargetAsGridNode() +{ + _gridNodeTarget = dynamic_cast (_target); + CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid"); +} + StopGrid* StopGrid::create() { StopGrid* pAction = new StopGrid(); @@ -402,13 +415,20 @@ bool ReuseGrid::initWithTimes(int times) void ReuseGrid::startWithTarget(Node *target) { ActionInstant::startWithTarget(target); + cacheTargetAsGridNode(); - if (_target->getGrid() && _target->getGrid()->isActive()) + if (_gridNodeTarget->getGrid() && _gridNodeTarget->getGrid()->isActive()) { - _target->getGrid()->setReuseGrid(_target->getGrid()->getReuseGrid() + _times); + _gridNodeTarget->getGrid()->setReuseGrid(_gridNodeTarget->getGrid()->getReuseGrid() + _times); } } +void ReuseGrid::cacheTargetAsGridNode() +{ + _gridNodeTarget = dynamic_cast (_target); + CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid"); +} + ReuseGrid* ReuseGrid::clone() const { return ReuseGrid::create(_times); diff --git a/cocos/2d/CCActionGrid.h b/cocos/2d/CCActionGrid.h index eb9ddc23a5..b3981b42a8 100644 --- a/cocos/2d/CCActionGrid.h +++ b/cocos/2d/CCActionGrid.h @@ -31,6 +31,7 @@ THE SOFTWARE. NS_CC_BEGIN class GridBase; +class NodeGrid; /** * @addtogroup actions @@ -57,6 +58,10 @@ protected: bool initWithDuration(float duration, const Size& gridSize); Size _gridSize; + + NodeGrid* _gridNodeTarget; + + void cacheTargetAsGridNode(); private: CC_DISALLOW_COPY_AND_ASSIGN(GridAction); @@ -248,7 +253,7 @@ private: /** @brief StopGrid action. @warning Don't call this action if another grid action is active. Call if you want to remove the the grid effect. Example: - Sequence::actions(Lens::action(...), StopGrid::action(...), NULL); + Sequence::actions(Lens::action(...), StopGrid::action(...), nullptr); */ class CC_DLL StopGrid : public ActionInstant { @@ -264,6 +269,10 @@ public: protected: StopGrid() {} virtual ~StopGrid() {} + + NodeGrid* _gridNodeTarget; + + void cacheTargetAsGridNode(); private: CC_DISALLOW_COPY_AND_ASSIGN(StopGrid); @@ -286,7 +295,11 @@ protected: virtual ~ReuseGrid() {} /** initializes an action with the number of times that the current grid will be reused */ bool initWithTimes(int times); - + + NodeGrid* _gridNodeTarget; + + void cacheTargetAsGridNode(); + int _times; private: diff --git a/cocos/2d/CCActionInstant.cpp b/cocos/2d/CCActionInstant.cpp index 408a400e84..92e5a5dfdf 100644 --- a/cocos/2d/CCActionInstant.cpp +++ b/cocos/2d/CCActionInstant.cpp @@ -421,7 +421,7 @@ CallFuncN * CallFuncN::create(const std::function &func) } CC_SAFE_DELETE(ret); - return NULL; + return nullptr; } // XXX deprecated diff --git a/cocos/2d/CCActionInstant.h b/cocos/2d/CCActionInstant.h index cf0b806336..f518899374 100644 --- a/cocos/2d/CCActionInstant.h +++ b/cocos/2d/CCActionInstant.h @@ -292,8 +292,8 @@ public: protected: CallFunc() - : _selectorTarget(NULL) - , _callFunc(NULL) + : _selectorTarget(nullptr) + , _callFunc(nullptr) , _function(nullptr) { } diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 9aca314728..7d4a1e0bbb 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -46,12 +46,12 @@ public: ExtraAction* ExtraAction::create() { - ExtraAction* pRet = new ExtraAction(); - if (pRet) + ExtraAction* ret = new ExtraAction(); + if (ret) { - pRet->autorelease(); + ret->autorelease(); } - return pRet; + return ret; } ExtraAction* ExtraAction::clone(void) const { @@ -158,30 +158,30 @@ Sequence* Sequence::createWithTwoActions(FiniteTimeAction *actionOne, FiniteTime return sequence; } -Sequence* Sequence::create(FiniteTimeAction *pAction1, ...) +Sequence* Sequence::create(FiniteTimeAction *action1, ...) { va_list params; - va_start(params, pAction1); + va_start(params, action1); - Sequence *pRet = Sequence::createWithVariableList(pAction1, params); + Sequence *ret = Sequence::createWithVariableList(action1, params); va_end(params); - return pRet; + return ret; } -Sequence* Sequence::createWithVariableList(FiniteTimeAction *pAction1, va_list args) +Sequence* Sequence::createWithVariableList(FiniteTimeAction *action1, va_list args) { - FiniteTimeAction *pNow; - FiniteTimeAction *pPrev = pAction1; + FiniteTimeAction *now; + FiniteTimeAction *prev = action1; bool bOneAction = true; - while (pAction1) + while (action1) { - pNow = va_arg(args, FiniteTimeAction*); - if (pNow) + now = va_arg(args, FiniteTimeAction*); + if (now) { - pPrev = createWithTwoActions(pPrev, pNow); + prev = createWithTwoActions(prev, now); bOneAction = false; } else @@ -189,18 +189,18 @@ Sequence* Sequence::createWithVariableList(FiniteTimeAction *pAction1, va_list a // If only one action is added to Sequence, make up a Sequence by adding a simplest finite time action. if (bOneAction) { - pPrev = createWithTwoActions(pPrev, ExtraAction::create()); + prev = createWithTwoActions(prev, ExtraAction::create()); } break; } } - return ((Sequence*)pPrev); + return ((Sequence*)prev); } Sequence* Sequence::create(const Vector& arrayOfActions) { - Sequence* pRet = NULL; + Sequence* ret = nullptr; do { auto count = arrayOfActions.size(); @@ -220,24 +220,24 @@ Sequence* Sequence::create(const Vector& arrayOfActions) // If only one action is added to Sequence, make up a Sequence by adding a simplest finite time action. prev = createWithTwoActions(prev, ExtraAction::create()); } - pRet = static_cast(prev); + ret = static_cast(prev); }while (0); - return pRet; + return ret; } -bool Sequence::initWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo) +bool Sequence::initWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo) { - CCASSERT(pActionOne != NULL, ""); - CCASSERT(pActionTwo != NULL, ""); + CCASSERT(actionOne != nullptr, ""); + CCASSERT(actionTwo != nullptr, ""); - float d = pActionOne->getDuration() + pActionTwo->getDuration(); + float d = actionOne->getDuration() + actionTwo->getDuration(); ActionInterval::initWithDuration(d); - _actions[0] = pActionOne; - pActionOne->retain(); + _actions[0] = actionOne; + actionOne->retain(); - _actions[1] = pActionTwo; - pActionTwo->retain(); + _actions[1] = actionTwo; + actionTwo->retain(); return true; } @@ -346,26 +346,26 @@ Sequence* Sequence::reverse() const // Repeat // -Repeat* Repeat::create(FiniteTimeAction *pAction, unsigned int times) +Repeat* Repeat::create(FiniteTimeAction *action, unsigned int times) { - Repeat* pRepeat = new Repeat(); - pRepeat->initWithAction(pAction, times); - pRepeat->autorelease(); + Repeat* repeat = new Repeat(); + repeat->initWithAction(action, times); + repeat->autorelease(); - return pRepeat; + return repeat; } -bool Repeat::initWithAction(FiniteTimeAction *pAction, unsigned int times) +bool Repeat::initWithAction(FiniteTimeAction *action, unsigned int times) { - float d = pAction->getDuration() * times; + float d = action->getDuration() * times; if (ActionInterval::initWithDuration(d)) { _times = times; - _innerAction = pAction; - pAction->retain(); + _innerAction = action; + action->retain(); - _actionInstant = dynamic_cast(pAction) ? true : false; + _actionInstant = dynamic_cast(action) ? true : false; //an instant action needs to be executed one time less in the update method since it uses startWithTarget to execute the action if (_actionInstant) { @@ -469,23 +469,23 @@ RepeatForever::~RepeatForever() CC_SAFE_RELEASE(_innerAction); } -RepeatForever *RepeatForever::create(ActionInterval *pAction) +RepeatForever *RepeatForever::create(ActionInterval *action) { - RepeatForever *pRet = new RepeatForever(); - if (pRet && pRet->initWithAction(pAction)) + RepeatForever *ret = new RepeatForever(); + if (ret && ret->initWithAction(action)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); - return NULL; + CC_SAFE_DELETE(ret); + return nullptr; } -bool RepeatForever::initWithAction(ActionInterval *pAction) +bool RepeatForever::initWithAction(ActionInterval *action) { - CCASSERT(pAction != NULL, ""); - pAction->retain(); - _innerAction = pAction; + CCASSERT(action != nullptr, ""); + action->retain(); + _innerAction = action; return true; } @@ -531,49 +531,49 @@ RepeatForever *RepeatForever::reverse() const // Spawn // -Spawn* Spawn::create(FiniteTimeAction *pAction1, ...) +Spawn* Spawn::create(FiniteTimeAction *action1, ...) { va_list params; - va_start(params, pAction1); + va_start(params, action1); - Spawn *pRet = Spawn::createWithVariableList(pAction1, params); + Spawn *ret = Spawn::createWithVariableList(action1, params); va_end(params); - return pRet; + return ret; } -Spawn* Spawn::createWithVariableList(FiniteTimeAction *pAction1, va_list args) +Spawn* Spawn::createWithVariableList(FiniteTimeAction *action1, va_list args) { - FiniteTimeAction *pNow; - FiniteTimeAction *pPrev = pAction1; - bool bOneAction = true; + FiniteTimeAction *now; + FiniteTimeAction *prev = action1; + bool oneAction = true; - while (pAction1) + while (action1) { - pNow = va_arg(args, FiniteTimeAction*); - if (pNow) + now = va_arg(args, FiniteTimeAction*); + if (now) { - pPrev = createWithTwoActions(pPrev, pNow); - bOneAction = false; + prev = createWithTwoActions(prev, now); + oneAction = false; } else { // If only one action is added to Spawn, make up a Spawn by adding a simplest finite time action. - if (bOneAction) + if (oneAction) { - pPrev = createWithTwoActions(pPrev, ExtraAction::create()); + prev = createWithTwoActions(prev, ExtraAction::create()); } break; } } - return ((Spawn*)pPrev); + return ((Spawn*)prev); } Spawn* Spawn::create(const Vector& arrayOfActions) { - Spawn* pRet = NULL; + Spawn* ret = nullptr; do { auto count = arrayOfActions.size(); @@ -591,10 +591,10 @@ Spawn* Spawn::create(const Vector& 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 = static_cast(prev); + ret = static_cast(prev); }while (0); - return pRet; + return ret; } Spawn* Spawn::createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2) @@ -606,38 +606,37 @@ Spawn* Spawn::createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction * return spawn; } -bool Spawn:: initWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2) +bool Spawn::initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2) { - CCASSERT(pAction1 != NULL, ""); - CCASSERT(pAction2 != NULL, ""); + CCASSERT(action1 != nullptr, ""); + CCASSERT(action2 != nullptr, ""); - bool bRet = false; + bool ret = false; - float d1 = pAction1->getDuration(); - float d2 = pAction2->getDuration(); + float d1 = action1->getDuration(); + float d2 = action2->getDuration(); if (ActionInterval::initWithDuration(MAX(d1, d2))) { - _one = pAction1; - _two = pAction2; + _one = action1; + _two = action2; if (d1 > d2) { - _two = Sequence::createWithTwoActions(pAction2, DelayTime::create(d1 - d2)); + _two = Sequence::createWithTwoActions(action2, DelayTime::create(d1 - d2)); } else if (d1 < d2) { - _one = Sequence::createWithTwoActions(pAction1, DelayTime::create(d2 - d1)); + _one = Sequence::createWithTwoActions(action1, DelayTime::create(d2 - d1)); } _one->retain(); _two->retain(); - bRet = true; + ret = true; } - - return bRet; + return ret; } Spawn* Spawn::clone(void) const @@ -691,41 +690,41 @@ Spawn* Spawn::reverse() const // RotateTo // -RotateTo* RotateTo::create(float fDuration, float fDeltaAngle) +RotateTo* RotateTo::create(float duration, float deltaAngle) { - RotateTo* pRotateTo = new RotateTo(); - pRotateTo->initWithDuration(fDuration, fDeltaAngle); - pRotateTo->autorelease(); + RotateTo* rotateTo = new RotateTo(); + rotateTo->initWithDuration(duration, deltaAngle); + rotateTo->autorelease(); - return pRotateTo; + return rotateTo; } -bool RotateTo::initWithDuration(float fDuration, float fDeltaAngle) +bool RotateTo::initWithDuration(float duration, float deltaAngle) { - if (ActionInterval::initWithDuration(fDuration)) + if (ActionInterval::initWithDuration(duration)) { - _dstAngleX = _dstAngleY = fDeltaAngle; + _dstAngleX = _dstAngleY = deltaAngle; return true; } return false; } -RotateTo* RotateTo::create(float fDuration, float fDeltaAngleX, float fDeltaAngleY) +RotateTo* RotateTo::create(float duration, float deltaAngleX, float deltaAngleY) { - RotateTo* pRotateTo = new RotateTo(); - pRotateTo->initWithDuration(fDuration, fDeltaAngleX, fDeltaAngleY); - pRotateTo->autorelease(); + RotateTo* rotateTo = new RotateTo(); + rotateTo->initWithDuration(duration, deltaAngleX, deltaAngleY); + rotateTo->autorelease(); - return pRotateTo; + return rotateTo; } -bool RotateTo::initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY) +bool RotateTo::initWithDuration(float duration, float deltaAngleX, float deltaAngleY) { - if (ActionInterval::initWithDuration(fDuration)) + if (ActionInterval::initWithDuration(duration)) { - _dstAngleX = fDeltaAngleX; - _dstAngleY = fDeltaAngleY; + _dstAngleX = deltaAngleX; + _dstAngleY = deltaAngleY; return true; } @@ -810,41 +809,41 @@ RotateTo *RotateTo::reverse() const // RotateBy // -RotateBy* RotateBy::create(float fDuration, float fDeltaAngle) +RotateBy* RotateBy::create(float duration, float deltaAngle) { - RotateBy *pRotateBy = new RotateBy(); - pRotateBy->initWithDuration(fDuration, fDeltaAngle); - pRotateBy->autorelease(); + RotateBy *rotateBy = new RotateBy(); + rotateBy->initWithDuration(duration, deltaAngle); + rotateBy->autorelease(); - return pRotateBy; + return rotateBy; } -bool RotateBy::initWithDuration(float fDuration, float fDeltaAngle) +bool RotateBy::initWithDuration(float duration, float deltaAngle) { - if (ActionInterval::initWithDuration(fDuration)) + if (ActionInterval::initWithDuration(duration)) { - _angleX = _angleY = fDeltaAngle; + _angleX = _angleY = deltaAngle; return true; } return false; } -RotateBy* RotateBy::create(float fDuration, float fDeltaAngleX, float fDeltaAngleY) +RotateBy* RotateBy::create(float duration, float deltaAngleX, float deltaAngleY) { - RotateBy *pRotateBy = new RotateBy(); - pRotateBy->initWithDuration(fDuration, fDeltaAngleX, fDeltaAngleY); - pRotateBy->autorelease(); + RotateBy *rotateBy = new RotateBy(); + rotateBy->initWithDuration(duration, deltaAngleX, deltaAngleY); + rotateBy->autorelease(); - return pRotateBy; + return rotateBy; } -bool RotateBy::initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY) +bool RotateBy::initWithDuration(float duration, float deltaAngleX, float deltaAngleY) { - if (ActionInterval::initWithDuration(fDuration)) + if (ActionInterval::initWithDuration(duration)) { - _angleX = fDeltaAngleX; - _angleY = fDeltaAngleY; + _angleX = deltaAngleX; + _angleY = deltaAngleY; return true; } @@ -888,11 +887,11 @@ RotateBy* RotateBy::reverse() const MoveBy* MoveBy::create(float duration, const Point& deltaPosition) { - MoveBy *pRet = new MoveBy(); - pRet->initWithDuration(duration, deltaPosition); - pRet->autorelease(); + MoveBy *ret = new MoveBy(); + ret->initWithDuration(duration, deltaPosition); + ret->autorelease(); - return pRet; + return ret; } bool MoveBy::initWithDuration(float duration, const Point& deltaPosition) @@ -950,11 +949,11 @@ void MoveBy::update(float t) MoveTo* MoveTo::create(float duration, const Point& position) { - MoveTo *pRet = new MoveTo(); - pRet->initWithDuration(duration, position); - pRet->autorelease(); + MoveTo *ret = new MoveTo(); + ret->initWithDuration(duration, position); + ret->autorelease(); - return pRet; + return ret; } bool MoveTo::initWithDuration(float duration, const Point& position) @@ -989,20 +988,20 @@ void MoveTo::startWithTarget(Node *target) // SkewTo* SkewTo::create(float t, float sx, float sy) { - SkewTo *pSkewTo = new SkewTo(); - if (pSkewTo) + SkewTo *skewTo = new SkewTo(); + if (skewTo) { - if (pSkewTo->initWithDuration(t, sx, sy)) + if (skewTo->initWithDuration(t, sx, sy)) { - pSkewTo->autorelease(); + skewTo->autorelease(); } else { - CC_SAFE_DELETE(pSkewTo); + CC_SAFE_DELETE(skewTo); } } - return pSkewTo; + return skewTo; } bool SkewTo::initWithDuration(float t, float sx, float sy) @@ -1107,20 +1106,20 @@ SkewTo::SkewTo() // SkewBy* SkewBy::create(float t, float sx, float sy) { - SkewBy *pSkewBy = new SkewBy(); - if (pSkewBy) + SkewBy *skewBy = new SkewBy(); + if (skewBy) { - if (pSkewBy->initWithDuration(t, sx, sy)) + if (skewBy->initWithDuration(t, sx, sy)) { - pSkewBy->autorelease(); + skewBy->autorelease(); } else { - CC_SAFE_DELETE(pSkewBy); + CC_SAFE_DELETE(skewBy); } } - return pSkewBy; + return skewBy; } SkewBy * SkewBy::clone() const @@ -1134,17 +1133,17 @@ SkewBy * SkewBy::clone() const bool SkewBy::initWithDuration(float t, float deltaSkewX, float deltaSkewY) { - bool bRet = false; + bool ret = false; if (SkewTo::initWithDuration(t, deltaSkewX, deltaSkewY)) { _skewX = deltaSkewX; _skewY = deltaSkewY; - bRet = true; + ret = true; } - return bRet; + return ret; } void SkewBy::startWithTarget(Node *target) @@ -1167,11 +1166,11 @@ SkewBy* SkewBy::reverse() const JumpBy* JumpBy::create(float duration, const Point& position, float height, int jumps) { - JumpBy *pJumpBy = new JumpBy(); - pJumpBy->initWithDuration(duration, position, height, jumps); - pJumpBy->autorelease(); + JumpBy *jumpBy = new JumpBy(); + jumpBy->initWithDuration(duration, position, height, jumps); + jumpBy->autorelease(); - return pJumpBy; + return jumpBy; } bool JumpBy::initWithDuration(float duration, const Point& position, float height, int jumps) @@ -1243,11 +1242,11 @@ JumpBy* JumpBy::reverse() const JumpTo* JumpTo::create(float duration, const Point& position, float height, int jumps) { - JumpTo *pJumpTo = new JumpTo(); - pJumpTo->initWithDuration(duration, position, height, jumps); - pJumpTo->autorelease(); + JumpTo *jumpTo = new JumpTo(); + jumpTo->initWithDuration(duration, position, height, jumps); + jumpTo->autorelease(); - return pJumpTo; + return jumpTo; } JumpTo* JumpTo::clone(void) const @@ -1289,11 +1288,11 @@ static inline float bezierat( float a, float b, float c, float d, float t ) BezierBy* BezierBy::create(float t, const ccBezierConfig& c) { - BezierBy *pBezierBy = new BezierBy(); - pBezierBy->initWithDuration(t, c); - pBezierBy->autorelease(); + BezierBy *bezierBy = new BezierBy(); + bezierBy->initWithDuration(t, c); + bezierBy->autorelease(); - return pBezierBy; + return bezierBy; } bool BezierBy::initWithDuration(float t, const ccBezierConfig& c) @@ -1362,8 +1361,8 @@ BezierBy* BezierBy::reverse(void) const r.controlPoint_1 = _config.controlPoint_2 + (-_config.endPosition); r.controlPoint_2 = _config.controlPoint_1 + (-_config.endPosition); - BezierBy *pAction = BezierBy::create(_duration, r); - return pAction; + BezierBy *action = BezierBy::create(_duration, r); + return action; } // @@ -1372,11 +1371,11 @@ BezierBy* BezierBy::reverse(void) const BezierTo* BezierTo::create(float t, const ccBezierConfig& c) { - BezierTo *pBezierTo = new BezierTo(); - pBezierTo->initWithDuration(t, c); - pBezierTo->autorelease(); + BezierTo *bezierTo = new BezierTo(); + bezierTo->initWithDuration(t, c); + bezierTo->autorelease(); - return pBezierTo; + return bezierTo; } bool BezierTo::initWithDuration(float t, const ccBezierConfig &c) @@ -1419,20 +1418,20 @@ BezierTo* BezierTo::reverse() const // ScaleTo* ScaleTo::create(float duration, float s) { - ScaleTo *pScaleTo = new ScaleTo(); - pScaleTo->initWithDuration(duration, s); - pScaleTo->autorelease(); + ScaleTo *scaleTo = new ScaleTo(); + scaleTo->initWithDuration(duration, s); + scaleTo->autorelease(); - return pScaleTo; + return scaleTo; } ScaleTo* ScaleTo::create(float duration, float sx, float sy) { - ScaleTo *pScaleTo = new ScaleTo(); - pScaleTo->initWithDuration(duration, sx, sy); - pScaleTo->autorelease(); + ScaleTo *scaleTo = new ScaleTo(); + scaleTo->initWithDuration(duration, sx, sy); + scaleTo->autorelease(); - return pScaleTo; + return scaleTo; } bool ScaleTo::initWithDuration(float duration, float s) @@ -1501,20 +1500,20 @@ void ScaleTo::update(float time) ScaleBy* ScaleBy::create(float duration, float s) { - ScaleBy *pScaleBy = new ScaleBy(); - pScaleBy->initWithDuration(duration, s); - pScaleBy->autorelease(); + ScaleBy *scaleBy = new ScaleBy(); + scaleBy->initWithDuration(duration, s); + scaleBy->autorelease(); - return pScaleBy; + return scaleBy; } ScaleBy* ScaleBy::create(float duration, float sx, float sy) { - ScaleBy *pScaleBy = new ScaleBy(); - pScaleBy->initWithDuration(duration, sx, sy); - pScaleBy->autorelease(); + ScaleBy *scaleBy = new ScaleBy(); + scaleBy->initWithDuration(duration, sx, sy); + scaleBy->autorelease(); - return pScaleBy; + return scaleBy; } ScaleBy* ScaleBy::clone(void) const @@ -1544,11 +1543,11 @@ ScaleBy* ScaleBy::reverse() const Blink* Blink::create(float duration, int blinks) { - Blink *pBlink = new Blink(); - pBlink->initWithDuration(duration, blinks); - pBlink->autorelease(); + Blink *blink = new Blink(); + blink->initWithDuration(duration, blinks); + blink->autorelease(); - return pBlink; + return blink; } bool Blink::initWithDuration(float duration, int blinks) @@ -1606,12 +1605,12 @@ Blink* Blink::reverse() const FadeIn* FadeIn::create(float d) { - FadeIn* pAction = new FadeIn(); + FadeIn* action = new FadeIn(); - pAction->initWithDuration(d); - pAction->autorelease(); + action->initWithDuration(d); + action->autorelease(); - return pAction; + return action; } FadeIn* FadeIn::clone() const @@ -1625,10 +1624,9 @@ FadeIn* FadeIn::clone() const void FadeIn::update(float time) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(_target); - if (pRGBAProtocol) + if (_target) { - pRGBAProtocol->setOpacity((GLubyte)(255 * time)); + _target->setOpacity((GLubyte)(255 * time)); } /*_target->setOpacity((GLubyte)(255 * time));*/ } @@ -1644,12 +1642,12 @@ ActionInterval* FadeIn::reverse() const FadeOut* FadeOut::create(float d) { - FadeOut* pAction = new FadeOut(); + FadeOut* action = new FadeOut(); - pAction->initWithDuration(d); - pAction->autorelease(); + action->initWithDuration(d); + action->autorelease(); - return pAction; + return action; } FadeOut* FadeOut::clone() const @@ -1663,10 +1661,9 @@ FadeOut* FadeOut::clone() const void FadeOut::update(float time) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(_target); - if (pRGBAProtocol) + if (_target) { - pRGBAProtocol->setOpacity(GLubyte(255 * (1 - time))); + _target->setOpacity(GLubyte(255 * (1 - time))); } /*_target->setOpacity(GLubyte(255 * (1 - time)));*/ } @@ -1682,11 +1679,11 @@ ActionInterval* FadeOut::reverse() const FadeTo* FadeTo::create(float duration, GLubyte opacity) { - FadeTo *pFadeTo = new FadeTo(); - pFadeTo->initWithDuration(duration, opacity); - pFadeTo->autorelease(); + FadeTo *fadeTo = new FadeTo(); + fadeTo->initWithDuration(duration, opacity); + fadeTo->autorelease(); - return pFadeTo; + return fadeTo; } bool FadeTo::initWithDuration(float duration, GLubyte opacity) @@ -1719,20 +1716,18 @@ void FadeTo::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); - RGBAProtocol *pRGBAProtocol = dynamic_cast(target); - if (pRGBAProtocol) + if (target) { - _fromOpacity = pRGBAProtocol->getOpacity(); + _fromOpacity = target->getOpacity(); } /*_fromOpacity = target->getOpacity();*/ } void FadeTo::update(float time) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(_target); - if (pRGBAProtocol) + if (_target) { - pRGBAProtocol->setOpacity((GLubyte)(_fromOpacity + (_toOpacity - _fromOpacity) * time)); + _target->setOpacity((GLubyte)(_fromOpacity + (_toOpacity - _fromOpacity) * time)); } /*_target->setOpacity((GLubyte)(_fromOpacity + (_toOpacity - _fromOpacity) * time));*/ } @@ -1742,11 +1737,11 @@ void FadeTo::update(float time) // TintTo* TintTo::create(float duration, GLubyte red, GLubyte green, GLubyte blue) { - TintTo *pTintTo = new TintTo(); - pTintTo->initWithDuration(duration, red, green, blue); - pTintTo->autorelease(); + TintTo *tintTo = new TintTo(); + tintTo->initWithDuration(duration, red, green, blue); + tintTo->autorelease(); - return pTintTo; + return tintTo; } bool TintTo::initWithDuration(float duration, GLubyte red, GLubyte green, GLubyte blue) @@ -1778,20 +1773,18 @@ TintTo* TintTo::reverse() const void TintTo::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); - RGBAProtocol *pRGBAProtocol = dynamic_cast(_target); - if (pRGBAProtocol) + if (_target) { - _from = pRGBAProtocol->getColor(); + _from = _target->getColor(); } /*_from = target->getColor();*/ } void TintTo::update(float time) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(_target); - if (pRGBAProtocol) + if (_target) { - pRGBAProtocol->setColor(Color3B(GLubyte(_from.r + (_to.r - _from.r) * time), + _target->setColor(Color3B(GLubyte(_from.r + (_to.r - _from.r) * time), (GLubyte)(_from.g + (_to.g - _from.g) * time), (GLubyte)(_from.b + (_to.b - _from.b) * time))); } @@ -1803,11 +1796,11 @@ void TintTo::update(float time) TintBy* TintBy::create(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue) { - TintBy *pTintBy = new TintBy(); - pTintBy->initWithDuration(duration, deltaRed, deltaGreen, deltaBlue); - pTintBy->autorelease(); + TintBy *tintBy = new TintBy(); + tintBy->initWithDuration(duration, deltaRed, deltaGreen, deltaBlue); + tintBy->autorelease(); - return pTintBy; + return tintBy; } bool TintBy::initWithDuration(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue) @@ -1837,10 +1830,9 @@ void TintBy::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); - RGBAProtocol *pRGBAProtocol = dynamic_cast(target); - if (pRGBAProtocol) + if (target) { - Color3B color = pRGBAProtocol->getColor(); + Color3B color = target->getColor(); _fromR = color.r; _fromG = color.g; _fromB = color.b; @@ -1849,10 +1841,9 @@ void TintBy::startWithTarget(Node *target) void TintBy::update(float time) { - RGBAProtocol *pRGBAProtocol = dynamic_cast(_target); - if (pRGBAProtocol) + if (_target) { - pRGBAProtocol->setColor(Color3B((GLubyte)(_fromR + _deltaR * time), + _target->setColor(Color3B((GLubyte)(_fromR + _deltaR * time), (GLubyte)(_fromG + _deltaG * time), (GLubyte)(_fromB + _deltaB * time))); } @@ -1868,12 +1859,12 @@ TintBy* TintBy::reverse() const // DelayTime* DelayTime::create(float d) { - DelayTime* pAction = new DelayTime(); + DelayTime* action = new DelayTime(); - pAction->initWithDuration(d); - pAction->autorelease(); + action->initWithDuration(d); + action->autorelease(); - return pAction; + return action; } DelayTime* DelayTime::clone() const @@ -1900,28 +1891,28 @@ DelayTime* DelayTime::reverse() const // ReverseTime // -ReverseTime* ReverseTime::create(FiniteTimeAction *pAction) +ReverseTime* ReverseTime::create(FiniteTimeAction *action) { // casting to prevent warnings - ReverseTime *pReverseTime = new ReverseTime(); - pReverseTime->initWithAction( pAction->clone() ); - pReverseTime->autorelease(); + ReverseTime *reverseTime = new ReverseTime(); + reverseTime->initWithAction( action->clone() ); + reverseTime->autorelease(); - return pReverseTime; + return reverseTime; } -bool ReverseTime::initWithAction(FiniteTimeAction *pAction) +bool ReverseTime::initWithAction(FiniteTimeAction *action) { - CCASSERT(pAction != NULL, ""); - CCASSERT(pAction != _other, ""); + CCASSERT(action != nullptr, ""); + CCASSERT(action != _other, ""); - if (ActionInterval::initWithDuration(pAction->getDuration())) + if (ActionInterval::initWithDuration(action->getDuration())) { // Don't leak if action is reused CC_SAFE_RELEASE(_other); - _other = pAction; - pAction->retain(); + _other = action; + action->retain(); return true; } @@ -1938,7 +1929,7 @@ ReverseTime* ReverseTime::clone() const return a; } -ReverseTime::ReverseTime() : _other(NULL) +ReverseTime::ReverseTime() : _other(nullptr) { } @@ -1977,21 +1968,21 @@ ReverseTime* ReverseTime::reverse() const // // Animate // -Animate* Animate::create(Animation *pAnimation) +Animate* Animate::create(Animation *animation) { - Animate *pAnimate = new Animate(); - pAnimate->initWithAnimation(pAnimation); - pAnimate->autorelease(); + Animate *animate = new Animate(); + animate->initWithAnimation(animation); + animate->autorelease(); - return pAnimate; + return animate; } Animate::Animate() : _splitTimes(new std::vector) , _nextFrame(0) -, _origFrame(NULL) +, _origFrame(nullptr) , _executedLoops(0) -, _animation(NULL) +, _animation(nullptr) { } @@ -2005,7 +1996,7 @@ Animate::~Animate() bool Animate::initWithAnimation(Animation* animation) { - CCASSERT( animation!=NULL, "Animate: argument Animation must be non-NULL"); + CCASSERT( animation!=nullptr, "Animate: argument Animation must be non-nullptr"); float singleDuration = animation->getDuration(); @@ -2013,7 +2004,7 @@ bool Animate::initWithAnimation(Animation* animation) { _nextFrame = 0; setAnimation(animation); - _origFrame = NULL; + _origFrame = nullptr; _executedLoops = 0; _splitTimes->reserve(animation->getFrames().size()); @@ -2056,13 +2047,13 @@ Animate* Animate::clone() const void Animate::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); - Sprite *pSprite = static_cast(target); + Sprite *sprite = static_cast(target); CC_SAFE_RELEASE(_origFrame); if (_animation->getRestoreOriginalFrame()) { - _origFrame = pSprite->getDisplayFrame(); + _origFrame = sprite->getSpriteFrame(); _origFrame->retain(); } _nextFrame = 0; @@ -2073,7 +2064,7 @@ void Animate::stop(void) { if (_animation->getRestoreOriginalFrame() && _target) { - static_cast(_target)->setDisplayFrame(_origFrame); + static_cast(_target)->setSpriteFrame(_origFrame); } ActionInterval::stop(); @@ -2098,7 +2089,7 @@ void Animate::update(float t) auto frames = _animation->getFrames(); auto numberOfFrames = frames.size(); - SpriteFrame *frameToDisplay = NULL; + SpriteFrame *frameToDisplay = nullptr; for( int i=_nextFrame; i < numberOfFrames; i++ ) { float splitTime = _splitTimes->at(i); @@ -2106,7 +2097,7 @@ void Animate::update(float t) if( splitTime <= t ) { AnimationFrame* frame = frames.at(i); frameToDisplay = frame->getSpriteFrame(); - static_cast(_target)->setDisplayFrame(frameToDisplay); + static_cast(_target)->setSpriteFrame(frameToDisplay); const ValueMap& dict = frame->getUserInfo(); if ( !dict.empty() ) @@ -2149,8 +2140,8 @@ Animate* Animate::reverse() const // TargetedAction TargetedAction::TargetedAction() -: _action(NULL) -, _forcedTarget(NULL) +: _action(nullptr) +, _forcedTarget(nullptr) { } @@ -2161,23 +2152,23 @@ TargetedAction::~TargetedAction() CC_SAFE_RELEASE(_action); } -TargetedAction* TargetedAction::create(Node* target, FiniteTimeAction* pAction) +TargetedAction* TargetedAction::create(Node* target, FiniteTimeAction* action) { TargetedAction* p = new TargetedAction(); - p->initWithTarget(target, pAction); + p->initWithTarget(target, action); p->autorelease(); return p; } -bool TargetedAction::initWithTarget(Node* target, FiniteTimeAction* pAction) +bool TargetedAction::initWithTarget(Node* target, FiniteTimeAction* action) { - if(ActionInterval::initWithDuration(pAction->getDuration())) + if(ActionInterval::initWithDuration(action->getDuration())) { CC_SAFE_RETAIN(target); _forcedTarget = target; - CC_SAFE_RETAIN(pAction); - _action = pAction; + CC_SAFE_RETAIN(action); + _action = action; return true; } return false; diff --git a/cocos/2d/CCActionInterval.h b/cocos/2d/CCActionInterval.h index 36306e2939..8fcfcda025 100644 --- a/cocos/2d/CCActionInterval.h +++ b/cocos/2d/CCActionInterval.h @@ -32,7 +32,7 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCSpriteFrame.h" #include "CCAnimation.h" -#include +#include "CCVector.h" #include NS_CC_BEGIN @@ -57,7 +57,7 @@ then running it again in Reverse mode. Example: -Action *pingPongAction = Sequence::actions(action, action->reverse(), NULL); +Action *pingPongAction = Sequence::actions(action, action->reverse(), nullptr); */ class CC_DLL ActionInterval : public FiniteTimeAction { @@ -92,7 +92,7 @@ class CC_DLL Sequence : public ActionInterval { public: /** helper constructor to create an array of sequenceable actions */ - static Sequence* create(FiniteTimeAction *pAction1, ...) CC_REQUIRES_NULL_TERMINATION; + static Sequence* create(FiniteTimeAction *action1, ...) CC_REQUIRES_NULL_TERMINATION; /** helper constructor to create an array of sequenceable actions given an array * @code * When this funtion bound to the js or lua,the input params changed @@ -102,9 +102,9 @@ public: */ static Sequence* create(const Vector& arrayOfActions); /** helper constructor to create an array of sequence-able actions */ - static Sequence* createWithVariableList(FiniteTimeAction *pAction1, va_list args); + static Sequence* createWithVariableList(FiniteTimeAction *action1, va_list args); /** creates the action */ - static Sequence* createWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo); + static Sequence* createWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo); // // Overrides @@ -136,15 +136,15 @@ class CC_DLL Repeat : public ActionInterval { public: /** creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30) */ - static Repeat* create(FiniteTimeAction *pAction, unsigned int times); + static Repeat* create(FiniteTimeAction *action, unsigned int times); - inline void setInnerAction(FiniteTimeAction *pAction) + inline void setInnerAction(FiniteTimeAction *action) { - if (_innerAction != pAction) + if (_innerAction != action) { - CC_SAFE_RETAIN(pAction); + CC_SAFE_RETAIN(action); CC_SAFE_RELEASE(_innerAction); - _innerAction = pAction; + _innerAction = action; } } @@ -188,14 +188,14 @@ class CC_DLL RepeatForever : public ActionInterval { public: /** creates the action */ - static RepeatForever* create(ActionInterval *pAction); + static RepeatForever* create(ActionInterval *action); - inline void setInnerAction(ActionInterval *pAction) + inline void setInnerAction(ActionInterval *action) { - if (_innerAction != pAction) + if (_innerAction != action) { CC_SAFE_RELEASE(_innerAction); - _innerAction = pAction; + _innerAction = action; CC_SAFE_RETAIN(_innerAction); } } @@ -220,7 +220,7 @@ protected: {} virtual ~RepeatForever(); /** initializes the action */ - bool initWithAction(ActionInterval *pAction); + bool initWithAction(ActionInterval *action); /** Inner action */ ActionInterval *_innerAction; @@ -241,16 +241,16 @@ public: * in lua :local create(local object1,local object2, ...) * @endcode */ - static Spawn* create(FiniteTimeAction *pAction1, ...) CC_REQUIRES_NULL_TERMINATION; + static Spawn* create(FiniteTimeAction *action1, ...) CC_REQUIRES_NULL_TERMINATION; /** helper constructor to create an array of spawned actions */ - static Spawn* createWithVariableList(FiniteTimeAction *pAction1, va_list args); + static Spawn* createWithVariableList(FiniteTimeAction *action1, va_list args); /** helper constructor to create an array of spawned actions given an array */ static Spawn* create(const Vector& arrayOfActions); /** creates the Spawn action */ - static Spawn* createWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); + static Spawn* createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2); // // Overrides @@ -265,7 +265,7 @@ protected: Spawn() {} virtual ~Spawn(); /** initializes the Spawn action with the 2 actions to spawn */ - bool initWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); + bool initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2); FiniteTimeAction *_one; FiniteTimeAction *_two; @@ -282,10 +282,10 @@ class CC_DLL RotateTo : public ActionInterval { public: /** creates the action with separate rotation angles */ - static RotateTo* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY); + static RotateTo* create(float duration, float deltaAngleX, float deltaAngleY); /** creates the action */ - static RotateTo* create(float fDuration, float fDeltaAngle); + static RotateTo* create(float duration, float deltaAngle); // // Overrides @@ -299,8 +299,8 @@ protected: RotateTo() {} virtual ~RotateTo() {} /** initializes the action */ - bool initWithDuration(float fDuration, float fDeltaAngle); - bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); + bool initWithDuration(float duration, float deltaAngle); + bool initWithDuration(float duration, float deltaAngleX, float deltaAngleY); float _dstAngleX; float _startAngleX; @@ -320,8 +320,8 @@ class CC_DLL RotateBy : public ActionInterval { public: /** creates the action */ - static RotateBy* create(float fDuration, float fDeltaAngle); - static RotateBy* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY); + static RotateBy* create(float duration, float deltaAngle); + static RotateBy* create(float duration, float deltaAngleX, float deltaAngleY); // // Override @@ -335,8 +335,8 @@ protected: RotateBy() {} virtual ~RotateBy() {} /** initializes the action */ - bool initWithDuration(float fDuration, float fDeltaAngle); - bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); + bool initWithDuration(float duration, float deltaAngle); + bool initWithDuration(float duration, float deltaAngleX, float deltaAngleY); float _angleX; float _startAngleX; @@ -878,7 +878,7 @@ class CC_DLL ReverseTime : public ActionInterval { public: /** creates the action */ - static ReverseTime* create(FiniteTimeAction *pAction); + static ReverseTime* create(FiniteTimeAction *action); // // Overrides @@ -893,7 +893,7 @@ protected: ReverseTime(); virtual ~ReverseTime(void); /** initializes the action */ - bool initWithAction(FiniteTimeAction *pAction); + bool initWithAction(FiniteTimeAction *action); FiniteTimeAction *_other; @@ -907,7 +907,7 @@ class CC_DLL Animate : public ActionInterval { public: /** creates the action with an Animation and will restore the original frame when the animation is over */ - static Animate* create(Animation *pAnimation); + static Animate* create(Animation *animation); /** sets the Animation object to be animated */ void setAnimation( Animation* animation ); @@ -928,7 +928,7 @@ protected: Animate(); virtual ~Animate(); /** initializes the action with an Animation and will restore the original frame when the animation is over */ - bool initWithAnimation(Animation *pAnimation); + bool initWithAnimation(Animation *animation); std::vector* _splitTimes; int _nextFrame; @@ -947,7 +947,7 @@ class CC_DLL TargetedAction : public ActionInterval { public: /** Create an action with the specified action and forced target */ - static TargetedAction* create(Node* target, FiniteTimeAction* pAction); + static TargetedAction* create(Node* target, FiniteTimeAction* action); /** Sets the target that the action will be forced to run with */ void setForcedTarget(Node* forcedTarget); @@ -968,7 +968,7 @@ protected: TargetedAction(); virtual ~TargetedAction(); /** Init an action with the specified action and forced target */ - bool initWithTarget(Node* target, FiniteTimeAction* pAction); + bool initWithTarget(Node* target, FiniteTimeAction* action); FiniteTimeAction* _action; Node* _forcedTarget; diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 2fb08fd0bd..56841d7f71 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -49,8 +49,8 @@ typedef struct _hashElement } tHashElement; ActionManager::ActionManager(void) -: _targets(NULL), - _currentTarget(NULL), +: _targets(nullptr), + _currentTarget(nullptr), _currentTargetSalvaged(false) { @@ -76,7 +76,7 @@ void ActionManager::deleteHashElement(tHashElement *element) void ActionManager::actionAllocWithHashElement(tHashElement *element) { // 4 actions per Node by default - if (element->actions == NULL) + if (element->actions == nullptr) { element->actions = ccArrayNew(4); }else @@ -122,7 +122,7 @@ void ActionManager::removeActionAtIndex(ssize_t index, tHashElement *element) void ActionManager::pauseTarget(Node *target) { - tHashElement *element = NULL; + tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -132,7 +132,7 @@ void ActionManager::pauseTarget(Node *target) void ActionManager::resumeTarget(Node *target) { - tHashElement *element = NULL; + tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -144,7 +144,7 @@ Vector ActionManager::pauseAllRunningActions() { Vector idsWithActions; - for (tHashElement *element=_targets; element != NULL; element = (tHashElement *)element->hh.next) + for (tHashElement *element=_targets; element != nullptr; element = (tHashElement *)element->hh.next) { if (! element->paused) { @@ -158,19 +158,19 @@ Vector ActionManager::pauseAllRunningActions() void ActionManager::resumeTargets(const Vector& targetsToResume) { - targetsToResume.forEach([this](Node* node){ + for(const auto &node : targetsToResume) { this->resumeTarget(node); - }); + } } // run void ActionManager::addAction(Action *action, Node *target, bool paused) { - CCASSERT(action != NULL, ""); - CCASSERT(target != NULL, ""); + CCASSERT(action != nullptr, ""); + CCASSERT(target != nullptr, ""); - tHashElement *element = NULL; + tHashElement *element = nullptr; // we should convert it to Object*, because we save it as Object* Object *tmp = target; HASH_FIND_PTR(_targets, &tmp, element); @@ -195,7 +195,7 @@ void ActionManager::addAction(Action *action, Node *target, bool paused) void ActionManager::removeAllActions() { - for (tHashElement *element = _targets; element != NULL; ) + for (tHashElement *element = _targets; element != nullptr; ) { auto target = element->target; element = (tHashElement*)element->hh.next; @@ -206,12 +206,12 @@ void ActionManager::removeAllActions() void ActionManager::removeAllActionsFromTarget(Node *target) { // explicit null handling - if (target == NULL) + if (target == nullptr) { return; } - tHashElement *element = NULL; + tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -240,12 +240,12 @@ void ActionManager::removeAllActionsFromTarget(Node *target) void ActionManager::removeAction(Action *action) { // explicit null handling - if (action == NULL) + if (action == nullptr) { return; } - tHashElement *element = NULL; + tHashElement *element = nullptr; Object *target = action->getOriginalTarget(); HASH_FIND_PTR(_targets, &target, element); if (element) @@ -265,9 +265,9 @@ void ActionManager::removeAction(Action *action) void ActionManager::removeActionByTag(int tag, Node *target) { CCASSERT(tag != Action::INVALID_TAG, ""); - CCASSERT(target != NULL, ""); + CCASSERT(target != nullptr, ""); - tHashElement *element = NULL; + tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); if (element) @@ -294,12 +294,12 @@ Action* ActionManager::getActionByTag(int tag, const Node *target) const { CCASSERT(tag != Action::INVALID_TAG, ""); - tHashElement *element = NULL; + tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); if (element) { - if (element->actions != NULL) + if (element->actions != nullptr) { auto limit = element->actions->num; for (int i = 0; i < limit; ++i) @@ -319,14 +319,14 @@ Action* ActionManager::getActionByTag(int tag, const Node *target) const // CCLOG("cocos2d : getActionByTag: Target not found"); } - return NULL; + return nullptr; } // 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 ssize_t ActionManager::getNumberOfRunningActionsInTarget(const Node *target) const { - tHashElement *element = NULL; + tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -339,7 +339,7 @@ ssize_t ActionManager::getNumberOfRunningActionsInTarget(const Node *target) con // main loop void ActionManager::update(float dt) { - for (tHashElement *elt = _targets; elt != NULL; ) + for (tHashElement *elt = _targets; elt != nullptr; ) { _currentTarget = elt; _currentTargetSalvaged = false; @@ -351,7 +351,7 @@ void ActionManager::update(float dt) _currentTarget->actionIndex++) { _currentTarget->currentAction = (Action*)_currentTarget->actions->arr[_currentTarget->actionIndex]; - if (_currentTarget->currentAction == NULL) + if (_currentTarget->currentAction == nullptr) { continue; } @@ -373,11 +373,11 @@ void ActionManager::update(float dt) Action *action = _currentTarget->currentAction; // Make currentAction nil to prevent removeAction from salvaging it. - _currentTarget->currentAction = NULL; + _currentTarget->currentAction = nullptr; removeAction(action); } - _currentTarget->currentAction = NULL; + _currentTarget->currentAction = nullptr; } } @@ -393,7 +393,7 @@ void ActionManager::update(float dt) } // issue #635 - _currentTarget = NULL; + _currentTarget = nullptr; } NS_CC_END diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 0f538e779c..406fadaeb9 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -72,7 +72,7 @@ public: If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target. When the target is paused, the queued actions won't be 'ticked'. */ - void addAction(Action *pAction, Node *target, bool paused); + void addAction(Action *action, Node *target, bool paused); /** Removes all actions from all the targets. */ @@ -85,7 +85,7 @@ public: /** Removes an action given an action reference. */ - void removeAction(Action *pAction); + void removeAction(Action *action); /** Removes an action given its tag and the target */ void removeActionByTag(int tag, Node *target); @@ -124,9 +124,9 @@ public: protected: // declared in ActionManager.m - void removeActionAtIndex(ssize_t index, struct _hashElement *pElement); - void deleteHashElement(struct _hashElement *pElement); - void actionAllocWithHashElement(struct _hashElement *pElement); + void removeActionAtIndex(ssize_t index, struct _hashElement *element); + void deleteHashElement(struct _hashElement *element); + void actionAllocWithHashElement(struct _hashElement *element); void update(float dt); protected: diff --git a/cocos/2d/CCActionPageTurn3D.cpp b/cocos/2d/CCActionPageTurn3D.cpp index 90ea5f6f28..1da881614d 100644 --- a/cocos/2d/CCActionPageTurn3D.cpp +++ b/cocos/2d/CCActionPageTurn3D.cpp @@ -28,21 +28,21 @@ NS_CC_BEGIN PageTurn3D* PageTurn3D::create(float duration, const Size& gridSize) { - PageTurn3D *pAction = new PageTurn3D(); + PageTurn3D *action = new PageTurn3D(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize)) + if (action->initWithDuration(duration, gridSize)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } PageTurn3D *PageTurn3D::clone() const diff --git a/cocos/2d/CCActionProgressTimer.cpp b/cocos/2d/CCActionProgressTimer.cpp index cf9e11f436..e5fa319875 100644 --- a/cocos/2d/CCActionProgressTimer.cpp +++ b/cocos/2d/CCActionProgressTimer.cpp @@ -31,20 +31,20 @@ NS_CC_BEGIN // implementation of ProgressTo -ProgressTo* ProgressTo::create(float duration, float fPercent) +ProgressTo* ProgressTo::create(float duration, float percent) { - ProgressTo *pProgressTo = new ProgressTo(); - pProgressTo->initWithDuration(duration, fPercent); - pProgressTo->autorelease(); + ProgressTo *progressTo = new ProgressTo(); + progressTo->initWithDuration(duration, percent); + progressTo->autorelease(); - return pProgressTo; + return progressTo; } -bool ProgressTo::initWithDuration(float duration, float fPercent) +bool ProgressTo::initWithDuration(float duration, float percent) { if (ActionInterval::initWithDuration(duration)) { - _to = fPercent; + _to = percent; return true; } @@ -87,21 +87,21 @@ void ProgressTo::update(float time) // implementation of ProgressFromTo -ProgressFromTo* ProgressFromTo::create(float duration, float fFromPercentage, float fToPercentage) +ProgressFromTo* ProgressFromTo::create(float duration, float fromPercentage, float toPercentage) { - ProgressFromTo *pProgressFromTo = new ProgressFromTo(); - pProgressFromTo->initWithDuration(duration, fFromPercentage, fToPercentage); - pProgressFromTo->autorelease(); + ProgressFromTo *progressFromTo = new ProgressFromTo(); + progressFromTo->initWithDuration(duration, fromPercentage, toPercentage); + progressFromTo->autorelease(); - return pProgressFromTo; + return progressFromTo; } -bool ProgressFromTo::initWithDuration(float duration, float fFromPercentage, float fToPercentage) +bool ProgressFromTo::initWithDuration(float duration, float fromPercentage, float toPercentage) { if (ActionInterval::initWithDuration(duration)) { - _to = fToPercentage; - _from = fFromPercentage; + _to = toPercentage; + _from = fromPercentage; return true; } diff --git a/cocos/2d/CCActionProgressTimer.h b/cocos/2d/CCActionProgressTimer.h index dc41237a48..bdb8ab03f9 100644 --- a/cocos/2d/CCActionProgressTimer.h +++ b/cocos/2d/CCActionProgressTimer.h @@ -42,7 +42,7 @@ class CC_DLL ProgressTo : public ActionInterval { public: /** Creates and initializes with a duration and a percent */ - static ProgressTo* create(float duration, float fPercent); + static ProgressTo* create(float duration, float percent); // // Overrides @@ -56,7 +56,7 @@ protected: ProgressTo() {} virtual ~ProgressTo() {} /** Initializes with a duration and a percent */ - bool initWithDuration(float duration, float fPercent); + bool initWithDuration(float duration, float percent); float _to; float _from; @@ -73,7 +73,7 @@ class CC_DLL ProgressFromTo : public ActionInterval { public: /** Creates and initializes the action with a duration, a "from" percentage and a "to" percentage */ - static ProgressFromTo* create(float duration, float fFromPercentage, float fToPercentage); + static ProgressFromTo* create(float duration, float fromPercentage, float toPercentage); // // Overrides @@ -87,7 +87,7 @@ protected: ProgressFromTo() {} virtual ~ProgressFromTo() {} /** Initializes the action with a duration, a "from" percentage and a "to" percentage */ - bool initWithDuration(float duration, float fFromPercentage, float fToPercentage); + bool initWithDuration(float duration, float fromPercentage, float toPercentage); float _to; float _from; diff --git a/cocos/2d/CCActionTiledGrid.cpp b/cocos/2d/CCActionTiledGrid.cpp index 269a798b1d..973634ace8 100644 --- a/cocos/2d/CCActionTiledGrid.cpp +++ b/cocos/2d/CCActionTiledGrid.cpp @@ -26,6 +26,7 @@ THE SOFTWARE. #include "CCDirector.h" #include "ccMacros.h" #include "CCGrid.h" +#include "CCNodeGrid.h" #include NS_CC_BEGIN @@ -39,31 +40,31 @@ struct Tile // implementation of ShakyTiles3D -ShakyTiles3D* ShakyTiles3D::create(float duration, const Size& gridSize, int nRange, bool bShakeZ) +ShakyTiles3D* ShakyTiles3D::create(float duration, const Size& gridSize, int range, bool shakeZ) { - ShakyTiles3D *pAction = new ShakyTiles3D(); + ShakyTiles3D *action = new ShakyTiles3D(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize, nRange, bShakeZ)) + if (action->initWithDuration(duration, gridSize, range, shakeZ)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } -bool ShakyTiles3D::initWithDuration(float duration, const Size& gridSize, int nRange, bool bShakeZ) +bool ShakyTiles3D::initWithDuration(float duration, const Size& gridSize, int range, bool shakeZ) { if (TiledGrid3DAction::initWithDuration(duration, gridSize)) { - _randrange = nRange; - _shakeZ = bShakeZ; + _randrange = range; + _shakeZ = shakeZ; return true; } @@ -118,32 +119,32 @@ void ShakyTiles3D::update(float time) // implementation of ShatteredTiles3D -ShatteredTiles3D* ShatteredTiles3D::create(float duration, const Size& gridSize, int nRange, bool bShatterZ) +ShatteredTiles3D* ShatteredTiles3D::create(float duration, const Size& gridSize, int range, bool shatterZ) { - ShatteredTiles3D *pAction = new ShatteredTiles3D(); + ShatteredTiles3D *action = new ShatteredTiles3D(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize, nRange, bShatterZ)) + if (action->initWithDuration(duration, gridSize, range, shatterZ)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } -bool ShatteredTiles3D::initWithDuration(float duration, const Size& gridSize, int nRange, bool bShatterZ) +bool ShatteredTiles3D::initWithDuration(float duration, const Size& gridSize, int range, bool shatterZ) { if (TiledGrid3DAction::initWithDuration(duration, gridSize)) { _once = false; - _randrange = nRange; - _shatterZ = bShatterZ; + _randrange = range; + _shatterZ = shatterZ; return true; } @@ -205,21 +206,21 @@ void ShatteredTiles3D::update(float time) ShuffleTiles* ShuffleTiles::create(float duration, const Size& gridSize, unsigned int seed) { - ShuffleTiles *pAction = new ShuffleTiles(); + ShuffleTiles *action = new ShuffleTiles(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize, seed)) + if (action->initWithDuration(duration, gridSize, seed)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } bool ShuffleTiles::initWithDuration(float duration, const Size& gridSize, unsigned int seed) @@ -227,8 +228,8 @@ bool ShuffleTiles::initWithDuration(float duration, const Size& gridSize, unsign if (TiledGrid3DAction::initWithDuration(duration, gridSize)) { _seed = seed; - _tilesOrder = NULL; - _tiles = NULL; + _tilesOrder = nullptr; + _tiles = nullptr; return true; } @@ -251,15 +252,15 @@ ShuffleTiles::~ShuffleTiles(void) CC_SAFE_DELETE_ARRAY(_tiles); } -void ShuffleTiles::shuffle(unsigned int *pArray, unsigned int nLen) +void ShuffleTiles::shuffle(unsigned int *array, unsigned int len) { int i; - for( i = nLen - 1; i >= 0; i-- ) + for( i = len - 1; i >= 0; i-- ) { unsigned int j = rand() % (i+1); - unsigned int v = pArray[i]; - pArray[i] = pArray[j]; - pArray[j] = v; + unsigned int v = array[i]; + array[i] = array[j]; + array[j] = v; } } @@ -279,7 +280,7 @@ void ShuffleTiles::placeTile(const Point& pos, Tile *t) { Quad3 coords = getOriginalTile(pos); - Point step = _target->getGrid()->getStep(); + Point step = _gridNodeTarget->getGrid()->getStep(); coords.bl.x += (int)(t->position.x * step.x); coords.bl.y += (int)(t->position.y * step.y); @@ -356,21 +357,21 @@ void ShuffleTiles::update(float time) FadeOutTRTiles* FadeOutTRTiles::create(float duration, const Size& gridSize) { - FadeOutTRTiles *pAction = new FadeOutTRTiles(); + FadeOutTRTiles *action = new FadeOutTRTiles(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize)) + if (action->initWithDuration(duration, gridSize)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } FadeOutTRTiles* FadeOutTRTiles::clone() const @@ -408,7 +409,7 @@ void FadeOutTRTiles::turnOffTile(const Point& pos) void FadeOutTRTiles::transformTile(const Point& pos, float distance) { Quad3 coords = getOriginalTile(pos); - Point step = _target->getGrid()->getStep(); + Point step = _gridNodeTarget->getGrid()->getStep(); coords.bl.x += (step.x / 2) * (1.0f - distance); coords.bl.y += (step.y / 2) * (1.0f - distance); @@ -454,21 +455,21 @@ void FadeOutTRTiles::update(float time) FadeOutBLTiles* FadeOutBLTiles::create(float duration, const Size& gridSize) { - FadeOutBLTiles *pAction = new FadeOutBLTiles(); + FadeOutBLTiles *action = new FadeOutBLTiles(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize)) + if (action->initWithDuration(duration, gridSize)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } FadeOutBLTiles* FadeOutBLTiles::clone() const @@ -495,21 +496,21 @@ float FadeOutBLTiles::testFunc(const Size& pos, float time) FadeOutUpTiles* FadeOutUpTiles::create(float duration, const Size& gridSize) { - FadeOutUpTiles *pAction = new FadeOutUpTiles(); + FadeOutUpTiles *action = new FadeOutUpTiles(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize)) + if (action->initWithDuration(duration, gridSize)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } FadeOutUpTiles* FadeOutUpTiles::clone() const @@ -535,7 +536,7 @@ float FadeOutUpTiles::testFunc(const Size& pos, float time) void FadeOutUpTiles::transformTile(const Point& pos, float distance) { Quad3 coords = getOriginalTile(pos); - Point step = _target->getGrid()->getStep(); + Point step = _gridNodeTarget->getGrid()->getStep(); coords.bl.y += (step.y / 2) * (1.0f - distance); coords.br.y += (step.y / 2) * (1.0f - distance); @@ -549,21 +550,21 @@ void FadeOutUpTiles::transformTile(const Point& pos, float distance) FadeOutDownTiles* FadeOutDownTiles::create(float duration, const Size& gridSize) { - FadeOutDownTiles *pAction = new FadeOutDownTiles(); + FadeOutDownTiles *action = new FadeOutDownTiles(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize)) + if (action->initWithDuration(duration, gridSize)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } FadeOutDownTiles* FadeOutDownTiles::clone() const @@ -604,21 +605,21 @@ TurnOffTiles* TurnOffTiles::create(float duration, const Size& gridSize) TurnOffTiles* TurnOffTiles::create(float duration, const Size& gridSize, unsigned int seed) { - TurnOffTiles *pAction = new TurnOffTiles(); + TurnOffTiles *action = new TurnOffTiles(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize, seed)) + if (action->initWithDuration(duration, gridSize, seed)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } bool TurnOffTiles::initWithDuration(float duration, const Size& gridSize, unsigned int seed) @@ -626,7 +627,7 @@ bool TurnOffTiles::initWithDuration(float duration, const Size& gridSize, unsign if (TiledGrid3DAction::initWithDuration(duration, gridSize)) { _seed = seed; - _tilesOrder = NULL; + _tilesOrder = nullptr; return true; } @@ -648,15 +649,15 @@ TurnOffTiles::~TurnOffTiles(void) CC_SAFE_DELETE_ARRAY(_tilesOrder); } -void TurnOffTiles::shuffle(unsigned int *pArray, unsigned int nLen) +void TurnOffTiles::shuffle(unsigned int *array, unsigned int len) { int i; - for (i = nLen - 1; i >= 0; i--) + for (i = len - 1; i >= 0; i--) { unsigned int j = rand() % (i+1); - unsigned int v = pArray[i]; - pArray[i] = pArray[j]; - pArray[j] = v; + unsigned int v = array[i]; + array[i] = array[j]; + array[j] = v; } } @@ -721,21 +722,21 @@ void TurnOffTiles::update(float time) WavesTiles3D* WavesTiles3D::create(float duration, const Size& gridSize, unsigned int waves, float amplitude) { - WavesTiles3D *pAction = new WavesTiles3D(); + WavesTiles3D *action = new WavesTiles3D(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize, waves, amplitude)) + if (action->initWithDuration(duration, gridSize, waves, amplitude)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } bool WavesTiles3D::initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude) @@ -786,21 +787,21 @@ void WavesTiles3D::update(float time) JumpTiles3D* JumpTiles3D::create(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude) { - JumpTiles3D *pAction = new JumpTiles3D(); + JumpTiles3D *action = new JumpTiles3D(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, gridSize, numberOfJumps, amplitude)) + if (action->initWithDuration(duration, gridSize, numberOfJumps, amplitude)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } bool JumpTiles3D::initWithDuration(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude) @@ -863,28 +864,28 @@ void JumpTiles3D::update(float time) SplitRows* SplitRows::create(float duration, unsigned int nRows) { - SplitRows *pAction = new SplitRows(); + SplitRows *action = new SplitRows(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, nRows)) + if (action->initWithDuration(duration, nRows)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } -bool SplitRows::initWithDuration(float duration, unsigned int nRows) +bool SplitRows::initWithDuration(float duration, unsigned int rows) { - _rows = nRows; + _rows = rows; - return TiledGrid3DAction::initWithDuration(duration, Size(1, nRows)); + return TiledGrid3DAction::initWithDuration(duration, Size(1, rows)); } SplitRows* SplitRows::clone() const @@ -927,29 +928,29 @@ void SplitRows::update(float time) // implementation of SplitCols -SplitCols* SplitCols::create(float duration, unsigned int nCols) +SplitCols* SplitCols::create(float duration, unsigned int cols) { - SplitCols *pAction = new SplitCols(); + SplitCols *action = new SplitCols(); - if (pAction) + if (action) { - if (pAction->initWithDuration(duration, nCols)) + if (action->initWithDuration(duration, cols)) { - pAction->autorelease(); + action->autorelease(); } else { - CC_SAFE_RELEASE_NULL(pAction); + CC_SAFE_RELEASE_NULL(action); } } - return pAction; + return action; } -bool SplitCols::initWithDuration(float duration, unsigned int nCols) +bool SplitCols::initWithDuration(float duration, unsigned int cols) { - _cols = nCols; - return TiledGrid3DAction::initWithDuration(duration, Size(nCols, 1)); + _cols = cols; + return TiledGrid3DAction::initWithDuration(duration, Size(cols, 1)); } SplitCols* SplitCols::clone() const diff --git a/cocos/2d/CCActionTiledGrid.h b/cocos/2d/CCActionTiledGrid.h index ca4dd786a6..a12e65fb4e 100644 --- a/cocos/2d/CCActionTiledGrid.h +++ b/cocos/2d/CCActionTiledGrid.h @@ -39,7 +39,7 @@ class CC_DLL ShakyTiles3D : public TiledGrid3DAction { public: /** creates the action with a range, whether or not to shake Z vertices, a grid size, and duration */ - static ShakyTiles3D* create(float duration, const Size& gridSize, int nRange, bool bShakeZ); + static ShakyTiles3D* create(float duration, const Size& gridSize, int range, bool shakeZ); // Override virtual ShakyTiles3D* clone() const override; @@ -49,7 +49,7 @@ protected: ShakyTiles3D() {} virtual ~ShakyTiles3D() {} /** initializes the action with a range, whether or not to shake Z vertices, a grid size, and duration */ - bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShakeZ); + bool initWithDuration(float duration, const Size& gridSize, int range, bool shakeZ); int _randrange; bool _shakeZ; @@ -63,7 +63,7 @@ class CC_DLL ShatteredTiles3D : public TiledGrid3DAction { public: /** creates the action with a range, whether of not to shatter Z vertices, a grid size and duration */ - static ShatteredTiles3D* create(float duration, const Size& gridSize, int nRange, bool bShatterZ); + static ShatteredTiles3D* create(float duration, const Size& gridSize, int range, bool shatterZ); // Override virtual ShatteredTiles3D* clone() const override; @@ -73,7 +73,7 @@ protected: ShatteredTiles3D() {} virtual ~ShatteredTiles3D() {} /** initializes the action with a range, whether or not to shatter Z vertices, a grid size and duration */ - bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShatterZ); + bool initWithDuration(float duration, const Size& gridSize, int range, bool shatterZ); int _randrange; bool _once; @@ -93,7 +93,7 @@ public: /** creates the action with a random seed, the grid size and the duration */ static ShuffleTiles* create(float duration, const Size& gridSize, unsigned int seed); - void shuffle(unsigned int *array, unsigned int nLen); + void shuffle(unsigned int *array, unsigned int len); Size getDelta(const Size& pos) const; void placeTile(const Point& pos, Tile *t); @@ -219,7 +219,7 @@ public: /** creates the action with a random seed, the grid size and the duration */ static TurnOffTiles* create(float duration, const Size& gridSize, unsigned int seed); - void shuffle(unsigned int *pArray, unsigned int nLen); + void shuffle(unsigned int *array, unsigned int len); void turnOnTile(const Point& pos); void turnOffTile(const Point& pos); @@ -251,11 +251,11 @@ public: /** waves amplitude */ inline float getAmplitude(void) const { return _amplitude; } - inline void setAmplitude(float fAmplitude) { _amplitude = fAmplitude; } + inline void setAmplitude(float amplitude) { _amplitude = amplitude; } /** waves amplitude rate */ inline float getAmplitudeRate(void) const { return _amplitudeRate; } - inline void setAmplitudeRate(float fAmplitudeRate) { _amplitudeRate = fAmplitudeRate; } + inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; } // Override virtual WavesTiles3D* clone() const override; @@ -286,11 +286,11 @@ public: /** amplitude of the sin*/ inline float getAmplitude(void) const { return _amplitude; } - inline void setAmplitude(float fAmplitude) { _amplitude = fAmplitude; } + inline void setAmplitude(float amplitude) { _amplitude = amplitude; } /** amplitude rate */ inline float getAmplitudeRate(void) const { return _amplitudeRate; } - inline void setAmplitudeRate(float fAmplitudeRate) { _amplitudeRate = fAmplitudeRate; } + inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; } // Override virtual JumpTiles3D* clone() const override; @@ -315,7 +315,7 @@ class CC_DLL SplitRows : public TiledGrid3DAction { public : /** creates the action with the number of rows to split and the duration */ - static SplitRows* create(float duration, unsigned int nRows); + static SplitRows* create(float duration, unsigned int rows); // Overrides virtual SplitRows* clone() const override; @@ -326,7 +326,7 @@ protected: SplitRows() {} virtual ~SplitRows() {} /** initializes the action with the number of rows to split and the duration */ - bool initWithDuration(float duration, unsigned int nRows); + bool initWithDuration(float duration, unsigned int rows); unsigned int _rows; Size _winSize; @@ -340,7 +340,7 @@ class CC_DLL SplitCols : public TiledGrid3DAction { public: /** creates the action with the number of columns to split and the duration */ - static SplitCols* create(float duration, unsigned int nCols); + static SplitCols* create(float duration, unsigned int cols); // Overrides virtual SplitCols* clone() const override; @@ -351,7 +351,7 @@ protected: SplitCols() {} virtual ~SplitCols() {} /** initializes the action with the number of columns to split and the duration */ - bool initWithDuration(float duration, unsigned int nCols); + bool initWithDuration(float duration, unsigned int cols); unsigned int _cols; Size _winSize; diff --git a/cocos/2d/CCActionTween.cpp b/cocos/2d/CCActionTween.cpp index 67a4f3ce38..a54f562713 100644 --- a/cocos/2d/CCActionTween.cpp +++ b/cocos/2d/CCActionTween.cpp @@ -29,21 +29,21 @@ NS_CC_BEGIN ActionTween* ActionTween::create(float aDuration, const std::string& key, float from, float to) { - ActionTween* pRet = new ActionTween(); - if (pRet && pRet->initWithDuration(aDuration, key, from, to)) + ActionTween* ret = new ActionTween(); + if (ret && ret->initWithDuration(aDuration, key, from, to)) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } -bool ActionTween::initWithDuration(float aDuration, const std::string& key, float from, float to) +bool ActionTween::initWithDuration(float duration, const std::string& key, float from, float to) { - if (ActionInterval::initWithDuration(aDuration)) + if (ActionInterval::initWithDuration(duration)) { _key = key; _to = to; diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 1f742cf6db..e79db07267 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -47,7 +47,7 @@ AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnit } AnimationFrame::AnimationFrame() -: _spriteFrame(NULL) +: _spriteFrame(nullptr) , _delayUnits(0.0f) { @@ -85,28 +85,28 @@ AnimationFrame* AnimationFrame::clone() const Animation* Animation::create(void) { - Animation *pAnimation = new Animation(); - pAnimation->init(); - pAnimation->autorelease(); + Animation *animation = new Animation(); + animation->init(); + animation->autorelease(); - return pAnimation; + return animation; } Animation* Animation::createWithSpriteFrames(const Vector& frames, float delay/* = 0.0f*/) { - Animation *pAnimation = new Animation(); - pAnimation->initWithSpriteFrames(frames, delay); - pAnimation->autorelease(); + Animation *animation = new Animation(); + animation->initWithSpriteFrames(frames, delay); + animation->autorelease(); - return pAnimation; + return animation; } Animation* Animation::create(const Vector& arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops /* = 1 */) { - Animation *pAnimation = new Animation(); - pAnimation->initWithAnimationFrames(arrayOfAnimationFrameNames, delayPerUnit, loops); - pAnimation->autorelease(); - return pAnimation; + Animation *animation = new Animation(); + animation->initWithAnimationFrames(arrayOfAnimationFrameNames, delayPerUnit, loops); + animation->autorelease(); + return animation; } bool Animation::init() @@ -175,14 +175,14 @@ void Animation::addSpriteFrameWithFile(const std::string& filename) Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); - SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect); - addSpriteFrame(pFrame); + SpriteFrame *frame = SpriteFrame::createWithTexture(texture, rect); + addSpriteFrame(frame); } void Animation::addSpriteFrameWithTexture(Texture2D *pobTexture, const Rect& rect) { - SpriteFrame *pFrame = SpriteFrame::createWithTexture(pobTexture, rect); - addSpriteFrame(pFrame); + SpriteFrame *frame = SpriteFrame::createWithTexture(pobTexture, rect); + addSpriteFrame(frame); } float Animation::getDuration(void) const diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 99fae8882d..9dddeb6fcc 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -157,7 +157,7 @@ public: /** Adds a SpriteFrame to a Animation. The frame will be added with one "delay unit". */ - void addSpriteFrame(SpriteFrame *pFrame); + void addSpriteFrame(SpriteFrame *frame); /** Adds a frame with an image filename. Internally it will create a SpriteFrame and it will add it. The frame will be added with one "delay unit". diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 85d56c27c9..59d9144252 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -35,22 +35,22 @@ using namespace std; NS_CC_BEGIN -AnimationCache* AnimationCache::s_pSharedAnimationCache = NULL; +AnimationCache* AnimationCache::s_sharedAnimationCache = nullptr; AnimationCache* AnimationCache::getInstance() { - if (! s_pSharedAnimationCache) + if (! s_sharedAnimationCache) { - s_pSharedAnimationCache = new AnimationCache(); - s_pSharedAnimationCache->init(); + s_sharedAnimationCache = new AnimationCache(); + s_sharedAnimationCache->init(); } - return s_pSharedAnimationCache; + return s_sharedAnimationCache; } void AnimationCache::destroyInstance() { - CC_SAFE_RELEASE_NULL(s_pSharedAnimationCache); + CC_SAFE_RELEASE_NULL(s_sharedAnimationCache); } bool AnimationCache::init() @@ -102,7 +102,8 @@ void AnimationCache::parseVersion1(const ValueMap& animations) continue; } - Vector frames(static_cast(frameNames.size())); + ssize_t frameNameSize = frameNames.size(); + Vector frames(frameNameSize); for (auto& frameName : frameNames) { @@ -118,12 +119,12 @@ void AnimationCache::parseVersion1(const ValueMap& animations) frames.pushBack(animFrame); } - if ( frames.size() == 0 ) + if ( frames.empty() ) { 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.size() != frameNames.size() ) + else if ( frames.size() != frameNameSize ) { 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()); } @@ -203,9 +204,9 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary) version = properties.at("format").asInt(); const ValueVector& spritesheets = properties.at("spritesheets").asValueVector(); - std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){ + for(const auto &value : spritesheets) { SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString()); - }); + } } switch (version) { diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index cfc48ababb..6e60201882 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -120,7 +120,7 @@ private: private: Map _animations; - static AnimationCache* s_pSharedAnimationCache; + static AnimationCache* s_sharedAnimationCache; }; // end of sprite_nodes group diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 44c73d3149..fc29683d90 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -33,6 +33,8 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "CCDirector.h" #include "TransformUtils.h" +#include "CCRenderer.h" +#include "renderer/CCQuadCommand.h" // external #include "kazmath/GL/matrix.h" @@ -48,7 +50,7 @@ AtlasNode::AtlasNode() , _itemsPerColumn(0) , _itemWidth(0) , _itemHeight(0) -, _textureAtlas(NULL) +, _textureAtlas(nullptr) , _isOpacityModifyRGB(false) , _quadsToDraw(0) , _uniformColor(0) @@ -63,14 +65,14 @@ AtlasNode::~AtlasNode() AtlasNode * AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) { - AtlasNode * pRet = new AtlasNode(); - if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) + AtlasNode * ret = new AtlasNode(); + if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); - return NULL; + CC_SAFE_DELETE(ret); + return nullptr; } bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) @@ -137,14 +139,29 @@ void AtlasNode::updateAtlasValues() // AtlasNode - draw void AtlasNode::draw(void) { - CC_NODE_DRAW_SETUP(); +// CC_NODE_DRAW_SETUP(); +// +// GL::blendFunc( _blendFunc.src, _blendFunc.dst ); +// +// GLfloat colors[4] = {_displayedColor.r / 255.0f, _displayedColor.g / 255.0f, _displayedColor.b / 255.0f, _displayedOpacity / 255.0f}; +// getShaderProgram()->setUniformLocationWith4fv(_uniformColor, colors, 1); +// +// _textureAtlas->drawNumberOfQuads(_quadsToDraw, 0); - GL::blendFunc( _blendFunc.src, _blendFunc.dst ); - GLfloat colors[4] = {_displayedColor.r / 255.0f, _displayedColor.g / 255.0f, _displayedColor.b / 255.0f, _displayedOpacity / 255.0f}; - getShaderProgram()->setUniformLocationWith4fv(_uniformColor, colors, 1); + auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); + + _quadCommand.init(0, + _vertexZ, + _textureAtlas->getTexture()->getName(), + shader, + _blendFunc, + _textureAtlas->getQuads(), + _textureAtlas->getTotalQuads(), + _modelViewTransform); + + Director::getInstance()->getRenderer()->addCommand(&_quadCommand); - _textureAtlas->drawNumberOfQuads(_quadsToDraw, 0); } // AtlasNode - RGBA protocol @@ -155,7 +172,7 @@ const Color3B& AtlasNode::getColor() const { return _colorUnmodified; } - return NodeRGBA::getColor(); + return Node::getColor(); } void AtlasNode::setColor(const Color3B& color3) @@ -169,22 +186,22 @@ void AtlasNode::setColor(const Color3B& color3) tmp.g = tmp.g * _displayedOpacity/255; tmp.b = tmp.b * _displayedOpacity/255; } - NodeRGBA::setColor(tmp); + Node::setColor(tmp); } void AtlasNode::setOpacity(GLubyte opacity) { - NodeRGBA::setOpacity(opacity); + Node::setOpacity(opacity); // special opacity for premultiplied textures if( _isOpacityModifyRGB ) this->setColor(_colorUnmodified); } -void AtlasNode::setOpacityModifyRGB(bool bValue) +void AtlasNode::setOpacityModifyRGB(bool value) { Color3B oldColor = this->getColor(); - _isOpacityModifyRGB = bValue; + _isOpacityModifyRGB = value; this->setColor(oldColor); } @@ -198,9 +215,9 @@ void AtlasNode::updateOpacityModifyRGB() _isOpacityModifyRGB = _textureAtlas->getTexture()->hasPremultipliedAlpha(); } -void AtlasNode::setIgnoreContentScaleFactor(bool bIgnoreContentScaleFactor) +void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor) { - _ignoreContentScaleFactor = bIgnoreContentScaleFactor; + _ignoreContentScaleFactor = ignoreContentScaleFactor; } // AtlasNode - CocosNodeTexture protocol @@ -245,14 +262,14 @@ TextureAtlas * AtlasNode::getTextureAtlas() const return _textureAtlas; } -int AtlasNode::getQuadsToDraw() const +ssize_t AtlasNode::getQuadsToDraw() const { return _quadsToDraw; } -void AtlasNode::setQuadsToDraw(int uQuadsToDraw) +void AtlasNode::setQuadsToDraw(ssize_t quadsToDraw) { - _quadsToDraw = uQuadsToDraw; + _quadsToDraw = quadsToDraw; } NS_CC_END diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 676458360e..71d013a907 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -30,6 +30,7 @@ THE SOFTWARE. #include "CCNode.h" #include "CCProtocols.h" #include "ccTypes.h" +#include "renderer/CCQuadCommand.h" NS_CC_BEGIN @@ -48,7 +49,7 @@ If you are going to render a TextureAtlas consider subclassing AtlasNode (or a s All features from Node are valid, plus the following features: - opacity and RGB colors */ -class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol +class CC_DLL AtlasNode : public Node, public TextureProtocol { public: /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ @@ -62,8 +63,8 @@ public: void setTextureAtlas(TextureAtlas* textureAtlas); TextureAtlas* getTextureAtlas() const; - void setQuadsToDraw(int quadsToDraw); - int getQuadsToDraw() const; + void setQuadsToDraw(ssize_t quadsToDraw); + ssize_t getQuadsToDraw() const; // Overrides @@ -125,11 +126,13 @@ protected: BlendFunc _blendFunc; // quads to draw - int _quadsToDraw; + ssize_t _quadsToDraw; // color uniform GLint _uniformColor; // This varible is only used for LabelAtlas FPS display. So plz don't modify its value. bool _ignoreContentScaleFactor; + // quad command + QuadCommand _quadCommand; private: CC_DISALLOW_COPY_AND_ASSIGN(AtlasNode); diff --git a/cocos/2d/CCCamera.cpp b/cocos/2d/CCCamera.cpp deleted file mode 100644 index 9da9cb7d49..0000000000 --- a/cocos/2d/CCCamera.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada - -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 "CCCamera.h" -#include "CCString.h" -#include "CCGL.h" - -#include "CCDrawingPrimitives.h" -#include "CCDirector.h" -#include "kazmath/GL/matrix.h" - -using namespace std; - -NS_CC_BEGIN - -Camera::Camera(void) -{ - init(); -} - -Camera::~Camera(void) -{ -} - -std::string Camera::getDescription() const -{ - return String::createWithFormat("", _centerX, _centerY, _centerZ)->getCString(); -} - -void Camera::init(void) -{ - restore(); -} - -void Camera::restore(void) -{ - _eyeX = _eyeY = 0.0f; - _eyeZ = getZEye(); - - _centerX = _centerY = _centerZ = 0.0f; - - _upX = 0.0f; - _upY = 1.0f; - _upZ = 0.0f; - - kmMat4Identity(&_lookupMatrix); - - _dirty = false; -} - -void Camera::locate(void) -{ - if (_dirty) - { - kmVec3 eye, center, up; - - kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ); - kmVec3Fill(¢er, _centerX, _centerY, _centerZ); - - kmVec3Fill(&up, _upX, _upY, _upZ); - kmMat4LookAt(&_lookupMatrix, &eye, ¢er, &up); - - _dirty = false; - } - kmGLMultMatrix(&_lookupMatrix); -} - -float Camera::getZEye(void) -{ - return FLT_EPSILON; -} - -void Camera::setEye(float eyeX, float eyeY, float eyeZ) -{ - _eyeX = eyeX; - _eyeY = eyeY; - _eyeZ = eyeZ; - - _dirty = true; -} - -void Camera::setCenter(float centerX, float centerY, float centerZ) -{ - _centerX = centerX; - _centerY = centerY; - _centerZ = centerZ; - - _dirty = true; -} - -void Camera::setUp(float upX, float upY, float upZ) -{ - _upX = upX; - _upY = upY; - _upZ = upZ; - - _dirty = true; -} - -void Camera::getEye(float *eyeX, float *eyeY, float *eyeZ) const -{ - *eyeX = _eyeX; - *eyeY = _eyeY; - *eyeZ = _eyeZ; -} - -void Camera::getCenter(float *centerX, float *centerY, float *centerZ) const -{ - *centerX = _centerX; - *centerY = _centerY; - *centerZ = _centerZ; -} - -void Camera::getUp(float *upX, float *upY, float *upZ) const -{ - *upX = _upX; - *upY = _upY; - *upZ = _upZ; -} - -NS_CC_END - diff --git a/cocos/2d/CCCamera.h b/cocos/2d/CCCamera.h deleted file mode 100644 index 916ddaebae..0000000000 --- a/cocos/2d/CCCamera.h +++ /dev/null @@ -1,186 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2011 Zynga Inc. - -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 __COCOS2DX_CAMERA_H__ -#define __COCOS2DX_CAMERA_H__ - -#include - -#include "CCObject.h" -#include "ccMacros.h" -#include "kazmath/mat4.h" - - -NS_CC_BEGIN - -/** - * @addtogroup base_nodes - * @{ - */ - -/** -A Camera is used in every Node. -Useful to look at the object from different views. -The OpenGL gluLookAt() function is used to locate the -camera. - -If the object is transformed by any of the scale, rotation or -position attributes, then they will override the camera. - -IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both. -World coordinates won't work if you use the camera. - -Limitations: - -- Some nodes, like ParallaxNode, Particle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors) -using the camera. - -- It doesn't work on batched nodes like Sprite objects when they are parented to a SpriteBatchNode object. - -- It is recommended to use it ONLY if you are going to create 3D effects. For 2D effects, use the action Follow or position/scale/rotate. - -*/ -class CC_DLL Camera : public Object -{ -public: - /** returns the Z eye */ - static float getZEye(); - /** - * @js ctor - */ - Camera(); - /** - * @js NA - * @lua NA - */ - ~Camera(); - - void init(); - /** - * @js NA - * @lua NA - */ - virtual std::string getDescription() const; - - /** sets the dirty value */ - inline void setDirty(bool value) { _dirty = value; } - /** get the dirty value */ - inline bool isDirty() const { return _dirty; } - - /** sets the camera in the default position */ - void restore(); - /** Sets the camera using gluLookAt using its eye, center and up_vector */ - void locate(); - /** sets the eye values in points */ - void setEye(float eyeX, float eyeY, float eyeZ); - /** - @deprecated. Use setEye() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void setEyeXYZ(float eyeX, float eyeY, float eyeZ){ setEye(eyeX, eyeY, eyeZ);} - /** sets the center values in points */ - void setCenter(float centerX, float centerY, float centerZ); - /** - @deprecated. Use setCenter() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void setCenterXYZ(float centerX, float centerY, float centerZ){ setCenter(centerX,centerY,centerZ);} - /** sets the up values */ - void setUp(float upX, float upY, float upZ); - /** - @deprecated. Use setUp() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void setUpXYZ(float upX, float upY, float upZ){ setUp(upX,upY,upZ); } - - /** get the eye vector values in points - * @code - * when this function bound to js or lua,the input params are changed - * in js: var getEye() - * in lua:local getEye() - * @endcode - */ - void getEye(float *eyeX, float *eyeY, float *eyeZ) const; - /** - @deprecated. Use getEye() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void getEyeXYZ(float *eyeX, float *eyeY, float *eyeZ) const { getEye(eyeX, eyeY, eyeZ); } - /** get the center vector values int points - * when this function bound to js or lua,the input params are changed - * in js: var getCenter() - * in lua:local getCenter() - */ - void getCenter(float *centerX, float *centerY, float *centerZ) const; - /** - @deprecated. Use getCenter() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void getCenterXYZ(float *centerX, float *centerY, float *centerZ) const{ getCenter(centerX,centerY,centerZ); } - /** get the up vector values - * when this function bound to js or lua,the input params are changed - * in js: var getUp() - * in lua:local getUp() - */ - void getUp(float *upX, float *upY, float *upZ) const; - /** - @deprecated. Use getUp() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void getUpXYZ(float *upX, float *upY, float *upZ) const{ getUp(upX, upY, upZ); } - -protected: - float _eyeX; - float _eyeY; - float _eyeZ; - - float _centerX; - float _centerY; - float _centerZ; - - float _upX; - float _upY; - float _upZ; - - bool _dirty; - kmMat4 _lookupMatrix; - -private: - DISALLOW_COPY_AND_ASSIGN(Camera); -}; - -// end of base_node group -/// @} - -NS_CC_END - -#endif // __COCOS2DX_CAMERA_H__ diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index f39131a4ac..d1f9c236e4 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -31,25 +31,47 @@ #include "CCShaderCache.h" #include "CCDirector.h" #include "CCDrawingPrimitives.h" +#include "CCRenderer.h" +#include "CCGroupCommand.h" +#include "CCCustomCommand.h" NS_CC_BEGIN static GLint g_sStencilBits = -1; +// store the current stencil layer (position in the stencil buffer), +// this will allow nesting up to n ClippingNode, +// where n is the number of bits of the stencil buffer. +static GLint s_layer = -1; static void setProgram(Node *n, GLProgram *p) { n->setShaderProgram(p); - n->getChildren().forEach([p](Node* child){ + auto& children = n->getChildren(); + for(const auto &child : children) { setProgram(child, p); - }); + } } ClippingNode::ClippingNode() -: _stencil(NULL) +: _stencil(nullptr) , _alphaThreshold(0.0f) , _inverted(false) -{} +, _currentStencilEnabled(GL_FALSE) +, _currentStencilWriteMask(~0) +, _currentStencilFunc(GL_ALWAYS) +, _currentStencilRef(0) +, _currentStencilValueMask(~0) +, _currentStencilFail(GL_KEEP) +, _currentStencilPassDepthFail(GL_KEEP) +, _currentStencilPassDepthPass(GL_KEEP) +, _currentDepthWriteMask(GL_TRUE) +, _currentAlphaTestEnabled(GL_FALSE) +, _currentAlphaTestFunc(GL_ALWAYS) +, _currentAlphaTestRef(1) +{ + +} ClippingNode::~ClippingNode() { @@ -58,37 +80,37 @@ ClippingNode::~ClippingNode() ClippingNode* ClippingNode::create() { - ClippingNode *pRet = new ClippingNode(); - if (pRet && pRet->init()) + ClippingNode *ret = new ClippingNode(); + if (ret && ret->init()) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } ClippingNode* ClippingNode::create(Node *pStencil) { - ClippingNode *pRet = new ClippingNode(); - if (pRet && pRet->init(pStencil)) + ClippingNode *ret = new ClippingNode(); + if (ret && ret->init(pStencil)) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } bool ClippingNode::init() { - return init(NULL); + return init(nullptr); } bool ClippingNode::init(Node *stencil) @@ -178,96 +200,136 @@ void ClippingNode::drawFullScreenQuadClearStencil() void ClippingNode::visit() { - // if stencil buffer disabled - if (g_sStencilBits < 1) - { - // draw everything, as if there where no stencil - Node::visit(); + if(!_visible) return; - } - // return fast (draw nothing, or draw everything if in inverted mode) if: - // - nil stencil node - // - or stencil node invisible: - if (!_stencil || !_stencil->isVisible()) + kmGLPushMatrix(); + transform(); + //Add group command + + Renderer* renderer = Director::getInstance()->getRenderer(); + + _groupCommand.init(0,_vertexZ); + renderer->addCommand(&_groupCommand); + + renderer->pushGroup(_groupCommand.getRenderQueueID()); + + _beforeVisitCmd.init(0,_vertexZ); + _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); + renderer->addCommand(&_beforeVisitCmd); + + _stencil->visit(); + + _afterDrawStencilCmd.init(0,_vertexZ); + _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); + renderer->addCommand(&_afterDrawStencilCmd); + + int i = 0; + + if(!_children.empty()) { - if (_inverted) + sortAllChildren(); + // draw children zOrder < 0 + for( ; i < _children.size(); i++ ) { - // draw everything - Node::visit(); - } - return; - } - - // store the current stencil layer (position in the stencil buffer), - // this will allow nesting up to n ClippingNode, - // where n is the number of bits of the stencil buffer. - static GLint layer = -1; - - // all the _stencilBits are in use? - if (layer + 1 == g_sStencilBits) - { - // warn once - static bool once = true; - if (once) - { - char warning[200] = {0}; - snprintf(warning, sizeof(warning), "Nesting more than %d stencils is not supported. Everything will be drawn without stencil for this node and its childs.", g_sStencilBits); - CCLOG("%s", warning); + auto node = _children.at(i); - once = false; + if ( node && node->getZOrder() < 0 ) + node->visit(); + else + break; } - // draw everything, as if there where no stencil - Node::visit(); - return; + // self draw + this->draw(); + + for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) + (*it)->visit(); } + else + { + this->draw(); + } + + _afterVisitCmd.init(0,_vertexZ); + _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); + renderer->addCommand(&_afterVisitCmd); + + renderer->popGroup(); + kmGLPopMatrix(); +} + +Node* ClippingNode::getStencil() const +{ + return _stencil; +} + +void ClippingNode::setStencil(Node *stencil) +{ + CC_SAFE_RELEASE(_stencil); + _stencil = stencil; + CC_SAFE_RETAIN(_stencil); +} + +GLfloat ClippingNode::getAlphaThreshold() const +{ + return _alphaThreshold; +} + +void ClippingNode::setAlphaThreshold(GLfloat alphaThreshold) +{ + _alphaThreshold = alphaThreshold; +} + +bool ClippingNode::isInverted() const +{ + return _inverted; +} + +void ClippingNode::setInverted(bool inverted) +{ + _inverted = inverted; +} + +void ClippingNode::onBeforeVisit() +{ /////////////////////////////////// // INIT - + // increment the current layer - layer++; - + s_layer++; + // mask of the current layer (ie: for layer 3: 00000100) - GLint mask_layer = 0x1 << layer; + GLint mask_layer = 0x1 << s_layer; // mask of all layers less than the current (ie: for layer 3: 00000011) GLint mask_layer_l = mask_layer - 1; // mask of all layers less than or equal to the current (ie: for layer 3: 00000111) - GLint mask_layer_le = mask_layer | mask_layer_l; - + _mask_layer_le = mask_layer | mask_layer_l; + // manually save the stencil state - GLboolean currentStencilEnabled = GL_FALSE; - GLuint currentStencilWriteMask = ~0; - GLenum currentStencilFunc = GL_ALWAYS; - GLint currentStencilRef = 0; - GLuint currentStencilValueMask = ~0; - GLenum currentStencilFail = GL_KEEP; - GLenum currentStencilPassDepthFail = GL_KEEP; - GLenum currentStencilPassDepthPass = GL_KEEP; - currentStencilEnabled = glIsEnabled(GL_STENCIL_TEST); - glGetIntegerv(GL_STENCIL_WRITEMASK, (GLint *)¤tStencilWriteMask); - glGetIntegerv(GL_STENCIL_FUNC, (GLint *)¤tStencilFunc); - glGetIntegerv(GL_STENCIL_REF, ¤tStencilRef); - glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)¤tStencilValueMask); - glGetIntegerv(GL_STENCIL_FAIL, (GLint *)¤tStencilFail); - glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, (GLint *)¤tStencilPassDepthFail); - glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, (GLint *)¤tStencilPassDepthPass); - + + _currentStencilEnabled = glIsEnabled(GL_STENCIL_TEST); + glGetIntegerv(GL_STENCIL_WRITEMASK, (GLint *)&_currentStencilWriteMask); + glGetIntegerv(GL_STENCIL_FUNC, (GLint *)&_currentStencilFunc); + glGetIntegerv(GL_STENCIL_REF, &_currentStencilRef); + glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&_currentStencilValueMask); + glGetIntegerv(GL_STENCIL_FAIL, (GLint *)&_currentStencilFail); + glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, (GLint *)&_currentStencilPassDepthFail); + glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, (GLint *)&_currentStencilPassDepthPass); + // enable stencil use glEnable(GL_STENCIL_TEST); // check for OpenGL error while enabling stencil test CHECK_GL_ERROR_DEBUG(); - + // all bits on the stencil buffer are readonly, except the current layer bit, // this means that operation like glClear or glStencilOp will be masked with this value glStencilMask(mask_layer); - + // manually save the depth test state - //GLboolean currentDepthTestEnabled = GL_TRUE; - GLboolean currentDepthWriteMask = GL_TRUE; - //currentDepthTestEnabled = glIsEnabled(GL_DEPTH_TEST); - glGetBooleanv(GL_DEPTH_WRITEMASK, ¤tDepthWriteMask); - + + glGetBooleanv(GL_DEPTH_WRITEMASK, &_currentDepthWriteMask); + // disable depth test while drawing the stencil //glDisable(GL_DEPTH_TEST); // disable update to the depth buffer while drawing the stencil, @@ -275,10 +337,10 @@ void ClippingNode::visit() // it should never prevent something else to be drawn, // only disabling depth buffer update should do glDepthMask(GL_FALSE); - + /////////////////////////////////// // CLEAR STENCIL BUFFER - + // manually clear the stencil buffer by drawing a fullscreen rectangle on it // setup the stencil test func like this: // for each pixel in the fullscreen rectangle @@ -287,14 +349,14 @@ void ClippingNode::visit() // if in inverted mode: set the current layer value to 1 in the stencil buffer glStencilFunc(GL_NEVER, mask_layer, mask_layer); glStencilOp(!_inverted ? GL_ZERO : GL_REPLACE, GL_KEEP, GL_KEEP); - + // draw a fullscreen solid rectangle to clear the stencil buffer //ccDrawSolidRect(Point::ZERO, ccpFromSize([[Director sharedDirector] winSize]), Color4F(1, 1, 1, 1)); drawFullScreenQuadClearStencil(); - + /////////////////////////////////// // DRAW CLIPPING STENCIL - + // setup the stencil test func like this: // for each pixel in the stencil node // never draw it into the frame buffer @@ -302,20 +364,15 @@ void ClippingNode::visit() // if in inverted mode: set the current layer value to 0 in the stencil buffer glStencilFunc(GL_NEVER, mask_layer, mask_layer); glStencilOp(!_inverted ? GL_REPLACE : GL_ZERO, GL_KEEP, GL_KEEP); - + // enable alpha test only if the alpha threshold < 1, // indeed if alpha threshold == 1, every pixel will be drawn anyways -#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) - GLboolean currentAlphaTestEnabled = GL_FALSE; - GLenum currentAlphaTestFunc = GL_ALWAYS; - GLclampf currentAlphaTestRef = 1; -#endif if (_alphaThreshold < 1) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) // manually save the alpha test state - currentAlphaTestEnabled = glIsEnabled(GL_ALPHA_TEST); - glGetIntegerv(GL_ALPHA_TEST_FUNC, (GLint *)¤tAlphaTestFunc); - glGetFloatv(GL_ALPHA_TEST_REF, ¤tAlphaTestRef); + _currentAlphaTestEnabled = glIsEnabled(GL_ALPHA_TEST); + glGetIntegerv(GL_ALPHA_TEST_FUNC, (GLint *)&_currentAlphaTestFunc); + glGetFloatv(GL_ALPHA_TEST_REF, &_currentAlphaTestRef); // enable alpha testing glEnable(GL_ALPHA_TEST); // check for OpenGL error while enabling alpha test @@ -333,27 +390,22 @@ void ClippingNode::visit() // we need to recursively apply this shader to all the nodes in the stencil node // XXX: we should have a way to apply shader to all nodes without having to do this setProgram(_stencil, program); - + #endif } - - // draw the stencil node as if it was one of our child - // (according to the stencil test func/op and alpha (or alpha shader) test) - kmGLPushMatrix(); - transform(); - if (_stencil != nullptr) - { - _stencil->visit(); - } - kmGLPopMatrix(); - + + //Draw _stencil +} + +void ClippingNode::onAfterDrawStencil() +{ // restore alpha test state if (_alphaThreshold < 1) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) // manually restore the alpha test state - glAlphaFunc(currentAlphaTestFunc, currentAlphaTestRef); - if (!currentAlphaTestEnabled) + glAlphaFunc(_currentAlphaTestFunc, _currentAlphaTestRef); + if (!_currentAlphaTestEnabled) { glDisable(GL_ALPHA_TEST); } @@ -361,74 +413,45 @@ void ClippingNode::visit() // XXX: we need to find a way to restore the shaders of the stencil node and its childs #endif } - + // restore the depth test state - glDepthMask(currentDepthWriteMask); + glDepthMask(_currentDepthWriteMask); //if (currentDepthTestEnabled) { // glEnable(GL_DEPTH_TEST); //} - + /////////////////////////////////// // DRAW CONTENT - + // setup the stencil test func like this: // for each pixel of this node and its childs // if all layers less than or equals to the current are set to 1 in the stencil buffer // draw the pixel and keep the current layer in the stencil buffer // else // do not draw the pixel but keep the current layer in the stencil buffer - glStencilFunc(GL_EQUAL, mask_layer_le, mask_layer_le); + glStencilFunc(GL_EQUAL, _mask_layer_le, _mask_layer_le); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); - + // draw (according to the stencil test func) this node and its childs - Node::visit(); - +} + + +void ClippingNode::onAfterVisit() +{ /////////////////////////////////// // CLEANUP - + // manually restore the stencil state - glStencilFunc(currentStencilFunc, currentStencilRef, currentStencilValueMask); - glStencilOp(currentStencilFail, currentStencilPassDepthFail, currentStencilPassDepthPass); - glStencilMask(currentStencilWriteMask); - if (!currentStencilEnabled) + glStencilFunc(_currentStencilFunc, _currentStencilRef, _currentStencilValueMask); + glStencilOp(_currentStencilFail, _currentStencilPassDepthFail, _currentStencilPassDepthPass); + glStencilMask(_currentStencilWriteMask); + if (!_currentStencilEnabled) { glDisable(GL_STENCIL_TEST); } - + // we are done using this layer, decrement - layer--; -} - -Node* ClippingNode::getStencil() const -{ - return _stencil; -} - -void ClippingNode::setStencil(Node *pStencil) -{ - CC_SAFE_RELEASE(_stencil); - _stencil = pStencil; - CC_SAFE_RETAIN(_stencil); -} - -GLfloat ClippingNode::getAlphaThreshold() const -{ - return _alphaThreshold; -} - -void ClippingNode::setAlphaThreshold(GLfloat fAlphaThreshold) -{ - _alphaThreshold = fAlphaThreshold; -} - -bool ClippingNode::isInverted() const -{ - return _inverted; -} - -void ClippingNode::setInverted(bool bInverted) -{ - _inverted = bInverted; + s_layer--; } NS_CC_END diff --git a/cocos/2d/CCClippingNode.h b/cocos/2d/CCClippingNode.h index 7c18e99e01..c18379f722 100644 --- a/cocos/2d/CCClippingNode.h +++ b/cocos/2d/CCClippingNode.h @@ -30,6 +30,8 @@ #include "CCNode.h" #include "CCGL.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN @@ -48,14 +50,14 @@ public: /** Creates and initializes a clipping node with an other node as its stencil. The stencil node will be retained. */ - static ClippingNode* create(Node *pStencil); + static ClippingNode* create(Node *stencil); /** The Node to use as a stencil to do the clipping. The stencil node will be retained. This default to nil. */ Node* getStencil() const; - void setStencil(Node *pStencil); + void setStencil(Node *stencil); /** The alpha threshold. The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. @@ -63,14 +65,14 @@ public: This default to 1 (so alpha test is disabled). */ GLfloat getAlphaThreshold() const; - void setAlphaThreshold(GLfloat fAlphaThreshold); + void setAlphaThreshold(GLfloat alphaThreshold); /** Inverted. If this is set to true, the stencil is inverted, so the content is drawn where the stencil is NOT drawn. This default to false. */ bool isInverted() const; - void setInverted(bool bInverted); + void setInverted(bool inverted); // Overrides /** @@ -111,7 +113,7 @@ protected: /** Initializes a clipping node with an other node as its stencil. The stencil node will be retained, and its parent will be set to this clipping node. */ - virtual bool init(Node *pStencil); + virtual bool init(Node *stencil); /**draw fullscreen quad to clear stencil bits */ @@ -120,6 +122,32 @@ protected: Node* _stencil; GLfloat _alphaThreshold; bool _inverted; +protected: + //renderData and callback + void onBeforeVisit(); + void onAfterDrawStencil(); + void onAfterVisit(); + + GLboolean _currentStencilEnabled; + GLuint _currentStencilWriteMask; + GLenum _currentStencilFunc; + GLint _currentStencilRef; + GLuint _currentStencilValueMask; + GLenum _currentStencilFail; + GLenum _currentStencilPassDepthFail; + GLenum _currentStencilPassDepthPass; + GLboolean _currentDepthWriteMask; + + GLboolean _currentAlphaTestEnabled; + GLenum _currentAlphaTestFunc; + GLclampf _currentAlphaTestRef; + + GLint _mask_layer_le; + + GroupCommand _groupCommand; + CustomCommand _beforeVisitCmd; + CustomCommand _afterDrawStencilCmd; + CustomCommand _afterVisitCmd; private: CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode); diff --git a/cocos/2d/CCComponent.cpp b/cocos/2d/CCComponent.cpp index b073051e06..4f8482367a 100644 --- a/cocos/2d/CCComponent.cpp +++ b/cocos/2d/CCComponent.cpp @@ -28,7 +28,7 @@ THE SOFTWARE. NS_CC_BEGIN Component::Component(void) -: _owner(NULL) +: _owner(nullptr) , _enabled(true) { } @@ -60,26 +60,26 @@ void Component::serialize(void *ar) Component* Component::create(void) { - Component * pRet = new Component(); - if (pRet != NULL && pRet->init()) + Component * ret = new Component(); + if (ret != nullptr && ret->init()) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } -const char* Component::getName() const +const std::string& Component::getName() const { - return _name.c_str(); + return _name; } -void Component::setName(const char *pName) +void Component::setName(const std::string& name) { - _name.assign(pName); + _name = name; } Node* Component::getOwner() const @@ -87,9 +87,9 @@ Node* Component::getOwner() const return _owner; } -void Component::setOwner(Node *pOwner) +void Component::setOwner(Node *owner) { - _owner = pOwner; + _owner = owner; } bool Component::isEnabled() const diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index 58023fe9fb..5631c2585f 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -60,8 +60,8 @@ public: virtual void setEnabled(bool b); static Component* create(void); - const char* getName() const; - void setName(const char *pName); + const std::string& getName() const; + void setName(const std::string& name); void setOwner(Node *pOwner); Node* getOwner() const; diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index 2a27f76ff7..905bebbe27 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -29,9 +29,9 @@ THE SOFTWARE. NS_CC_BEGIN -ComponentContainer::ComponentContainer(Node *pNode) +ComponentContainer::ComponentContainer(Node *node) : _components(nullptr) -, _owner(pNode) +, _owner(node) { } @@ -40,24 +40,22 @@ ComponentContainer::~ComponentContainer(void) CC_SAFE_DELETE(_components); } -Component* ComponentContainer::get(const char *pName) const +Component* ComponentContainer::get(const std::string& name) const { - Component* pRet = NULL; - CCASSERT(pName != NULL, "Argument must be non-nil"); + Component* ret = nullptr; do { - CC_BREAK_IF(NULL == pName); - CC_BREAK_IF(NULL == _components); - pRet = _components->at(pName); + CC_BREAK_IF(nullptr == _components); + ret = _components->at(name); } while (0); - return pRet; + return ret; } -bool ComponentContainer::add(Component *pCom) +bool ComponentContainer::add(Component *com) { - bool bRet = false; - CCASSERT(pCom != NULL, "Argument must be non-nil"); - CCASSERT(pCom->getOwner() == NULL, "Component already added. It can't be added again"); + bool ret = false; + CCASSERT(com != nullptr, "Argument must be non-nil"); + CCASSERT(com->getOwner() == nullptr, "Component already added. It can't be added again"); do { if (_components == nullptr) @@ -65,38 +63,37 @@ bool ComponentContainer::add(Component *pCom) _components = new Map(); _owner->scheduleUpdate(); } - Component *pComponent = _components->at(pCom->getName()); + Component *component = _components->at(com->getName()); - CCASSERT(pComponent == NULL, "Component already added. It can't be added again"); - CC_BREAK_IF(pComponent); - pCom->setOwner(_owner); - _components->insert(pCom->getName(), pCom); - pCom->onEnter(); - bRet = true; + CCASSERT(component == nullptr, "Component already added. It can't be added again"); + CC_BREAK_IF(component); + com->setOwner(_owner); + _components->insert(com->getName(), com); + com->onEnter(); + ret = true; } while(0); - return bRet; + return ret; } -bool ComponentContainer::remove(const char *pName) +bool ComponentContainer::remove(const std::string& name) { - bool bRet = false; - CCASSERT(pName != NULL, "Argument must be non-nil"); + bool ret = false; do { CC_BREAK_IF(!_components); - auto iter = _components->find(pName); + auto iter = _components->find(name); CC_BREAK_IF(iter == _components->end()); auto com = iter->second; com->onExit(); - com->setOwner(NULL); + com->setOwner(nullptr); _components->erase(iter); - bRet = true; + ret = true; } while(0); - return bRet; + return ret; } void ComponentContainer::removeAll() @@ -106,7 +103,7 @@ void ComponentContainer::removeAll() for (auto iter = _components->begin(); iter != _components->end(); ++iter) { iter->second->onExit(); - iter->second->setOwner(NULL); + iter->second->setOwner(nullptr); } _components->clear(); @@ -121,13 +118,13 @@ void ComponentContainer::alloc(void) _components = new Map(); } -void ComponentContainer::visit(float fDelta) +void ComponentContainer::visit(float delta) { if (_components != nullptr) { for (auto iter = _components->begin(); iter != _components->end(); ++iter) { - iter->second->update(fDelta); + iter->second->update(delta); } } } diff --git a/cocos/2d/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h index 894fcc635a..d895693a86 100644 --- a/cocos/2d/CCComponentContainer.h +++ b/cocos/2d/CCComponentContainer.h @@ -26,6 +26,7 @@ THE SOFTWARE. #define __CC_FRAMEWORK_COMCONTAINER_H__ #include "CCMap.h" +#include NS_CC_BEGIN @@ -46,11 +47,11 @@ public: * @lua NA */ virtual ~ComponentContainer(void); - virtual Component* get(const char *pName) const; - virtual bool add(Component *pCom); - virtual bool remove(const char *pName); + virtual Component* get(const std::string& name) const; + virtual bool add(Component *com); + virtual bool remove(const std::string& name); virtual void removeAll(); - virtual void visit(float fDelta); + virtual void visit(float delta); public: bool isEmpty() const; diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index ea3e64d362..07ff02933d 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -284,7 +284,7 @@ void Configuration::setValue(const std::string& key, const Value& value) // // load file // -void Configuration::loadConfigFile(const char *filename) +void Configuration::loadConfigFile(const std::string& filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); @@ -312,14 +312,14 @@ void Configuration::loadConfigFile(const char *filename) if (! validMetadata) { - CCLOG("Invalid config format for file: %s", filename); + CCLOG("Invalid config format for file: %s", filename.c_str()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.end() || dataIter->second.getType() != Value::Type::MAP) { - CCLOG("Expected 'data' dict, but not found. Config file: %s", filename); + CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); return; } diff --git a/cocos/2d/CCConfiguration.h b/cocos/2d/CCConfiguration.h index f0296080ec..90387d5c38 100644 --- a/cocos/2d/CCConfiguration.h +++ b/cocos/2d/CCConfiguration.h @@ -128,7 +128,7 @@ public: void gatherGPUInfo(); /** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added. */ - void loadConfigFile(const char *filename); + void loadConfigFile(const std::string& filename); private: Configuration(void); diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index b8a3dd87a8..b2710848bf 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -560,8 +560,8 @@ CC_DEPRECATED_ATTRIBUTE typedef GLProgram CCGLProgram; CC_DEPRECATED_ATTRIBUTE typedef Touch CCTouch; CC_DEPRECATED_ATTRIBUTE typedef Texture2D CCTexture2D; CC_DEPRECATED_ATTRIBUTE typedef Node CCNode; -CC_DEPRECATED_ATTRIBUTE typedef NodeRGBA CCNodeRGBA; -CC_DEPRECATED_ATTRIBUTE typedef RGBAProtocol CCRGBAProtocol; +CC_DEPRECATED_ATTRIBUTE typedef Node CCNodeRGBA; +CC_DEPRECATED_ATTRIBUTE typedef Node CCRGBAProtocol; CC_DEPRECATED_ATTRIBUTE typedef SpriteFrame CCSpriteFrame; CC_DEPRECATED_ATTRIBUTE typedef AnimationFrame CCAnimationFrame; CC_DEPRECATED_ATTRIBUTE typedef Animation CCAnimation; @@ -678,7 +678,7 @@ CC_DEPRECATED_ATTRIBUTE typedef SpriteBatchNode CCSpriteBatchNode; CC_DEPRECATED_ATTRIBUTE typedef LabelBMFont CCLabelBMFont; CC_DEPRECATED_ATTRIBUTE typedef Layer CCLayer; //CC_DEPRECATED_ATTRIBUTE typedef KeypadDelegate CCKeypadDelegate; -CC_DEPRECATED_ATTRIBUTE typedef LayerRGBA CCLayerRGBA; +CC_DEPRECATED_ATTRIBUTE typedef Layer CCLayerRGBA; CC_DEPRECATED_ATTRIBUTE typedef LayerColor CCLayerColor; CC_DEPRECATED_ATTRIBUTE typedef LayerGradient CCLayerGradient; CC_DEPRECATED_ATTRIBUTE typedef LayerMultiplex CCLayerMultiplex; @@ -1038,7 +1038,11 @@ CC_DEPRECATED_ATTRIBUTE typedef __Integer CCInteger; CC_DEPRECATED_ATTRIBUTE typedef __Bool Bool; CC_DEPRECATED_ATTRIBUTE typedef __Bool CCBool; CC_DEPRECATED_ATTRIBUTE typedef __String CCString; -//CC_DEPRECATED_ATTRIBUTE typedef __String String; +CC_DEPRECATED_ATTRIBUTE typedef __String String; + +CC_DEPRECATED_ATTRIBUTE typedef __RGBAProtocol RGBAProtocol; +CC_DEPRECATED_ATTRIBUTE typedef __NodeRGBA NodeRGBA; +CC_DEPRECATED_ATTRIBUTE typedef __LayerRGBA LayerRGBA; NS_CC_END diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 1817371471..b0ecc02c4a 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. @@ -45,11 +45,9 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #include "CCApplication.h" #include "CCLabelBMFont.h" -#include "CCLabelAtlas.h" #include "CCActionManager.h" #include "CCAnimationCache.h" #include "CCTouch.h" -#include "CCEventDispatcher.h" #include "CCUserDefault.h" #include "ccGLStateCache.h" #include "CCShaderCache.h" @@ -60,8 +58,10 @@ THE SOFTWARE. #include "CCEGLView.h" #include "CCConfiguration.h" #include "CCEventDispatcher.h" +#include "CCEventCustom.h" #include "CCFontFreeType.h" - +#include "CCRenderer.h" +#include "renderer/CCFrustum.h" /** Position of the FPS @@ -84,6 +84,11 @@ static DisplayLinkDirector *s_SharedDirector = nullptr; #define kDefaultFPS 60 // 60 frames per second extern const char* cocos2dVersion(void); +const char *Director::EVENT_PROJECTION_CHANGED = "director_projection_changed"; +const char *Director::EVENT_AFTER_DRAW = "director_after_draw"; +const char *Director::EVENT_AFTER_VISIT = "director_after_visit"; +const char *Director::EVENT_AFTER_UPDATE = "director_after_udpate"; + Director* Director::getInstance() { if (!s_SharedDirector) @@ -95,9 +100,8 @@ Director* Director::getInstance() return s_SharedDirector; } -Director::Director(void) +Director::Director() { - } bool Director::init(void) @@ -134,7 +138,9 @@ bool Director::init(void) _winSizeInPoints = Size::ZERO; _openGLView = nullptr; - + + _cullingFrustum = new Frustum(); + _contentScaleFactor = 1.0f; // scheduler @@ -144,9 +150,22 @@ bool Director::init(void) _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); + _eventAfterDraw = new EventCustom(EVENT_AFTER_DRAW); + _eventAfterDraw->setUserData(this); + _eventAfterVisit = new EventCustom(EVENT_AFTER_VISIT); + _eventAfterVisit->setUserData(this); + _eventAfterUpdate = new EventCustom(EVENT_AFTER_UPDATE); + _eventAfterUpdate->setUserData(this); + _eventProjectionChanged = new EventCustom(EVENT_PROJECTION_CHANGED); + _eventProjectionChanged->setUserData(this); + + //init TextureCache initTextureCache(); - + + // Renderer + _renderer = new Renderer; + // create autorelease pool PoolManager::sharedPoolManager()->push(); @@ -166,7 +185,14 @@ Director::~Director(void) CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_eventDispatcher); - + + delete _eventAfterUpdate; + delete _eventAfterDraw; + delete _eventAfterVisit; + delete _eventProjectionChanged; + + delete _renderer; + // pop the autorelease pool PoolManager::sharedPoolManager()->pop(); PoolManager::purgePoolManager(); @@ -245,6 +271,7 @@ void Director::drawScene() if (! _paused) { _scheduler->update(_deltaTime); + _eventDispatcher->dispatchEvent(_eventAfterUpdate); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -257,11 +284,22 @@ void Director::drawScene() } kmGLPushMatrix(); - + + //construct the frustum + { + kmMat4 view; + kmMat4 projection; + kmGLGetMatrix(KM_GL_PROJECTION, &projection); + kmGLGetMatrix(KM_GL_MODELVIEW, &view); + + _cullingFrustum->setupFromMatrix(view, projection); + } + // draw the scene if (_runningScene) { _runningScene->visit(); + _eventDispatcher->dispatchEvent(_eventAfterVisit); } // draw the notifications node @@ -275,6 +313,9 @@ void Director::drawScene() showStats(); } + _renderer->render(); + _eventDispatcher->dispatchEvent(_eventAfterDraw); + kmGLPopMatrix(); _totalFrames++; @@ -353,6 +394,8 @@ void Director::setOpenGLView(EGLView *openGLView) setGLDefaultValues(); } + _renderer->initGLView(); + CHECK_GL_ERROR_DEBUG(); // _touchDispatcher->setDispatchEvents(true); @@ -452,6 +495,8 @@ void Director::setProjection(Projection projection) _projection = projection; GL::setProjectionMatrixDirty(); + + _eventDispatcher->dispatchEvent(_eventProjectionChanged); } void Director::purgeCachedData(void) @@ -706,6 +751,7 @@ void Director::purgeDirector() CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_SPFLabel); CC_SAFE_RELEASE_NULL(_drawsLabel); + CC_SAFE_DELETE(_cullingFrustum); // purge bitmap cache LabelBMFont::purgeCachedData(); @@ -801,13 +847,10 @@ void Director::resume() setAnimationInterval(_oldAnimationInterval); - if (gettimeofday(_lastUpdate, nullptr) != 0) - { - CCLOG("cocos2d: Director: Error in gettimeofday"); - } - _paused = false; _deltaTime = 0; + // fix issue #3509, skip one fps to avoid incorrect time calculation. + setNextDeltaTimeZero(true); } // display the FPS using a LabelAtlas @@ -906,17 +949,17 @@ void Director::createStatsLabel() */ float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f; - _FPSLabel = new LabelAtlas(); + _FPSLabel = new LabelAtlas; _FPSLabel->setIgnoreContentScaleFactor(true); _FPSLabel->initWithString("00.0", texture, 12, 32 , '.'); _FPSLabel->setScale(factor); - _SPFLabel = new LabelAtlas(); + _SPFLabel = new LabelAtlas; _SPFLabel->setIgnoreContentScaleFactor(true); _SPFLabel->initWithString("0.000", texture, 12, 32, '.'); _SPFLabel->setScale(factor); - _drawsLabel = new LabelAtlas(); + _drawsLabel = new LabelAtlas; _drawsLabel->setIgnoreContentScaleFactor(true); _drawsLabel->initWithString("000", texture, 12, 32, '.'); _drawsLabel->setScale(factor); @@ -1009,6 +1052,12 @@ void Director::setEventDispatcher(EventDispatcher* dispatcher) } } +Renderer* Director::getRenderer() const +{ + return _renderer; +} + + /*************************************************** * implementation of DisplayLinkDirector **************************************************/ @@ -1024,6 +1073,8 @@ void DisplayLinkDirector::startAnimation() } _invalid = false; + + Application::getInstance()->setAnimationInterval(_animationInterval); } void DisplayLinkDirector::mainLoop() diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 78c2a96114..b2204e7146 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -54,7 +54,11 @@ class Node; class Scheduler; class ActionManager; class EventDispatcher; +class EventCustom; +class EventListenerCustom; class TextureCache; +class Frustum; +class Renderer; /** @brief Class that creates and handles the main Window and manages how @@ -79,6 +83,12 @@ and when to execute the Scenes. class CC_DLL Director : public Object { public: + static const char *EVENT_PROJECTION_CHANGED; + static const char* EVENT_AFTER_UPDATE; + static const char* EVENT_AFTER_VISIT; + static const char* EVENT_AFTER_DRAW; + + /** @typedef ccDirectorProjection Possible OpenGL projections used by director */ @@ -330,8 +340,13 @@ public: */ void setContentScaleFactor(float scaleFactor); float getContentScaleFactor() const; + + /** + Get the Culling Frustum + */ + + Frustum* getFrustum() const { return _cullingFrustum; } -public: /** Gets the Scheduler associated with this director @since v2.0 */ @@ -361,7 +376,12 @@ public: @since v3.0 */ void setEventDispatcher(EventDispatcher* dispatcher); - + + /** Returns the Renderer + @since v3.0 + */ + Renderer* getRenderer() const; + /* Gets delta time since last tick to main loop */ float getDeltaTime() const; @@ -388,27 +408,27 @@ protected: void initTextureCache(); void destroyTextureCache(); -protected: /** Scheduler associated with this director @since v2.0 */ - Scheduler* _scheduler; + Scheduler *_scheduler; /** ActionManager associated with this director @since v2.0 */ - ActionManager* _actionManager; + ActionManager *_actionManager; /** EventDispatcher associated with this director @since v3.0 */ EventDispatcher* _eventDispatcher; + EventCustom *_eventProjectionChanged, *_eventAfterDraw, *_eventAfterVisit, *_eventAfterUpdate; /* delta time since last tick to main loop */ float _deltaTime; /* The EGLView, where everything is rendered */ - EGLView *_openGLView; + EGLView *_openGLView; //texture cache belongs to this director TextureCache *_textureCache; @@ -434,6 +454,8 @@ protected: unsigned int _totalFrames; unsigned int _frames; float _secondsPerFrame; + + Frustum *_cullingFrustum; /* The running scene */ Scene *_runningScene; @@ -443,7 +465,7 @@ protected: Scene *_nextScene; /* If true, then "old" scene will receive the cleanup message */ - bool _sendCleanupToScene; + bool _sendCleanupToScene; /* scheduled scenes */ Vector _scenesStack; @@ -458,10 +480,10 @@ protected: Projection _projection; /* window size in points */ - Size _winSizeInPoints; + Size _winSizeInPoints; /* content scale factor */ - float _contentScaleFactor; + float _contentScaleFactor; /* store the fps string */ char *_FPS; @@ -471,6 +493,8 @@ protected: /* Projection protocol delegate */ DirectorDelegate *_projectionDelegate; + + Renderer *_renderer; // EGLViewProtocol will recreate stats labels to fit visible rect friend class EGLViewProtocol; diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 4d88845957..ee4f218337 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -26,6 +26,9 @@ #include "CCNotificationCenter.h" #include "CCEventType.h" #include "CCConfiguration.h" +#include "CCCustomCommand.h" +#include "CCDirector.h" +#include "CCRenderer.h" NS_CC_BEGIN @@ -101,7 +104,7 @@ DrawNode::DrawNode() , _vbo(0) , _bufferCapacity(0) , _bufferCount(0) -, _buffer(NULL) +, _buffer(nullptr) , _dirty(false) { _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; @@ -110,7 +113,7 @@ DrawNode::DrawNode() DrawNode::~DrawNode() { free(_buffer); - _buffer = NULL; + _buffer = nullptr; glDeleteBuffers(1, &_vbo); _vbo = 0; @@ -129,17 +132,17 @@ DrawNode::~DrawNode() DrawNode* DrawNode::create() { - DrawNode* pRet = new DrawNode(); - if (pRet && pRet->init()) + DrawNode* ret = new DrawNode(); + if (ret && ret->init()) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } void DrawNode::ensureCapacity(int count) @@ -196,7 +199,7 @@ bool DrawNode::init() NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(DrawNode::listenBackToForeground), EVNET_COME_TO_FOREGROUND, - NULL); + nullptr); #endif return true; @@ -237,10 +240,17 @@ void DrawNode::render() } void DrawNode::draw() +{ + _customCommand.init(0, _vertexZ); + _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this); + Director::getInstance()->getRenderer()->addCommand(&_customCommand); +} + +void DrawNode::onDraw() { CC_NODE_DRAW_SETUP(); GL::blendFunc(_blendFunc.src, _blendFunc.dst); - + render(); } diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 38f899fc72..e91f41e8ca 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -32,6 +32,7 @@ #include "CCNode.h" #include "ccTypes.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN @@ -84,6 +85,8 @@ public: */ void listenBackToForeground(Object *obj); + void onDraw(); + // Overrides virtual void draw() override; @@ -103,6 +106,7 @@ protected: V2F_C4B_T2F *_buffer; BlendFunc _blendFunc; + CustomCommand _customCommand; bool _dirty; diff --git a/cocos/2d/CCDrawingPrimitives.cpp b/cocos/2d/CCDrawingPrimitives.cpp index 4e22032e21..16903cebe8 100644 --- a/cocos/2d/CCDrawingPrimitives.cpp +++ b/cocos/2d/CCDrawingPrimitives.cpp @@ -55,7 +55,7 @@ NS_CC_BEGIN namespace DrawPrimitives { static bool s_initialized = false; -static GLProgram* s_shader = NULL; +static GLProgram* s_shader = nullptr; static int s_colorLocation = -1; static Color4F s_color(1.0f,1.0f,1.0f,1.0f); static int s_pointSizeLocation = -1; @@ -475,7 +475,7 @@ void drawCardinalSpline( PointArray *config, float tension, unsigned int segmen Vertex2F* vertices = new Vertex2F[segments + 1]; - unsigned int p; + ssize_t p; float lt; float deltaT = 1.0f / config->count(); diff --git a/cocos/2d/CCEvent.h b/cocos/2d/CCEvent.h index 205ec443a7..b067ff3ce3 100644 --- a/cocos/2d/CCEvent.h +++ b/cocos/2d/CCEvent.h @@ -29,6 +29,7 @@ #include #include +#include "CCObject.h" #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -38,7 +39,7 @@ class Node; /** * Base class of all kinds of events. */ -class Event +class Event : public Object { public: enum class Type diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index fbbe534cde..151a6c267c 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -26,6 +26,11 @@ #include "CCEventTouch.h" #include "CCEventCustom.h" #include "CCEventListenerTouch.h" +#include "CCEventListenerAcceleration.h" +#include "CCEventListenerMouse.h" +#include "CCEventListenerKeyboard.h" +#include "CCEventListenerCustom.h" + #include "CCNode.h" #include "CCDirector.h" @@ -59,31 +64,30 @@ private: NS_CC_BEGIN -static EventListener::ListenerID getListenerID(Event* event) +static EventListener::ListenerID __getListenerID(Event* event) { EventListener::ListenerID ret; switch (event->getType()) { case Event::Type::ACCELERATION: - ret = static_cast(EventListener::Type::ACCELERATION); + ret = EventListenerAcceleration::LISTENER_ID; break; case Event::Type::CUSTOM: { auto customEvent = static_cast(event); - auto listenerID = std::hash()(customEvent->getEventName()); - ret = static_cast(listenerID); + ret = customEvent->getEventName(); } break; case Event::Type::KEYBOARD: - ret = static_cast(EventListener::Type::KEYBOARD); + ret = EventListenerKeyboard::LISTENER_ID; break; case Event::Type::MOUSE: - ret = static_cast(EventListener::Type::MOUSE); + ret = EventListenerMouse::LISTENER_ID; break; case Event::Type::TOUCH: // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. - // return UNKNOW instead. - ret = static_cast(EventListener::Type::UNKNOWN); + // return UNKNOWN instead. + CCASSERT(false, "Don't call this method if the event is for touch."); break; default: CCASSERT(false, "Invalid type!"); @@ -93,10 +97,10 @@ static EventListener::ListenerID getListenerID(Event* event) return ret; } -EventDispatcher::EventListenerVector::EventListenerVector() -: _sceneGraphListeners(nullptr) -, _fixedListeners(nullptr) -, _gt0Index(0) +EventDispatcher::EventListenerVector::EventListenerVector() : + _fixedListeners(nullptr), + _sceneGraphListeners(nullptr), + _gt0Index(0) { } @@ -335,6 +339,8 @@ void EventDispatcher::addEventListener(EventListener* listener) { _toAddedListeners.push_back(listener); } + + listener->retain(); } void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node) @@ -349,7 +355,6 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list listener->setFixedPriority(0); listener->setRegistered(true); - listener->retain(); addEventListener(listener); associateNodeAndEventListener(node, listener); @@ -373,12 +378,17 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, listener->setFixedPriority(fixedPriority); listener->setRegistered(true); listener->setPaused(false); - - listener->retain(); addEventListener(listener); } +EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string &eventName, std::function callback) +{ + EventListenerCustom *listener = EventListenerCustom::create(eventName, callback); + addEventListenerWithFixedPriority(listener, 1); + return listener; +} + void EventDispatcher::removeEventListener(EventListener* listener) { if (listener == nullptr) @@ -491,11 +501,12 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); - int i = 0; + ssize_t i = 0; // priority < 0 if (fixedPriorityListeners) { - for (; !fixedPriorityListeners->empty() && i < listeners->getGt0Index(); ++i) + bool isEmpty = fixedPriorityListeners->empty(); + for (; !isEmpty && i < listeners->getGt0Index(); ++i) { auto l = fixedPriorityListeners->at(i); if (!l->isPaused() && l->isRegistered() && onEvent(l)) @@ -527,7 +538,8 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s if (!shouldStopPropagation) { // priority > 0 - for (; i < fixedPriorityListeners->size(); ++i) + ssize_t size = fixedPriorityListeners->size(); + for (; i < size; ++i) { auto l = fixedPriorityListeners->at(i); @@ -557,7 +569,7 @@ void EventDispatcher::dispatchEvent(Event* event) return; } - auto listenerID = getListenerID(event); + auto listenerID = __getListenerID(event); sortEventListeners(listenerID); @@ -578,16 +590,21 @@ void EventDispatcher::dispatchEvent(Event* event) updateListeners(event); } +void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData) +{ + EventCustom ev(eventName); + ev.setUserData(optionalUserData); + dispatchEvent(&ev); +} + + void EventDispatcher::dispatchTouchEvent(EventTouch* event) { - auto touchOneByOneID = static_cast(EventListener::Type::TOUCH_ONE_BY_ONE); - auto touchAllAtOnceID = static_cast(EventListener::Type::TOUCH_ALL_AT_ONCE); + sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID); + sortEventListeners(EventListenerTouchAllAtOnce::LISTENER_ID); - sortEventListeners(touchOneByOneID); - sortEventListeners(touchAllAtOnceID); - - auto oneByOnelisteners = getListeners(touchOneByOneID); - auto allAtOncelisteners = getListeners(touchAllAtOnceID); + auto oneByOnelisteners = getListeners(EventListenerTouchOneByOne::LISTENER_ID); + auto allAtOncelisteners = getListeners(EventListenerTouchAllAtOnce::LISTENER_ID); // If there aren't any touch listeners, return directly. if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) @@ -776,7 +793,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) void EventDispatcher::updateListeners(Event* event) { - auto onUpdateListeners = [this](EventListener::ListenerID listenerID) + auto onUpdateListeners = [this](const EventListener::ListenerID& listenerID) { auto listenersIter = _listeners.find(listenerID); if (listenersIter == _listeners.end()) @@ -844,12 +861,12 @@ void EventDispatcher::updateListeners(Event* event) if (event->getType() == Event::Type::TOUCH) { - onUpdateListeners(static_cast(EventListener::Type::TOUCH_ONE_BY_ONE)); - onUpdateListeners(static_cast(EventListener::Type::TOUCH_ALL_AT_ONCE)); + onUpdateListeners(EventListenerTouchOneByOne::LISTENER_ID); + onUpdateListeners(EventListenerTouchAllAtOnce::LISTENER_ID); } else { - onUpdateListeners(getListenerID(event)); + onUpdateListeners(__getListenerID(event)); } @@ -907,7 +924,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() } } -void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID) +void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID) { DirtyFlag dirtyFlag = DirtyFlag::NONE; @@ -933,7 +950,7 @@ void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID) } } -void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID) +void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID) { auto listeners = getListeners(listenerID); @@ -962,7 +979,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::List #endif } -void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID) +void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID) { auto listeners = getListeners(listenerID); @@ -996,7 +1013,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerI } -EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::ListenerID listenerID) +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID) { auto iter = _listeners.find(listenerID); if (iter != _listeners.end()) @@ -1007,7 +1024,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene return nullptr; } -void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerID listenerID) +void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID) { auto listenerItemIter = _listeners.find(listenerID); if (listenerItemIter != _listeners.end()) @@ -1068,26 +1085,47 @@ void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerI void EventDispatcher::removeEventListeners(EventListener::Type listenerType) { - CCASSERT(listenerType != EventListener::Type::CUSTOM, "Not support custom event listener type, please use EventDispatcher::removeCustomEventListeners instead."); - - removeEventListenersForListenerID(static_cast(listenerType)); + if (listenerType == EventListener::Type::TOUCH_ONE_BY_ONE) + { + removeEventListenersForListenerID(EventListenerTouchOneByOne::LISTENER_ID); + } + else if (listenerType == EventListener::Type::TOUCH_ALL_AT_ONCE) + { + removeEventListenersForListenerID(EventListenerTouchAllAtOnce::LISTENER_ID); + } + else if (listenerType == EventListener::Type::MOUSE) + { + removeEventListenersForListenerID(EventListenerMouse::LISTENER_ID); + } + else if (listenerType == EventListener::Type::ACCELERATION) + { + removeEventListenersForListenerID(EventListenerAcceleration::LISTENER_ID); + } + else if (listenerType == EventListener::Type::KEYBOARD) + { + removeEventListenersForListenerID(EventListenerKeyboard::LISTENER_ID); + } + else + { + CCASSERT(false, "Invalid listener type!"); + } } void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) { - removeEventListenersForListenerID(std::hash()(customEventName)); + removeEventListenersForListenerID(customEventName); } void EventDispatcher::removeAllEventListeners() { std::vector types(_listeners.size()); - for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) + for (const auto& e : _listeners) { - types.push_back(iter->first); + types.push_back(e.first); } - for (auto& type : types) + for (const auto& type : types) { removeEventListenersForListenerID(type); } @@ -1118,7 +1156,7 @@ void EventDispatcher::setDirtyForNode(Node* node) } } -void EventDispatcher::setDirty(EventListener::ListenerID listenerID, DirtyFlag flag) +void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag) { auto iter = _priorityDirtyFlagMap.find(listenerID); if (iter == _priorityDirtyFlagMap.end()) diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 5fe81cca95..41c98495bd 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -40,6 +40,8 @@ NS_CC_BEGIN class Event; class EventTouch; class Node; +class EventCustom; +class EventListenerCustom; /** This class manages event listener subscriptions @@ -69,17 +71,23 @@ public: */ void addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority); - /** Remove a listener + /** Adds a Custom event listener. + It will use a fixed priority of 1. + @return the generated event. Needed in order to remove the event from the dispather + */ + EventListenerCustom* addCustomEventListener(const std::string &eventName, std::function callback); + + /** Remove a listener * @param listener The specified event listener which needs to be removed. */ void removeEventListener(EventListener* listener); /** Removes all listeners with the same event listener type */ void removeEventListeners(EventListener::Type listenerType); - + /** Removes all custom listeners with the same event name */ void removeCustomEventListeners(const std::string& customEventName); - + /** Removes all listeners */ void removeAllEventListeners(); @@ -97,13 +105,16 @@ public: * event dispatcher list. */ void dispatchEvent(Event* event); - + + /** Dispatches a Custom Event with a event name an optional user data */ + void dispatchCustomEvent(const std::string &eventName, void *optionalUserData); + /** Constructor of EventDispatcher */ EventDispatcher(); /** Destructor of EventDispatcher */ ~EventDispatcher(); -private: +protected: friend class Node; /** Sets the dirty flag for a node. */ @@ -148,22 +159,22 @@ private: void addEventListener(EventListener* listener); /** Gets event the listener list for the event listener type. */ - EventListenerVector* getListeners(EventListener::ListenerID listenerID); + EventListenerVector* getListeners(const EventListener::ListenerID& listenerID); /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); /** Removes all listeners with the same event listener ID */ - void removeEventListenersForListenerID(EventListener::ListenerID listenerID); + void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID); /** Sort event listener */ - void sortEventListeners(EventListener::ListenerID listenerID); + void sortEventListeners(const EventListener::ListenerID& listenerID); /** Sorts the listeners of specified type by scene graph priority */ - void sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID); + void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID); /** Sorts the listeners of specified type by fixed priority */ - void sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID); + void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID); /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. @@ -193,12 +204,11 @@ private: }; /** Sets the dirty flag for a specified listener ID */ - void setDirty(EventListener::ListenerID listenerID, DirtyFlag flag); + void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */ void visitTarget(Node* node); -private: /** Listeners map */ std::unordered_map _listeners; diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index a24b709e5b..ea44c83559 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -57,7 +57,7 @@ public: CUSTOM }; - typedef std::size_t ListenerID; + typedef std::string ListenerID; protected: /** Constructor */ @@ -83,7 +83,7 @@ protected: inline bool isRegistered() const { return _isRegistered; }; inline Type getType() const { return _type; }; - inline ListenerID getListenerID() const { return _listenerID; }; + inline const ListenerID& getListenerID() const { return _listenerID; }; inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; }; inline int getFixedPriority() const { return _fixedPriority; }; diff --git a/cocos/2d/CCEventListenerAcceleration.cpp b/cocos/2d/CCEventListenerAcceleration.cpp index 258af5929e..d4192e2a83 100644 --- a/cocos/2d/CCEventListenerAcceleration.cpp +++ b/cocos/2d/CCEventListenerAcceleration.cpp @@ -27,6 +27,8 @@ NS_CC_BEGIN +const std::string EventListenerAcceleration::LISTENER_ID = "__cc_acceleration"; + EventListenerAcceleration::EventListenerAcceleration() { @@ -59,7 +61,7 @@ bool EventListenerAcceleration::init(std::functiononAccelerationEvent(&accEvent->_acc, event); }; - if (EventListener::init(Type::ACCELERATION, static_cast(Type::ACCELERATION), listener)) + if (EventListener::init(Type::ACCELERATION, LISTENER_ID, listener)) { onAccelerationEvent = callback; return true; diff --git a/cocos/2d/CCEventListenerAcceleration.h b/cocos/2d/CCEventListenerAcceleration.h index 59ce3d8439..afe7fb5bba 100644 --- a/cocos/2d/CCEventListenerAcceleration.h +++ b/cocos/2d/CCEventListenerAcceleration.h @@ -33,6 +33,8 @@ NS_CC_BEGIN class EventListenerAcceleration : public EventListener { public: + static const std::string LISTENER_ID; + static EventListenerAcceleration* create(std::function callback); virtual ~EventListenerAcceleration(); @@ -44,6 +46,8 @@ private: bool init(std::function callback); std::function onAccelerationEvent; + + friend class LuaEventListenerAcceleration; }; NS_CC_END diff --git a/cocos/2d/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp index 09e657a9fc..eda8ba36fa 100644 --- a/cocos/2d/CCEventListenerCustom.cpp +++ b/cocos/2d/CCEventListenerCustom.cpp @@ -35,7 +35,7 @@ EventListenerCustom::EventListenerCustom() EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function callback) { EventListenerCustom* ret = new EventListenerCustom(); - if (ret && ret->init(std::hash()(eventName), callback)) + if (ret && ret->init(eventName, callback)) { ret->autorelease(); } diff --git a/cocos/2d/CCEventListenerCustom.h b/cocos/2d/CCEventListenerCustom.h index e2e750ce56..8a7fe162e1 100644 --- a/cocos/2d/CCEventListenerCustom.h +++ b/cocos/2d/CCEventListenerCustom.h @@ -70,6 +70,8 @@ protected: bool init(ListenerID listenerId, std::function callback); std::function _onCustomEvent; + + friend class LuaEventListenerCustom; }; NS_CC_END diff --git a/cocos/2d/CCEventListenerKeyboard.cpp b/cocos/2d/CCEventListenerKeyboard.cpp index 77ce94d705..ff31aa2ace 100644 --- a/cocos/2d/CCEventListenerKeyboard.cpp +++ b/cocos/2d/CCEventListenerKeyboard.cpp @@ -29,6 +29,8 @@ NS_CC_BEGIN +const std::string EventListenerKeyboard::LISTENER_ID = "__cc_keyboard"; + bool EventListenerKeyboard::checkAvailable() { if (onKeyPressed == nullptr && onKeyReleased == nullptr) @@ -92,7 +94,7 @@ bool EventListenerKeyboard::init() } }; - if (EventListener::init(Type::KEYBOARD, static_cast(Type::KEYBOARD), listener)) + if (EventListener::init(Type::KEYBOARD, LISTENER_ID, listener)) { return true; } diff --git a/cocos/2d/CCEventListenerKeyboard.h b/cocos/2d/CCEventListenerKeyboard.h index c34d2add0d..a8b181da66 100644 --- a/cocos/2d/CCEventListenerKeyboard.h +++ b/cocos/2d/CCEventListenerKeyboard.h @@ -36,6 +36,8 @@ class Event; class EventListenerKeyboard : public EventListener { public: + static const std::string LISTENER_ID; + static EventListenerKeyboard* create(); /// Overrides diff --git a/cocos/2d/CCEventListenerMouse.cpp b/cocos/2d/CCEventListenerMouse.cpp index aa65e9b356..63ebebd501 100644 --- a/cocos/2d/CCEventListenerMouse.cpp +++ b/cocos/2d/CCEventListenerMouse.cpp @@ -27,6 +27,8 @@ NS_CC_BEGIN +const std::string EventListenerMouse::LISTENER_ID = "__cc_mouse"; + bool EventListenerMouse::checkAvailable() { return true; @@ -65,8 +67,8 @@ EventListenerMouse* EventListenerMouse::clone() } EventListenerMouse::EventListenerMouse() -: onMouseUp(nullptr) -, onMouseDown(nullptr) +: onMouseDown(nullptr) +, onMouseUp(nullptr) , onMouseMove(nullptr) , onMouseScroll(nullptr) { @@ -99,7 +101,7 @@ bool EventListenerMouse::init() } }; - if (EventListener::init(Type::MOUSE, static_cast(Type::MOUSE), listener)) + if (EventListener::init(Type::MOUSE, LISTENER_ID, listener)) { return true; } diff --git a/cocos/2d/CCEventListenerMouse.h b/cocos/2d/CCEventListenerMouse.h index 360d46128a..a9fa326b8b 100644 --- a/cocos/2d/CCEventListenerMouse.h +++ b/cocos/2d/CCEventListenerMouse.h @@ -36,6 +36,8 @@ class Event; class EventListenerMouse : public EventListener { public: + static const std::string LISTENER_ID; + static EventListenerMouse* create(); /// Overrides diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index 20e620910a..c453d5f84c 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -30,6 +30,8 @@ NS_CC_BEGIN +const std::string EventListenerTouchOneByOne::LISTENER_ID = "__cc_touch_one_by_one"; + EventListenerTouchOneByOne::EventListenerTouchOneByOne() : onTouchBegan(nullptr) , onTouchMoved(nullptr) @@ -46,7 +48,7 @@ EventListenerTouchOneByOne::~EventListenerTouchOneByOne() bool EventListenerTouchOneByOne::init() { - if (EventListener::init(Type::TOUCH_ONE_BY_ONE, static_cast(Type::TOUCH_ONE_BY_ONE), nullptr)) + if (EventListener::init(Type::TOUCH_ONE_BY_ONE, LISTENER_ID, nullptr)) { return true; } @@ -107,6 +109,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::clone() } ///////// + +const std::string EventListenerTouchAllAtOnce::LISTENER_ID = "__cc_touch_all_at_once"; + EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce() : onTouchesBegan(nullptr) , onTouchesMoved(nullptr) @@ -122,7 +127,7 @@ EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce() bool EventListenerTouchAllAtOnce::init() { - if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, static_cast(Type::TOUCH_ALL_AT_ONCE), nullptr)) + if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, LISTENER_ID, nullptr)) { return true; } diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index 80ff176263..5f1ddd2845 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -36,6 +36,8 @@ NS_CC_BEGIN class EventListenerTouchOneByOne : public EventListener { public: + static const std::string LISTENER_ID; + static EventListenerTouchOneByOne* create(); virtual ~EventListenerTouchOneByOne(); @@ -67,8 +69,8 @@ private: class EventListenerTouchAllAtOnce : public EventListener { public: - static const ListenerID ID = static_cast(Type::TOUCH_ALL_AT_ONCE); - + static const std::string LISTENER_ID; + static EventListenerTouchAllAtOnce* create(); virtual ~EventListenerTouchAllAtOnce(); diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index c48acdc0b5..471346a5ad 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -27,15 +27,21 @@ #include "CCFontFNT.h" #include "CCFontFreeType.h" +#include "edtaa3func.h" NS_CC_BEGIN +const int Font::DistanceMapSpread = 3; + const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖ×ØÙÚÛÜÃÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; -Font::Font() : _usedGlyphs(GlyphCollection::ASCII), _customGlyphs(nullptr) +Font::Font() : +_usedGlyphs(GlyphCollection::ASCII) +, _customGlyphs(nullptr) +,_distanceFieldEnabled(false) { } @@ -109,6 +115,164 @@ Font* Font::createWithFNT(const std::string& fntFilePath) return FontFNT::create(fntFilePath); } +unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) +{ + unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); + + short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); + short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); + double * gx = (double *) calloc( pixelAmount, sizeof(double) ); + double * gy = (double *) calloc( pixelAmount, sizeof(double) ); + double * data = (double *) calloc( pixelAmount, sizeof(double) ); + double * outside = (double *) calloc( pixelAmount, sizeof(double) ); + double * inside = (double *) calloc( pixelAmount, sizeof(double) ); + unsigned int i,j; + + // Convert img into double (data) rescale image levels between 0 and 1 + unsigned int outWidth = width + 2 * DistanceMapSpread; + for (i = 0; i < width; ++i) + { + for (j = 0; j < height; ++j) + { + data[j * outWidth + DistanceMapSpread + i] = img[j * width + i] / 255.0; + } + } + + width += 2 * DistanceMapSpread; + height += 2 * DistanceMapSpread; + + // Transform background (outside contour, in areas of 0's) + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, outside); + for( i=0; i< pixelAmount; i++) + if( outside[i] < 0.0 ) + outside[i] = 0.0; + + // Transform foreground (inside contour, in areas of 1's) + for( i=0; i< pixelAmount; i++) + data[i] = 1 - data[i]; + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, inside); + for( i=0; i< pixelAmount; i++) + if( inside[i] < 0.0 ) + inside[i] = 0.0; + + // The bipolar distance field is now outside-inside + double dist; + /* Single channel 8-bit output (bad precision and range, but simple) */ + unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); + for( i=0; i < pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0 ) dist = 0; + if( dist > 255 ) dist = 255; + out[i] = (unsigned char) dist; + } + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); + for( i=0; i< pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0.0 ) dist = 0.0; + if( dist >= 256.0 ) dist = 255.999; + // R channel is a copy of the original grayscale image + out[3*i] = img[i]; + // G channel is fraction + out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); + // B channel is truncated integer part + out[3*i + 2] = (unsigned char)dist; + }*/ + + free( xdist ); + free( ydist ); + free( gx ); + free( gy ); + free( data ); + free( outside ); + free( inside ); + + return out; +} + +void Font::setDistanceFieldEnabled(bool distanceFieldEnabled) +{ + _distanceFieldEnabled = distanceFieldEnabled; +} + +bool Font::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) +{ + unsigned char *sourceBitmap = 0; + int sourceWidth = 0; + int sourceHeight = 0; + + sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + + if (!sourceBitmap) + return false; + + if (_distanceFieldEnabled) + { + unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); + + int iX = posX; + int iY = posY; + + sourceWidth += 2 * DistanceMapSpread; + sourceHeight += 2 * DistanceMapSpread; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*int index = (iX + ( iY * destSize )) * 3; + int index2 = (bitmap_y + x)*3; + destMemory[index] = out[index2]; + destMemory[index + 1] = out[index2 + 1]; + destMemory[index + 2] = out[index2 + 2];*/ + + //Single channel 8-bit output + destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; + + iX += 1; + } + + iX = posX; + iY += 1; + } + free(out); + return true; + } + + int iX = posX; + int iY = posY; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + unsigned char cTemp = sourceBitmap[bitmap_y + x]; + + // the final pixel + destMemory[(iX + ( iY * destSize ) )] = cTemp; + + iX += 1; + } + + iX = posX; + iY += 1; + } + + //everything good + return true; +} + unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const { unsigned short* utf16String = cc_utf8_to_utf16(text); diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index cf3084011d..dfd5dd7ecc 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -40,11 +40,16 @@ class FontAtlas; class CC_DLL Font : public Object { public: - + static const int DistanceMapSpread; // create the font static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static Font* createWithFNT(const std::string& fntFilePath); + static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); + void setDistanceFieldEnabled(bool distanceFieldEnabled); + bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} + bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); + virtual FontAtlas *createFontAtlas() = 0; virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; @@ -76,7 +81,8 @@ protected: char * _customGlyphs; static const char * _glyphASCII; static const char * _glyphNEHE; - + bool _distanceFieldEnabled; + }; NS_CC_END diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index e0b97aa286..a4dcb8fd19 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -21,12 +21,14 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - #include "cocos2d.h" #include "CCFontAtlas.h" #include "CCFont.h" #include "CCFontFreeType.h" +#define PAGE_WIDTH 1024 +#define PAGE_HEIGHT 1024 + NS_CC_BEGIN FontAtlas::FontAtlas(Font &theFont) : @@ -34,7 +36,8 @@ _font(&theFont), _currentPageData(nullptr) { _font->retain(); - + _makeDistanceMap = _font->isDistanceFieldEnabled(); + FontFreeType* fontTTf = dynamic_cast(_font); if (fontTTf && fontTTf->isDynamicGlyphCollection()) { @@ -45,7 +48,17 @@ _currentPageData(nullptr) _currentPageOrigX = 0; _currentPageOrigY = 0; _letterPadding = 5; - _currentPageDataSize = (1024 * 1024 * 4); + + if(_makeDistanceMap) + { + _commonLineHeight += 2 * Font::DistanceMapSpread; + _letterPadding += 2 * Font::DistanceMapSpread; + _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); + } + else + { + _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); + } _currentPageData = new unsigned char[_currentPageDataSize]; memset(_currentPageData, 0, _currentPageDataSize); @@ -97,16 +110,20 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) FontFreeType* fontTTf = (FontFreeType*)_font; - std::vector fontDefs; + std::unordered_map fontDefs; int length = cc_wcslen(utf16String); //find out new letter for (int i = 0; i < length; ++i) { auto outIterator = _fontLetterDefinitions.find(utf16String[i]); - + if (outIterator == _fontLetterDefinitions.end()) - { + { + auto outIterator2 = fontDefs.find(utf16String[i]); + if(outIterator2 != fontDefs.end()) + continue; + Rect tempRect; FontLetterDefinition tempDef; @@ -135,28 +152,30 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.offsetY = tempRect.origin.y; tempDef.commonLineHeight = _currentPageLineHeight; - } - fontDefs.push_back(tempDef); + } + fontDefs[utf16String[i]] = tempDef; } } + Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT); float scaleFactor = CC_CONTENT_SCALE_FACTOR(); - size_t newLetterCount = fontDefs.size(); float glyphWidth; - for (int i = 0; i < newLetterCount; ++i) + Texture2D::PixelFormat pixelFormat = _makeDistanceMap ? Texture2D::PixelFormat::A8 : Texture2D::PixelFormat::A8; + + for(auto it = fontDefs.begin(); it != fontDefs.end(); it++) { - if (fontDefs[i].validDefinition) + if(it->second.validDefinition) { _currentPageOrigX += _letterPadding; - glyphWidth = fontDefs[i].width - _letterPadding; + glyphWidth = it->second.width - _letterPadding; - if (_currentPageOrigX + glyphWidth > 1024) + if (_currentPageOrigX + glyphWidth > PAGE_WIDTH) { _currentPageOrigY += _currentPageLineHeight; - if(_currentPageOrigY >= 1024) + _currentPageOrigX = 0; + if(_currentPageOrigY >= PAGE_HEIGHT) { - _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, Texture2D::PixelFormat::RGBA8888, 1024, 1024, Size(1024, 1024) ); - _currentPageOrigX = 0; + _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize ); _currentPageOrigY = 0; delete []_currentPageData; @@ -170,63 +189,25 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tex->release(); } } - renderCharAt(fontDefs[i].letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,1024); + _font->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); - fontDefs[i].U = _currentPageOrigX - 1; - fontDefs[i].V = _currentPageOrigY; - fontDefs[i].textureID = _currentPage; + it->second.U = _currentPageOrigX - 1; + it->second.V = _currentPageOrigY; + it->second.textureID = _currentPage; // take from pixels to points - fontDefs[i].width = fontDefs[i].width / scaleFactor; - fontDefs[i].height = fontDefs[i].height / scaleFactor; - fontDefs[i].U = fontDefs[i].U / scaleFactor; - fontDefs[i].V = fontDefs[i].V / scaleFactor; + it->second.width = it->second.width / scaleFactor; + it->second.height = it->second.height / scaleFactor; + it->second.U = it->second.U / scaleFactor; + it->second.V = it->second.V / scaleFactor; } else glyphWidth = 0; - this->addLetterDefinition(fontDefs[i]); + _fontLetterDefinitions[it->second.letteCharUTF16] = it->second; _currentPageOrigX += glyphWidth; } - if(newLetterCount > 0) - _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, Texture2D::PixelFormat::RGBA8888, 1024, 1024, Size(1024, 1024) ); - return true; -} - -bool FontAtlas::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) -{ - unsigned char *sourceBitmap = 0; - int sourceWidth = 0; - int sourceHeight = 0; - - // get the glyph's bitmap - sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight); - - if (!sourceBitmap) - return false; - - int iX = posX; - int iY = posY; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - unsigned char cTemp = sourceBitmap[bitmap_y + x]; - - // the final pixel - int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp; - *(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp; - - iX += 1; - } - - iX = posX; - iY += 1; - } - - //everything good + if(fontDefs.size() > 0) + _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize ); return true; } @@ -248,6 +229,8 @@ float FontAtlas::getCommonLineHeight() const void FontAtlas::setCommonLineHeight(float newHeight) { + if(_makeDistanceMap) + newHeight += 2 * Font::DistanceMapSpread; _commonLineHeight = newHeight; } diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 317a06561d..044b0cdb5e 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -73,7 +73,6 @@ public: const Font* getFont() const; private: - bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); void relaseTextures(); std::unordered_map _atlasTextures; @@ -89,6 +88,7 @@ private: float _currentPageOrigY; float _currentPageLineHeight; float _letterPadding; + bool _makeDistanceMap; }; diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 00fc1e2a1f..b72b76540c 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -30,14 +30,14 @@ NS_CC_BEGIN std::unordered_map FontAtlasCache::_atlasMap; -FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) +FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) { - std::string atlasName = generateFontName(fontFileName, size, glyphs); + std::string atlasName = generateFontName(fontFileName, size, glyphs, useDistanceField); FontAtlas *tempAtlas = _atlasMap[atlasName]; if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs); + tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs, useDistanceField); if (tempAtlas) _atlasMap[atlasName] = tempAtlas; } @@ -49,9 +49,9 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, return tempAtlas; } -FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName) +FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) { - std::string atlasName = generateFontName(fontFileName, 0, GlyphCollection::CUSTOM); + std::string atlasName = generateFontName(fontFileName, 0, GlyphCollection::CUSTOM,false); FontAtlas *tempAtlas = _atlasMap[atlasName]; if ( !tempAtlas ) @@ -68,7 +68,7 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName) return tempAtlas; } -std::string FontAtlasCache::generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs) +std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField) { std::string tempName(fontFileName); @@ -93,7 +93,8 @@ std::string FontAtlasCache::generateFontName(const char *fontFileName, int size, default: break; } - + if(useDistanceField) + tempName.append("df"); // std::to_string is not supported on android, using std::stringstream instead. std::stringstream ss; ss << size; diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index f5f8ca7df4..acbbb28ca9 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -38,14 +38,14 @@ class CC_DLL FontAtlasCache public: - static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0); - static FontAtlas * getFontAtlasFNT(const char *fontFileName); + static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); + static FontAtlas * getFontAtlasFNT(const std::string& fontFileName); static bool releaseFontAtlas(FontAtlas *atlas); private: - static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs); + static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField); static std::unordered_map _atlasMap; }; diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index b1cd69172f..8e532af2c5 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -30,24 +30,28 @@ NS_CC_BEGIN -FontAtlas * FontAtlasFactory::createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs) +FontAtlas * FontAtlasFactory::createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) { Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); if (font) + { + font->setDistanceFieldEnabled(useDistanceField); return font->createFontAtlas(); + } else + { return nullptr; + } } -FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath) +FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath) { Font *font = Font::createWithFNT(fntFilePath); if(font) { - FontAtlas * atlas = font->createFontAtlas(); - return atlas; + return font->createFontAtlas(); } else { diff --git a/cocos/2d/CCFontAtlasFactory.h b/cocos/2d/CCFontAtlasFactory.h index f1b785f4c1..b03806dccd 100644 --- a/cocos/2d/CCFontAtlasFactory.h +++ b/cocos/2d/CCFontAtlasFactory.h @@ -36,8 +36,8 @@ class CC_DLL FontAtlasFactory public: - static FontAtlas * createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0); - static FontAtlas * createAtlasFromFNT(const char* fntFilePath); + static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); + static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath); private: }; diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 08e8d0304d..77a64bcfd9 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -90,22 +90,23 @@ FT_Library FontFreeType::getFTLibrary() FontFreeType::FontFreeType(bool dynamicGlyphCollection) : _fontRef(nullptr), _letterPadding(5), -_ttfData(nullptr), _dynamicGlyphCollection(dynamicGlyphCollection) { + if(_distanceFieldEnabled) + _letterPadding += 2 * DistanceMapSpread; } bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) { FT_Face face; - ssize_t len = 0; - _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len); - if (!_ttfData) + _ttfData = FileUtils::getInstance()->getDataFromFile(fontName); + + if (_ttfData.isNull()) return false; // create the face from the data - if (FT_New_Memory_Face(getFTLibrary(), _ttfData, len, 0, &face )) + if (FT_New_Memory_Face(getFTLibrary(), _ttfData.getBytes(), _ttfData.getSize(), 0, &face )) return false; //we want to use unicode @@ -134,11 +135,6 @@ FontFreeType::~FontFreeType() { FT_Done_Face(_fontRef); } - if (_ttfData) - { - free(_ttfData); - _ttfData = nullptr; - } } FontAtlas * FontFreeType::createFontAtlas() @@ -354,23 +350,21 @@ int FontFreeType::getFontMaxHeight() const return (static_cast(_fontRef->size->metrics.height >> 6)); } -unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const +unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { if (!_fontRef) return 0; - // get the ID to the char we need - int glyphIndex = FT_Get_Char_Index(_fontRef, theChar); - - if (!glyphIndex) - return 0; - - // load glyph infos - if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT)) - return 0; - - if (FT_Render_Glyph( _fontRef->glyph, FT_RENDER_MODE_NORMAL )) - return 0; + if (_distanceFieldEnabled) + { + if (FT_Load_Char(_fontRef,theChar,FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT)) + return 0; + } + else + { + if (FT_Load_Char(_fontRef,theChar,FT_LOAD_RENDER)) + return 0; + } outWidth = _fontRef->glyph->bitmap.width; outHeight = _fontRef->glyph->bitmap.rows; diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index a305b2253e..7ff7596c20 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -25,11 +25,12 @@ #ifndef _FontFreetype_h_ #define _FontFreetype_h_ +#include "CCFont.h" +#include "CCData.h" + #include #include -#include "CCFont.h" - #include FT_FREETYPE_H NS_CC_BEGIN @@ -71,9 +72,9 @@ private: static FT_Library _FTlibrary; static bool _FTInitialized; FT_Face _fontRef; - const int _letterPadding; + int _letterPadding; std::string _fontName; - unsigned char* _ttfData; + Data _ttfData; bool _dynamicGlyphCollection; }; diff --git a/cocos/2d/CCGLProgram.cpp b/cocos/2d/CCGLProgram.cpp index 44d180877b..0d9441cde3 100644 --- a/cocos/2d/CCGLProgram.cpp +++ b/cocos/2d/CCGLProgram.cpp @@ -46,6 +46,7 @@ typedef struct _hashUniformEntry } tHashUniformEntry; const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor"; +const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP = "ShaderPositionTextureColor_noMVP"; const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest"; const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor"; const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture"; @@ -54,6 +55,12 @@ const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR = "ShaderPositionTe const char* GLProgram::SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"; const char* GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR = "ShaderPositionLengthTextureColor"; +const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL = "ShaderLabelNormol"; +const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW = "ShaderLabelGlow"; +const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_OUTLINE = "ShaderLabelOutline"; +const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_SHADOW = "ShaderLabelShadow"; + + // uniform names const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix"; const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix"; @@ -74,7 +81,7 @@ GLProgram::GLProgram() : _program(0) , _vertShader(0) , _fragShader(0) -, _hashForUniforms(NULL) +, _hashForUniforms(nullptr) , _flags() { memset(_uniforms, 0, sizeof(_uniforms)); @@ -138,7 +145,7 @@ bool GLProgram::initWithVertexShaderByteArray(const GLchar* vShaderByteArray, co { glAttachShader(_program, _fragShader); } - _hashForUniforms = NULL; + _hashForUniforms = nullptr; CHECK_GL_ERROR_DEBUG(); @@ -147,18 +154,18 @@ bool GLProgram::initWithVertexShaderByteArray(const GLchar* vShaderByteArray, co bool GLProgram::initWithVertexShaderFilename(const char* vShaderFilename, const char* fShaderFilename) { - const GLchar * vertexSource = (GLchar*) String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename).c_str())->getCString(); - const GLchar * fragmentSource = (GLchar*) String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename).c_str())->getCString(); + std::string vertexSource = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename).c_str()); + std::string fragmentSource = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename).c_str()); - return initWithVertexShaderByteArray(vertexSource, fragmentSource); + return initWithVertexShaderByteArray(vertexSource.c_str(), fragmentSource.c_str()); } std::string GLProgram::getDescription() const { - return String::createWithFormat("", - (size_t)this, _program, _vertShader, _fragShader)->getCString(); + (size_t)this, _program, _vertShader, _fragShader); } bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source) @@ -186,7 +193,7 @@ bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source }; *shader = glCreateShader(type); - glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, NULL); + glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, nullptr); glCompileShader(*shader); glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); @@ -197,7 +204,7 @@ bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source glGetShaderiv(*shader, GL_SHADER_SOURCE_LENGTH, &length); GLchar* src = (GLchar *)malloc(sizeof(GLchar) * length); - glGetShaderSource(*shader, length, NULL, src); + glGetShaderSource(*shader, length, nullptr, src); CCLOG("cocos2d: ERROR: Failed to compile shader:\n%s", src); if (type == GL_VERTEX_SHADER) @@ -234,8 +241,9 @@ void GLProgram::updateUniforms() _uniforms[UNIFORM_SAMPLER] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER); + _flags.usesP = _uniforms[UNIFORM_P_MATRIX] != -1; + _flags.usesMV = _uniforms[UNIFORM_MV_MATRIX] != -1; _flags.usesMVP = _uniforms[UNIFORM_MVP_MATRIX] != -1; - _flags.usesMV = (_uniforms[UNIFORM_MV_MATRIX] != -1 && _uniforms[UNIFORM_P_MATRIX] != -1 ); _flags.usesTime = ( _uniforms[UNIFORM_TIME] != -1 || _uniforms[UNIFORM_SIN_TIME] != -1 || @@ -323,7 +331,7 @@ std::string GLProgram::getProgramLog() const // Uniform cache -bool GLProgram::updateUniformLocation(GLint location, GLvoid* data, unsigned int bytes) +bool GLProgram::updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes) { if (location < 0) { @@ -331,7 +339,7 @@ bool GLProgram::updateUniformLocation(GLint location, GLvoid* data, unsigned int } bool updated = true; - tHashUniformEntry *element = NULL; + tHashUniformEntry *element = nullptr; HASH_FIND_INT(_hashForUniforms, &location, element); if (! element) @@ -364,7 +372,7 @@ bool GLProgram::updateUniformLocation(GLint location, GLvoid* data, unsigned int GLint GLProgram::getUniformLocationForName(const char* name) const { - CCASSERT(name != NULL, "Invalid uniform name" ); + CCASSERT(name != nullptr, "Invalid uniform name" ); CCASSERT(_program != 0, "Invalid operation. Cannot get uniform location when program is not initialized"); return glGetUniformLocation(_program, name); @@ -486,7 +494,7 @@ void GLProgram::setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, } } -void GLProgram::setUniformLocationWith2fv(GLint location, GLfloat* floats, unsigned int numberOfArrays) +void GLProgram::setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays) { bool updated = updateUniformLocation(location, floats, sizeof(float)*2*numberOfArrays); @@ -496,7 +504,7 @@ void GLProgram::setUniformLocationWith2fv(GLint location, GLfloat* floats, unsig } } -void GLProgram::setUniformLocationWith3fv(GLint location, GLfloat* floats, unsigned int numberOfArrays) +void GLProgram::setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays) { bool updated = updateUniformLocation(location, floats, sizeof(float)*3*numberOfArrays); @@ -506,7 +514,7 @@ void GLProgram::setUniformLocationWith3fv(GLint location, GLfloat* floats, unsig } } -void GLProgram::setUniformLocationWith4fv(GLint location, GLfloat* floats, unsigned int numberOfArrays) +void GLProgram::setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays) { bool updated = updateUniformLocation(location, floats, sizeof(float)*4*numberOfArrays); @@ -516,7 +524,7 @@ void GLProgram::setUniformLocationWith4fv(GLint location, GLfloat* floats, unsig } } -void GLProgram::setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) { +void GLProgram::setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) { bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*4*numberOfMatrices); if( updated ) @@ -525,7 +533,7 @@ void GLProgram::setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixA } } -void GLProgram::setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) { +void GLProgram::setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) { bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*9*numberOfMatrices); if( updated ) @@ -535,7 +543,7 @@ void GLProgram::setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixA } -void GLProgram::setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) +void GLProgram::setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) { bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*16*numberOfMatrices); @@ -547,12 +555,23 @@ void GLProgram::setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixA void GLProgram::setUniformsForBuiltins() { - kmMat4 matrixP; kmMat4 matrixMV; + kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV); + + setUniformsForBuiltins(matrixMV); +} + +void GLProgram::setUniformsForBuiltins(const kmMat4 &matrixMV) +{ + kmMat4 matrixP; kmGLGetMatrix(KM_GL_PROJECTION, &matrixP); - kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV); - + + if(_flags.usesP) + setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1); + + if(_flags.usesMV) + setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1); if(_flags.usesMVP) { kmMat4 matrixMVP; @@ -560,11 +579,6 @@ void GLProgram::setUniformsForBuiltins() setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MVP_MATRIX], matrixMVP.mat, 1); } - if(_flags.usesMV) { - setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1); - setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1); - } - if(_flags.usesTime) { Director *director = Director::getInstance(); // This doesn't give the most accurate global time value. @@ -601,7 +615,7 @@ void GLProgram::reset() free(current_element->value); free(current_element); } - _hashForUniforms = NULL; + _hashForUniforms = nullptr; } NS_CC_END diff --git a/cocos/2d/CCGLProgram.h b/cocos/2d/CCGLProgram.h index a46fa4eaa5..84aaa113fa 100644 --- a/cocos/2d/CCGLProgram.h +++ b/cocos/2d/CCGLProgram.h @@ -32,6 +32,7 @@ THE SOFTWARE. #include "CCObject.h" #include "CCGL.h" +#include "kazmath/kazmath.h" NS_CC_BEGIN @@ -78,6 +79,7 @@ public: }; static const char* SHADER_NAME_POSITION_TEXTURE_COLOR; + static const char* SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP; static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST; static const char* SHADER_NAME_POSITION_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE; @@ -85,6 +87,11 @@ public: static const char* SHADER_NAME_POSITION_TEXTURE_A8_COLOR; static const char* SHADER_NAME_POSITION_U_COLOR; static const char* SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR; + + static const char* SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL; + static const char* SHADER_NAME_LABEL_DISTANCEFIELD_GLOW; + static const char* SHADER_NAME_LABEL_DISTANCEFIELD_OUTLINE; + static const char* SHADER_NAME_LABEL_DISTANCEFIELD_SHADOW; // uniform names static const char* UNIFORM_NAME_P_MATRIX; @@ -190,25 +197,26 @@ public: void setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4); /** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ - void setUniformLocationWith2fv(GLint location, GLfloat* floats, unsigned int numberOfArrays); + void setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ - void setUniformLocationWith3fv(GLint location, GLfloat* floats, unsigned int numberOfArrays); + void setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ - void setUniformLocationWith4fv(GLint location, GLfloat* floats, unsigned int numberOfArrays); + void setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */ - void setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices); + void setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */ - void setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices); + void setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ - void setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices); + void setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** will update the builtin uniforms if they are different than the previous call for this same shader program. */ void setUniformsForBuiltins(); + void setUniformsForBuiltins(const kmMat4 &modelView); /** returns the vertexShader error log */ std::string getVertexShaderLog() const; @@ -226,8 +234,9 @@ public: inline const GLuint getProgram() const { return _program; } private: - bool updateUniformLocation(GLint location, GLvoid* data, unsigned int bytes); + bool updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes); virtual std::string getDescription() const; + bool compileShader(GLuint * shader, GLenum type, const GLchar* source); std::string logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const; @@ -242,6 +251,7 @@ private: unsigned int usesTime:1; unsigned int usesMVP:1; unsigned int usesMV:1; + unsigned int usesP:1; unsigned int usesRandom:1; // handy way to initialize the bitfield diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index b99077bbcf..06da510aed 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -76,9 +76,9 @@ GridBase* GridBase::create(const Size& gridSize, Texture2D *texture, bool flippe return pGridBase; } -bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlipped) +bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool flipped) { - bool bRet = true; + bool ret = true; _active = false; _reuseGrid = 0; @@ -86,7 +86,7 @@ bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlip _texture = texture; CC_SAFE_RETAIN(_texture); - _isTextureFlipped = bFlipped; + _isTextureFlipped = flipped; Size texSize = _texture->getContentSize(); _step.x = texSize.width / _gridSize.width; @@ -99,19 +99,19 @@ bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlip } else { - bRet = false; + ret = false; } _shaderProgram = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE); calculateVertexPoints(); - return bRet; + return ret; } bool GridBase::initWithSize(const Size& gridSize) { - Director *pDirector = Director::getInstance(); - Size s = pDirector->getWinSizeInPixels(); + Director *director = Director::getInstance(); + Size s = director->getWinSizeInPixels(); auto POTWide = ccNextPOT((unsigned int)s.width); auto POTHigh = ccNextPOT((unsigned int)s.height); @@ -156,10 +156,10 @@ GridBase::~GridBase(void) } // properties -void GridBase::setActive(bool bActive) +void GridBase::setActive(bool active) { - _active = bActive; - if (! bActive) + _active = active; + if (! active) { Director *pDirector = Director::getInstance(); Director::Projection proj = pDirector->getProjection(); @@ -167,11 +167,11 @@ void GridBase::setActive(bool bActive) } } -void GridBase::setTextureFlipped(bool bFlipped) +void GridBase::setTextureFlipped(bool flipped) { - if (_isTextureFlipped != bFlipped) + if (_isTextureFlipped != flipped) { - _isTextureFlipped = bFlipped; + _isTextureFlipped = flipped; calculateVertexPoints(); } } @@ -216,17 +216,17 @@ void GridBase::afterDraw(cocos2d::Node *target) Director *director = Director::getInstance(); director->setProjection(_directorProjection); - if (target->getCamera()->isDirty()) - { - Point offset = target->getAnchorPointInPoints(); - - // - // XXX: Camera should be applied in the AnchorPoint - // - kmGLTranslatef(offset.x, offset.y, 0); - target->getCamera()->locate(); - kmGLTranslatef(-offset.x, -offset.y, 0); - } +// if (target->getCamera()->isDirty()) +// { +// Point offset = target->getAnchorPointInPoints(); +// +// // +// // XXX: Camera should be applied in the AnchorPoint +// // +// kmGLTranslatef(offset.x, offset.y, 0); +// target->getCamera()->locate(); +// kmGLTranslatef(-offset.x, -offset.y, 0); +// } GL::bindTexture2D(_texture->getName()); @@ -253,52 +253,52 @@ void GridBase::calculateVertexPoints(void) // implementation of Grid3D -Grid3D* Grid3D::create(const Size& gridSize, Texture2D *texture, bool bFlipped) +Grid3D* Grid3D::create(const Size& gridSize, Texture2D *texture, bool flipped) { - Grid3D *pRet= new Grid3D(); + Grid3D *ret= new Grid3D(); - if (pRet) + if (ret) { - if (pRet->initWithSize(gridSize, texture, bFlipped)) + if (ret->initWithSize(gridSize, texture, flipped)) { - pRet->autorelease(); + ret->autorelease(); } else { - delete pRet; - pRet = NULL; + delete ret; + ret = nullptr; } } - return pRet; + return ret; } Grid3D* Grid3D::create(const Size& gridSize) { - Grid3D *pRet= new Grid3D(); + Grid3D *ret= new Grid3D(); - if (pRet) + if (ret) { - if (pRet->initWithSize(gridSize)) + if (ret->initWithSize(gridSize)) { - pRet->autorelease(); + ret->autorelease(); } else { - delete pRet; - pRet = NULL; + delete ret; + ret = nullptr; } } - return pRet; + return ret; } Grid3D::Grid3D() - : _texCoordinates(NULL) - , _vertices(NULL) - , _originalVertices(NULL) - , _indices(NULL) + : _texCoordinates(nullptr) + , _vertices(nullptr) + , _originalVertices(nullptr) + , _indices(nullptr) { } @@ -470,10 +470,10 @@ void Grid3D::reuse(void) // implementation of TiledGrid3D TiledGrid3D::TiledGrid3D() - : _texCoordinates(NULL) - , _vertices(NULL) - , _originalVertices(NULL) - , _indices(NULL) + : _texCoordinates(nullptr) + , _vertices(nullptr) + , _originalVertices(nullptr) + , _indices(nullptr) { } @@ -486,44 +486,44 @@ TiledGrid3D::~TiledGrid3D(void) CC_SAFE_FREE(_indices); } -TiledGrid3D* TiledGrid3D::create(const Size& gridSize, Texture2D *texture, bool bFlipped) +TiledGrid3D* TiledGrid3D::create(const Size& gridSize, Texture2D *texture, bool flipped) { - TiledGrid3D *pRet= new TiledGrid3D(); + TiledGrid3D *ret= new TiledGrid3D(); - if (pRet) + if (ret) { - if (pRet->initWithSize(gridSize, texture, bFlipped)) + if (ret->initWithSize(gridSize, texture, flipped)) { - pRet->autorelease(); + ret->autorelease(); } else { - delete pRet; - pRet = NULL; + delete ret; + ret = nullptr; } } - return pRet; + return ret; } TiledGrid3D* TiledGrid3D::create(const Size& gridSize) { - TiledGrid3D *pRet= new TiledGrid3D(); + TiledGrid3D *ret= new TiledGrid3D(); - if (pRet) + if (ret) { - if (pRet->initWithSize(gridSize)) + if (ret->initWithSize(gridSize)) { - pRet->autorelease(); + ret->autorelease(); } else { - delete pRet; - pRet = NULL; + delete ret; + ret = nullptr; } } - return pRet; + return ret; } void TiledGrid3D::blit(void) diff --git a/cocos/2d/CCGrid.h b/cocos/2d/CCGrid.h index 7c5f7e03da..63e49547d8 100644 --- a/cocos/2d/CCGrid.h +++ b/cocos/2d/CCGrid.h @@ -27,7 +27,6 @@ THE SOFTWARE. #include "CCObject.h" #include "CCNode.h" -#include "CCCamera.h" #include "ccTypes.h" #include "CCTexture2D.h" #include "CCDirector.h" @@ -62,16 +61,16 @@ public: */ virtual ~GridBase(void); - bool initWithSize(const Size& gridSize, Texture2D *texture, bool bFlipped); + bool initWithSize(const Size& gridSize, Texture2D *texture, bool flipped); bool initWithSize(const Size& gridSize); /** whether or not the grid is active */ inline bool isActive(void) const { return _active; } - void setActive(bool bActive); + void setActive(bool active); /** number of times that the grid will be reused */ inline int getReuseGrid(void) const { return _reuseGrid; } - inline void setReuseGrid(int nReuseGrid) { _reuseGrid = nReuseGrid; } + inline void setReuseGrid(int reuseGrid) { _reuseGrid = reuseGrid; } /** size of the grid */ inline const Size& getGridSize(void) const { return _gridSize; } @@ -83,7 +82,7 @@ public: /** is texture flipped */ inline bool isTextureFlipped(void) const { return _isTextureFlipped; } - void setTextureFlipped(bool bFlipped); + void setTextureFlipped(bool flipped); void beforeDraw(void); void afterDraw(Node *target); @@ -115,7 +114,7 @@ class CC_DLL Grid3D : public GridBase { public: /** create one Grid */ - static Grid3D* create(const Size& gridSize, Texture2D *texture, bool bFlipped); + static Grid3D* create(const Size& gridSize, Texture2D *texture, bool flipped); /** create one Grid */ static Grid3D* create(const Size& gridSize); /** @@ -178,7 +177,7 @@ class CC_DLL TiledGrid3D : public GridBase { public: /** create one Grid */ - static TiledGrid3D* create(const Size& gridSize, Texture2D *texture, bool bFlipped); + static TiledGrid3D* create(const Size& gridSize, Texture2D *texture, bool flipped); /** create one Grid */ static TiledGrid3D* create(const Size& gridSize); /** diff --git a/cocos/2d/CCIMEDelegate.h b/cocos/2d/CCIMEDelegate.h index d7fee2e59b..053359abfc 100644 --- a/cocos/2d/CCIMEDelegate.h +++ b/cocos/2d/CCIMEDelegate.h @@ -25,9 +25,11 @@ THE SOFTWARE. #ifndef __CC_IME_DELEGATE_H__ #define __CC_IME_DELEGATE_H__ +#include #include "CCGeometry.h" NS_CC_BEGIN +extern const std::string STD_STRING_EMPTY; /** * @addtogroup input @@ -114,7 +116,7 @@ protected: * @js NA * @lua NA */ - virtual const char * getContentText() { return 0; } + virtual const std::string& getContentText() { return STD_STRING_EMPTY; } ////////////////////////////////////////////////////////////////////////// // keyboard show/hide notification diff --git a/cocos/2d/CCIMEDispatcher.cpp b/cocos/2d/CCIMEDispatcher.cpp index a7dd70a756..7bc493c988 100644 --- a/cocos/2d/CCIMEDispatcher.cpp +++ b/cocos/2d/CCIMEDispatcher.cpp @@ -78,12 +78,12 @@ public: _delegateWithIme = 0; } - DelegateIter findDelegate(IMEDelegate* pDelegate) + DelegateIter findDelegate(IMEDelegate* delegate) { DelegateIter end = _delegateList.end(); for (DelegateIter iter = _delegateList.begin(); iter != end; ++iter) { - if (pDelegate == *iter) + if (delegate == *iter) { return iter; } @@ -114,29 +114,29 @@ IMEDispatcher::~IMEDispatcher() // Add/Attach/Remove IMEDelegate ////////////////////////////////////////////////////////////////////////// -void IMEDispatcher::addDelegate(IMEDelegate* pDelegate) +void IMEDispatcher::addDelegate(IMEDelegate* delegate) { - if (! pDelegate || ! _impl) + if (! delegate || ! _impl) { return; } - if (_impl->_delegateList.end() != _impl->findDelegate(pDelegate)) + if (_impl->_delegateList.end() != _impl->findDelegate(delegate)) { // pDelegate already in list return; } - _impl->_delegateList.push_front(pDelegate); + _impl->_delegateList.push_front(delegate); } -bool IMEDispatcher::attachDelegateWithIME(IMEDelegate * pDelegate) +bool IMEDispatcher::attachDelegateWithIME(IMEDelegate * delegate) { - bool bRet = false; + bool ret = false; do { - CC_BREAK_IF(! _impl || ! pDelegate); + CC_BREAK_IF(! _impl || ! delegate); DelegateIter end = _impl->_delegateList.end(); - DelegateIter iter = _impl->findDelegate(pDelegate); + DelegateIter iter = _impl->findDelegate(delegate); // if pDelegate is not in delegate list, return CC_BREAK_IF(end == iter); @@ -147,55 +147,55 @@ bool IMEDispatcher::attachDelegateWithIME(IMEDelegate * pDelegate) // or pDelegate canAttachWithIME return false, // do nothing. CC_BREAK_IF(! _impl->_delegateWithIme->canDetachWithIME() - || ! pDelegate->canAttachWithIME()); + || ! delegate->canAttachWithIME()); // detach first - IMEDelegate * pOldDelegate = _impl->_delegateWithIme; + IMEDelegate * oldDelegate = _impl->_delegateWithIme; _impl->_delegateWithIme = 0; - pOldDelegate->didDetachWithIME(); + oldDelegate->didDetachWithIME(); _impl->_delegateWithIme = *iter; - pDelegate->didAttachWithIME(); - bRet = true; + delegate->didAttachWithIME(); + ret = true; break; } // delegate hasn't attached to IME yet - CC_BREAK_IF(! pDelegate->canAttachWithIME()); + CC_BREAK_IF(! delegate->canAttachWithIME()); _impl->_delegateWithIme = *iter; - pDelegate->didAttachWithIME(); - bRet = true; + delegate->didAttachWithIME(); + ret = true; } while (0); - return bRet; + return ret; } -bool IMEDispatcher::detachDelegateWithIME(IMEDelegate * pDelegate) +bool IMEDispatcher::detachDelegateWithIME(IMEDelegate * delegate) { - bool bRet = false; + bool ret = false; do { - CC_BREAK_IF(! _impl || ! pDelegate); + CC_BREAK_IF(! _impl || ! delegate); // if pDelegate is not the current delegate attached to IME, return - CC_BREAK_IF(_impl->_delegateWithIme != pDelegate); + CC_BREAK_IF(_impl->_delegateWithIme != delegate); - CC_BREAK_IF(! pDelegate->canDetachWithIME()); + CC_BREAK_IF(! delegate->canDetachWithIME()); _impl->_delegateWithIme = 0; - pDelegate->didDetachWithIME(); - bRet = true; + delegate->didDetachWithIME(); + ret = true; } while (0); - return bRet; + return ret; } -void IMEDispatcher::removeDelegate(IMEDelegate* pDelegate) +void IMEDispatcher::removeDelegate(IMEDelegate* delegate) { do { - CC_BREAK_IF(! pDelegate || ! _impl); + CC_BREAK_IF(! delegate || ! _impl); - DelegateIter iter = _impl->findDelegate(pDelegate); + DelegateIter iter = _impl->findDelegate(delegate); DelegateIter end = _impl->_delegateList.end(); CC_BREAK_IF(end == iter); @@ -213,16 +213,16 @@ void IMEDispatcher::removeDelegate(IMEDelegate* pDelegate) // dispatch text message ////////////////////////////////////////////////////////////////////////// -void IMEDispatcher::dispatchInsertText(const char * pText, int nLen) +void IMEDispatcher::dispatchInsertText(const char * text, int len) { do { - CC_BREAK_IF(! _impl || ! pText || nLen <= 0); + CC_BREAK_IF(! _impl || ! text || len <= 0); // there is no delegate attached to IME CC_BREAK_IF(! _impl->_delegateWithIme); - _impl->_delegateWithIme->insertText(pText, nLen); + _impl->_delegateWithIme->insertText(text, len); } while (0); } @@ -239,14 +239,13 @@ void IMEDispatcher::dispatchDeleteBackward() } while (0); } -const char * IMEDispatcher::getContentText() +const std::string& IMEDispatcher::getContentText() { - const char * pszContentText = 0; if (_impl && _impl->_delegateWithIme) { - pszContentText = _impl->_delegateWithIme->getContentText(); + return _impl->_delegateWithIme->getContentText(); } - return (pszContentText) ? pszContentText : ""; + return STD_STRING_EMPTY; } ////////////////////////////////////////////////////////////////////////// @@ -257,14 +256,14 @@ void IMEDispatcher::dispatchKeyboardWillShow(IMEKeyboardNotificationInfo& info) { if (_impl) { - IMEDelegate * pDelegate = 0; + IMEDelegate * delegate = 0; DelegateIter last = _impl->_delegateList.end(); for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) { - pDelegate = *(first); - if (pDelegate) + delegate = *(first); + if (delegate) { - pDelegate->keyboardWillShow(info); + delegate->keyboardWillShow(info); } } } @@ -274,14 +273,14 @@ void IMEDispatcher::dispatchKeyboardDidShow(IMEKeyboardNotificationInfo& info) { if (_impl) { - IMEDelegate * pDelegate = 0; + IMEDelegate * delegate = 0; DelegateIter last = _impl->_delegateList.end(); for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) { - pDelegate = *(first); - if (pDelegate) + delegate = *(first); + if (delegate) { - pDelegate->keyboardDidShow(info); + delegate->keyboardDidShow(info); } } } @@ -291,14 +290,14 @@ void IMEDispatcher::dispatchKeyboardWillHide(IMEKeyboardNotificationInfo& info) { if (_impl) { - IMEDelegate * pDelegate = 0; + IMEDelegate * delegate = 0; DelegateIter last = _impl->_delegateList.end(); for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) { - pDelegate = *(first); - if (pDelegate) + delegate = *(first); + if (delegate) { - pDelegate->keyboardWillHide(info); + delegate->keyboardWillHide(info); } } } @@ -308,14 +307,14 @@ void IMEDispatcher::dispatchKeyboardDidHide(IMEKeyboardNotificationInfo& info) { if (_impl) { - IMEDelegate * pDelegate = 0; + IMEDelegate * delegate = 0; DelegateIter last = _impl->_delegateList.end(); for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) { - pDelegate = *(first); - if (pDelegate) + delegate = *(first); + if (delegate) { - pDelegate->keyboardDidHide(info); + delegate->keyboardDidHide(info); } } } diff --git a/cocos/2d/CCIMEDispatcher.h b/cocos/2d/CCIMEDispatcher.h index 124b9b6f8f..ea551a4d3e 100644 --- a/cocos/2d/CCIMEDispatcher.h +++ b/cocos/2d/CCIMEDispatcher.h @@ -63,7 +63,7 @@ public: * @js NA * @lua NA */ - void dispatchInsertText(const char * pText, int nLen); + void dispatchInsertText(const char * text, int len); /** @brief Dispatches the delete-backward operation. @@ -77,7 +77,7 @@ public: * @js NA * @lua NA */ - const char * getContentText(); + const std::string& getContentText(); ////////////////////////////////////////////////////////////////////////// // dispatch keyboard notification @@ -109,20 +109,20 @@ protected: /** @brief Add delegate to receive IME messages. */ - void addDelegate(IMEDelegate * pDelegate); + void addDelegate(IMEDelegate * delegate); /** @brief Attach the pDelegate to the IME. @return If the old delegate can detach from the IME, and the new delegate can attach to the IME, return true, otherwise false. */ - bool attachDelegateWithIME(IMEDelegate * pDelegate); - bool detachDelegateWithIME(IMEDelegate * pDelegate); + bool attachDelegateWithIME(IMEDelegate * delegate); + bool detachDelegateWithIME(IMEDelegate * delegate); /** @brief Remove the delegate from the delegates which receive IME messages. */ - void removeDelegate(IMEDelegate * pDelegate); + void removeDelegate(IMEDelegate * delegate); private: IMEDispatcher(); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index ca94d2b4f9..c2a512d482 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -27,20 +27,28 @@ #include "CCFontAtlasCache.h" #include "CCLabelTextFormatter.h" +#define DISTANCEFIELD_ATLAS_FONTSIZE 50 + NS_CC_BEGIN -Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) +Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) { - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs); + FontAtlas *tmpAtlas = nullptr; + if(useDistanceField) + tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), DISTANCEFIELD_ATLAS_FONTSIZE, glyphs, customGlyphs,true); + else + tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs,false); if (!tmpAtlas) return nullptr; // create the actual label - Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize); + Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize, useDistanceField,true); if (templabel) { + if(useDistanceField) + templabel->setFontSize(fontSize); templabel->setText(label, lineSize, alignment, false); return templabel; } @@ -71,9 +79,9 @@ Label* Label::createWithBMFont(const std::string& label, const std::string& bmfo return 0; } -Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize) +Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize, bool useDistanceField,bool useA8Shader) { - Label *ret = new Label(atlas, alignment); + Label *ret = new Label(atlas, alignment, useDistanceField,useA8Shader); if (!ret) return 0; @@ -92,21 +100,22 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li return ret; } -Label::Label(FontAtlas *atlas, TextHAlignment alignment) +Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) : _reusedLetter(nullptr) +, _multilineEnable(true) +, _commonLineHeight(0.0f) , _lineBreakWithoutSpaces(false) +, _width(0.0f) , _alignment(alignment) , _currentUTF16String(0) , _originalUTF16String(0) -, _advances(0) +, _advances(nullptr) , _fontAtlas(atlas) -, _displayedColor(Color3B::WHITE) -, _realColor(Color3B::WHITE) -, _cascadeColorEnabled(true) -, _cascadeOpacityEnabled(true) -, _displayedOpacity(255) -, _realOpacity(255) , _isOpacityModifyRGB(true) +, _useDistanceField(useDistanceField) +, _useA8Shader(useA8Shader) +, _fontSize(0) +, _uniformEffectColor(0) { } @@ -124,19 +133,31 @@ Label::~Label() bool Label::init() { + bool ret = true; if(_fontAtlas) { _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); + ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); _reusedLetter->retain(); - return SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); } + if (_useDistanceField) + setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK); + else if(_useA8Shader) + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR)); - return true; + return ret; } void Label::setString(const std::string &stringToRender) { + _multilineEnable = true; + setText(stringToRender, _width, TextHAlignment::CENTER, false); +} + +void Label::setString(const std::string &stringToRender,bool multilineEnable) +{ + _multilineEnable = multilineEnable; setText(stringToRender, _width, TextHAlignment::CENTER, false); } @@ -221,20 +242,53 @@ void Label::setLineBreakWithoutSpace(bool breakWithoutSpace) void Label::setScale(float scale) { + if (_useDistanceField) + { + scale *= 1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE; + } Node::setScale(scale); - alignText(); } void Label::setScaleX(float scaleX) { + if (_useDistanceField) + { + scaleX *= 1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE; + } Node::setScaleX(scaleX); - alignText(); } void Label::setScaleY(float scaleY) { + if (_useDistanceField) + { + scaleY *= 1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE; + } Node::setScaleY(scaleY); - alignText(); +} + +float Label::getScaleY() const +{ + if (_useDistanceField) + { + return _scaleY / (1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE); + } + else + { + return _scaleY; + } +} + +float Label::getScaleX() const +{ + if (_useDistanceField) + { + return _scaleX / (1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE); + } + else + { + return _scaleX; + } } void Label::alignText() @@ -243,22 +297,18 @@ void Label::alignText() _textureAtlas->removeAllQuads(); _fontAtlas->prepareLetterDefinitions(_currentUTF16String); LabelTextFormatter::createStringSprites(this); - if( LabelTextFormatter::multilineText(this) ) + if(_multilineEnable && LabelTextFormatter::multilineText(this) ) LabelTextFormatter::createStringSprites(this); LabelTextFormatter::alignText(this); int strLen = cc_wcslen(_currentUTF16String); - - _children.forEach([this, &strLen](Node* child){ - if (child) - { - int tag = child->getTag(); - if(tag < 0 || tag >= strLen) - SpriteBatchNode::removeChild(child, true); - } - }); - + for(const auto &child : _children) { + int tag = child->getTag(); + if(tag < 0 || tag >= strLen) + SpriteBatchNode::removeChild(child, true); + } + _reusedLetter->setBatchNode(nullptr); int vaildIndex = 0; @@ -415,6 +465,68 @@ void Label::addChild(Node * child, int zOrder/* =0 */, int tag/* =0 */) CCASSERT(0, "addChild: is not supported on Label."); } +void Label::setLabelEffect(LabelEffect effect,const Color3B& effectColor) +{ + if(_useDistanceField == false) + return; + + _currLabelEffect = effect; + _effectColor = effectColor; + + switch (_currLabelEffect) + { + case cocos2d::LabelEffect::NORMAL: + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL)); + break; + case cocos2d::LabelEffect::OUTLINE: + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_OUTLINE)); + break; + case cocos2d::LabelEffect::SHADOW: + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_SHADOW)); + break; + case cocos2d::LabelEffect::GLOW: + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW)); + break; + default: + return; + } + + _uniformEffectColor = glGetUniformLocation(_shaderProgram->getProgram(), "v_effectColor"); +} + +void Label::setFontSize(int fontSize) +{ + _fontSize = fontSize; + Node::setScale(1.0f*_fontSize/DISTANCEFIELD_ATLAS_FONTSIZE); +} + +void Label::draw() +{ + CC_PROFILER_START("CCSpriteBatchNode - draw"); + + // Optimization: Fast Dispatch + if( _textureAtlas->getTotalQuads() == 0 ) + { + return; + } + + CC_NODE_DRAW_SETUP(); + + if (_useDistanceField && _currLabelEffect != LabelEffect::NORMAL) + { + _shaderProgram->setUniformLocationWith3f(_uniformEffectColor, _effectColor.r/255.0f,_effectColor.g/255.0f,_effectColor.b/255.0f); + } + + for(const auto &child: _children) + child->updateTransform(); + + GL::blendFunc( _blendFunc.src, _blendFunc.dst ); + + _textureAtlas->drawQuads(); + + CC_PROFILER_STOP("CCSpriteBatchNode - draw"); +} + ///// PROTOCOL STUFF Sprite * Label::getLetter(int ID) @@ -434,7 +546,7 @@ Sprite * Label::getLetter(int ID) uvRect.origin.x = _lettersInfo[ID].def.U; uvRect.origin.y = _lettersInfo[ID].def.V; - sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID), uvRect); + sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect); sp->setBatchNode(this); sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); sp->setPosition(_lettersInfo[ID].position); @@ -592,123 +704,25 @@ void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) { _isOpacityModifyRGB = isOpacityModifyRGB; - _children.forEach([this](Node* child){ - if (child) - { - RGBAProtocol *pRGBAProtocol = dynamic_cast(child); - if (pRGBAProtocol) - { - pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB); - } - } - }); - + for(const auto& child: _children) { + child->setOpacityModifyRGB(_isOpacityModifyRGB); + } + _reusedLetter->setOpacityModifyRGB(true); } -unsigned char Label::getOpacity() const -{ - return _realOpacity; -} - -unsigned char Label::getDisplayedOpacity() const -{ - return _displayedOpacity; -} - -void Label::setOpacity(GLubyte opacity) -{ - _displayedOpacity = _realOpacity = opacity; - _reusedLetter->setOpacity(opacity); - if( _cascadeOpacityEnabled ) { - GLubyte parentOpacity = 255; - RGBAProtocol* pParent = dynamic_cast(_parent); - if (pParent && pParent->isCascadeOpacityEnabled()) - { - parentOpacity = pParent->getDisplayedOpacity(); - } - this->updateDisplayedOpacity(parentOpacity); - } -} -void Label::updateDisplayedOpacity(GLubyte parentOpacity) -{ - _displayedOpacity = _realOpacity * parentOpacity/255.0; - - _children.forEach([this](Node* child){ - Sprite *item = static_cast( child ); - item->updateDisplayedOpacity(_displayedOpacity); - }); - - V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - auto count = _textureAtlas->getTotalQuads(); - Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); - if (_isOpacityModifyRGB) - { - color4.r *= _displayedOpacity/255.0f; - color4.g *= _displayedOpacity/255.0f; - color4.b *= _displayedOpacity/255.0f; - } - for (int index = 0; index < count; ++index) - { - quads[index].bl.colors = color4; - quads[index].br.colors = color4; - quads[index].tl.colors = color4; - quads[index].tr.colors = color4; - _textureAtlas->updateQuad(&quads[index], index); - } -} - -bool Label::isCascadeOpacityEnabled() const -{ - return false; -} - -void Label::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) -{ - _cascadeOpacityEnabled = cascadeOpacityEnabled; -} - -const Color3B& Label::getColor(void) const -{ - return _realColor; -} - -const Color3B& Label::getDisplayedColor() const -{ - return _displayedColor; -} - void Label::setColor(const Color3B& color) { - _displayedColor = _realColor = color; _reusedLetter->setColor(color); - if( _cascadeColorEnabled ) - { - Color3B parentColor = Color3B::WHITE; - RGBAProtocol* pParent = dynamic_cast(_parent); - - if (pParent && pParent->isCascadeColorEnabled()) - parentColor = pParent->getDisplayedColor(); - - updateDisplayedColor(parentColor); - } + SpriteBatchNode::setColor(color); } -void Label::updateDisplayedColor(const Color3B& parentColor) +void Label::updateColor() { - _displayedColor.r = _realColor.r * parentColor.r/255.0; - _displayedColor.g = _realColor.g * parentColor.g/255.0; - _displayedColor.b = _realColor.b * parentColor.b/255.0; - - _children.forEach([this](Node* child){ - Sprite *item = static_cast( child ); - item->updateDisplayedColor(_displayedColor); - }); - V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); auto count = _textureAtlas->getTotalQuads(); Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); - + // special opacity for premultiplied textures if (_isOpacityModifyRGB) { @@ -717,29 +731,19 @@ void Label::updateDisplayedColor(const Color3B& parentColor) color4.b *= _displayedOpacity/255.0f; } for (int index=0; indexupdateQuad(&quads[index], index); - } -} - -bool Label::isCascadeColorEnabled() const -{ - return false; -} - -void Label::setCascadeColorEnabled(bool cascadeColorEnabled) -{ - _cascadeColorEnabled = cascadeColorEnabled; + } } std::string Label::getDescription() const { - return StringUtils::format("