From 567f75c31b49bba84c5c54497c8df268562bcaaa Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Sat, 14 Sep 2013 15:52:41 +0800 Subject: [PATCH 001/197] upload CCArmatureDefine.cpp --- extensions/Android.mk | 4 --- .../Armature/utils/CCArmatureDefine.cpp | 34 +++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp diff --git a/extensions/Android.mk b/extensions/Android.mk index b0c6196ec7..34af4f3a73 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -69,12 +69,8 @@ CocoStudio/Armature/display/CCBatchNode.cpp \ CocoStudio/Armature/display/CCDecorativeDisplay.cpp \ CocoStudio/Armature/display/CCDisplayFactory.cpp \ CocoStudio/Armature/display/CCDisplayManager.cpp \ -CocoStudio/Armature/display/CCShaderNode.cpp \ CocoStudio/Armature/display/CCSkin.cpp \ -CocoStudio/Armature/external_tool/CCTexture2DMutable.cpp \ -CocoStudio/Armature/external_tool/GLES-Render.cpp \ CocoStudio/Armature/physics/CCColliderDetector.cpp \ -CocoStudio/Armature/physics/CCPhysicsWorld.cpp \ CocoStudio/Armature/utils/CCArmatureDataManager.cpp \ CocoStudio/Armature/utils/CCDataReaderHelper.cpp \ CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.cpp \ diff --git a/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp new file mode 100644 index 0000000000..cbd53fe1e0 --- /dev/null +++ b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** +Copyright (c) 2013 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "CCArmatureDefine.h" + +NS_CC_EXT_ARMATURE_BEGIN + +const char *armatureVersion() +{ + return "0.4.0.0"; +} + +NS_CC_EXT_ARMATURE_END From e1acbb6af4098417e4862c9c015088619ba07027 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Sun, 22 Sep 2013 13:53:25 +0800 Subject: [PATCH 002/197] fix setcolor --- extensions/CocoStudio/Armature/CCArmature.cpp | 4 +--- extensions/CocoStudio/Armature/CCBone.cpp | 11 +++++++++++ extensions/CocoStudio/Armature/CCBone.h | 15 +++++++++------ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/extensions/CocoStudio/Armature/CCArmature.cpp b/extensions/CocoStudio/Armature/CCArmature.cpp index d7817b16b1..8486000dc1 100644 --- a/extensions/CocoStudio/Armature/CCArmature.cpp +++ b/extensions/CocoStudio/Armature/CCArmature.cpp @@ -128,9 +128,7 @@ bool Armature::init(const char *name) _topBoneList = new Array(); _topBoneList->init(); - - _blendFunc.src = CC_BLEND_SRC; - _blendFunc.dst = CC_BLEND_DST; + _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; _name = name == NULL ? "" : name; diff --git a/extensions/CocoStudio/Armature/CCBone.cpp b/extensions/CocoStudio/Armature/CCBone.cpp index e6063e51c3..a5f59d7a16 100644 --- a/extensions/CocoStudio/Armature/CCBone.cpp +++ b/extensions/CocoStudio/Armature/CCBone.cpp @@ -211,6 +211,17 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } +void Bone::setColor(const Color3B& color) +{ + CCNodeRGBA::setColor(color); + updateColor(); +} +void Bone::setOpacity(GLubyte opacity) +{ + CCNodeRGBA::setOpacity(opacity); + updateColor(); +} + void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); diff --git a/extensions/CocoStudio/Armature/CCBone.h b/extensions/CocoStudio/Armature/CCBone.h index 9f979e616a..1aecfcb099 100644 --- a/extensions/CocoStudio/Armature/CCBone.h +++ b/extensions/CocoStudio/Armature/CCBone.h @@ -122,18 +122,21 @@ public: */ void removeChildBone(Bone *bone, bool recursion); - void update(float delta); + void update(float delta) override; - void updateDisplayedColor(const Color3B &parentColor); - void updateDisplayedOpacity(GLubyte parentOpacity); + virtual void updateDisplayedColor(const Color3B &parentColor) override; + virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; + + virtual void setColor(const Color3B& color) override; + virtual void setOpacity(GLubyte opacity) override; //! Update color to render display - void updateColor(); + virtual void updateColor(); //! Update zorder - void updateZOrder(); + virtual void updateZOrder(); - virtual void setZOrder(int zOrder); + virtual void setZOrder(int zOrder) override; Tween *getTween(); From 90d7abb3ca77d0e927c412098d4a23116380237c Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Mon, 23 Sep 2013 16:48:09 +0800 Subject: [PATCH 003/197] fix add display --- extensions/CocoStudio/Armature/CCArmature.cpp | 26 ++-- extensions/CocoStudio/Armature/CCBone.cpp | 20 ++- .../Armature/display/CCDisplayManager.cpp | 5 +- .../CocoStudio/Armature/display/CCSkin.cpp | 13 +- .../Armature/utils/CCDataReaderHelper.cpp | 114 +++++++++--------- 5 files changed, 95 insertions(+), 83 deletions(-) diff --git a/extensions/CocoStudio/Armature/CCArmature.cpp b/extensions/CocoStudio/Armature/CCArmature.cpp index 8486000dc1..c5709b0418 100644 --- a/extensions/CocoStudio/Armature/CCArmature.cpp +++ b/extensions/CocoStudio/Armature/CCArmature.cpp @@ -261,18 +261,12 @@ void Armature::addBone(Bone *bone, const char *parentName) } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } bone->setArmature(this); @@ -338,7 +332,7 @@ Dictionary *Armature::getBoneDic() return _boneDic; } -const AffineTransform& Armature::getNodeToParentTransform() const +const AffineTransform &Armature::getNodeToParentTransform() const { if (_transformDirty) { @@ -387,16 +381,16 @@ const AffineTransform& Armature::getNodeToParentTransform() const // Build Transform Matrix // Adjusted transform calculation for rotational skew _transform = AffineTransformMake( cy * _scaleX, sy * _scaleX, - -sx * _scaleY, cx * _scaleY, - x, y ); + -sx * _scaleY, cx * _scaleY, + x, y ); // XXX: Try to inline skew // If skew is needed, apply skew and then anchor point if (needsSkewMatrix) { AffineTransform skewMatrix = AffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(_skewY)), - tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, - 0.0f, 0.0f ); + tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, + 0.0f, 0.0f ); _transform = AffineTransformConcat(skewMatrix, _transform); // adjust anchor point @@ -452,7 +446,7 @@ void Armature::update(float dt) Object *object = NULL; CCARRAY_FOREACH(_topBoneList, object) { - static_cast(object)->update(dt); + static_cast(object)->update(dt); } _armatureTransformDirty = false; @@ -523,6 +517,8 @@ void Armature::draw() } } armature->draw(); + + _atlas = armature->getTextureAtlas(); } break; default: @@ -679,7 +675,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) for(int i = length - 1; i >= 0; i--) { - bs = static_cast( _children->getObjectAtIndex(i) ); + bs = static_cast( _children->getObjectAtIndex(i) ); if(bs->getDisplayManager()->containPoint(x, y)) { return bs; diff --git a/extensions/CocoStudio/Armature/CCBone.cpp b/extensions/CocoStudio/Armature/CCBone.cpp index a5f59d7a16..d9ad2bfdc7 100644 --- a/extensions/CocoStudio/Armature/CCBone.cpp +++ b/extensions/CocoStudio/Armature/CCBone.cpp @@ -165,6 +165,13 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); + CCBone *armatureParentBone = _armature->getParentBone(); + if (armatureParentBone && !_boneTransformDirty) + { + _boneTransformDirty = armatureParentBone->isTransformDirty(); + } + + if (_boneTransformDirty) { if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) @@ -182,6 +189,13 @@ void Bone::update(float delta) { _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); } + else + { + if (armatureParentBone) + { + _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); + } + } } DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); @@ -211,15 +225,15 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } -void Bone::setColor(const Color3B& color) +void Bone::setColor(const Color3B &color) { CCNodeRGBA::setColor(color); - updateColor(); + updateColor(); } void Bone::setOpacity(GLubyte opacity) { CCNodeRGBA::setOpacity(opacity); - updateColor(); + updateColor(); } void Bone::updateColor() diff --git a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp b/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp index 01103f392d..ae69ea8230 100644 --- a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp +++ b/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp @@ -135,6 +135,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); + ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { @@ -256,8 +257,8 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) if (RGBAProtocol *rgbaProtocaol = dynamic_cast(_displayRenderNode)) { - rgbaProtocaol->setColor(_bone->getDisplayedColor()); - rgbaProtocaol->setOpacity(_bone->getDisplayedOpacity()); + rgbaProtocaol->setColor(_bone->getDisplayedColor()); + rgbaProtocaol->setOpacity(_bone->getDisplayedOpacity()); } _displayRenderNode->retain(); diff --git a/extensions/CocoStudio/Armature/display/CCSkin.cpp b/extensions/CocoStudio/Armature/display/CCSkin.cpp index 2fdf2b24af..a35bbffcbe 100644 --- a/extensions/CocoStudio/Armature/display/CCSkin.cpp +++ b/extensions/CocoStudio/Armature/display/CCSkin.cpp @@ -84,10 +84,10 @@ bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) if (ret) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); + TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); - _displayName = pszSpriteFrameName; + _displayName = pszSpriteFrameName; } return ret; @@ -99,10 +99,10 @@ bool Skin::initWithFile(const char *pszFilename) if (ret) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); + TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); - _displayName = pszFilename; + _displayName = pszFilename; } return ret; @@ -118,6 +118,7 @@ void Skin::setSkinData(const BaseData &var) setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); + updateArmatureTransform(); } const BaseData &Skin::getSkinData() const diff --git a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp index 76d56a4b8d..a053e4f490 100644 --- a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp +++ b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp @@ -136,7 +136,7 @@ static const char *CONFIG_FILE_PATH = "config_file_path"; NS_CC_EXT_ARMATURE_BEGIN - std::vector s_arrConfigFileList; +std::vector s_arrConfigFileList; float s_PositionReadScale = 1; static float s_FlashToolVersion = VERSION_2_0; static float s_CocoStudioVersion = VERSION_COMBINED; @@ -169,8 +169,8 @@ void DataReaderHelper::loadData() } else { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); + std::unique_lock lk(_sleepMutex); + _sleepCondition.wait(lk); continue; } } @@ -243,12 +243,12 @@ void DataReaderHelper::clear() } DataReaderHelper::DataReaderHelper() - : _loadingThread(nullptr) - , _asyncStructQueue(nullptr) - , _dataQueue(nullptr) - , need_quit(false) - , _asyncRefCount(0) - , _asyncRefTotalCount(0) + : _loadingThread(nullptr) + , _asyncStructQueue(nullptr) + , _dataQueue(nullptr) + , need_quit(false) + , _asyncRefCount(0) + , _asyncRefTotalCount(0) { } @@ -257,11 +257,11 @@ DataReaderHelper::~DataReaderHelper() { need_quit = true; - _sleepCondition.notify_one(); - if (_loadingThread) _loadingThread->join(); + _sleepCondition.notify_one(); + if (_loadingThread) _loadingThread->join(); - CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; + CC_SAFE_DELETE(_loadingThread); + _dataReaderHelper = NULL; } void DataReaderHelper::addDataFromFile(const char *filePath) @@ -354,15 +354,15 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target _asyncStructQueue = new std::queue(); _dataQueue = new std::queue(); - // create a new thread to load images - _loadingThread = new std::thread(&DataReaderHelper::loadData, this); + // create a new thread to load images + _loadingThread = new std::thread(&DataReaderHelper::loadData, this); need_quit = false; } if (0 == _asyncRefCount) { - Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); + Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); } ++_asyncRefCount; @@ -854,26 +854,26 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov } - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) + CCFrameData **frames = (CCFrameData **)movBoneData->frameList.data->arr; + for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) + { + if (i > 0) + { + float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; + float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } + if (difSkewX < -M_PI || difSkewX > M_PI) + { + frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + } - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } + if (difSkewY < -M_PI || difSkewY > M_PI) + { + frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + } + } + } // @@ -1429,29 +1429,29 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) } - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) - { - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movementBoneData->frameList.data->arr; - for (int i = movementBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) + { + //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) + CCFrameData **frames = (CCFrameData **)movementBoneData->frameList.data->arr; + for (int i = movementBoneData->frameList.count() - 1; i >= 0; i--) + { + if (i > 0) + { + float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; + float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } + if (difSkewX < -M_PI || difSkewX > M_PI) + { + frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + } - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } - } + if (difSkewY < -M_PI || difSkewY > M_PI) + { + frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + } + } + } + } if (s_CocoStudioVersion < VERSION_COMBINED) { @@ -1478,7 +1478,7 @@ FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json) frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); - frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); + frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); const char *event = json.getItemStringValue(A_EVENT); if (event != NULL) @@ -1531,7 +1531,7 @@ TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) { ContourData *contourData = new ContourData(); - contourData->init(); + contourData->init(); int length = json.getArrayItemCount(VERTEX_POINT); for (int i = length - 1; i >= 0; i--) From 6f5e7d540e7039e1ddc818ea997259ac4e2c0b65 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 24 Sep 2013 23:22:07 +0800 Subject: [PATCH 004/197] remove cc --- extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp index a053e4f490..45b63c4db5 100644 --- a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp +++ b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp @@ -855,7 +855,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movBoneData->frameList.data->arr; + FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) { if (i > 0) From 8f2f524f2d4c131037817b9913208fe3858b7903 Mon Sep 17 00:00:00 2001 From: dualface Date: Fri, 18 Oct 2013 11:30:28 +0800 Subject: [PATCH 005/197] fix tolua_fix, cleanup peertable after object deleted --- cocos/scripting/lua/bindings/tolua_fix.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/tolua_fix.c b/cocos/scripting/lua/bindings/tolua_fix.c index 870db00d75..259a05242e 100644 --- a/cocos/scripting/lua/bindings/tolua_fix.c +++ b/cocos/scripting/lua/bindings/tolua_fix.c @@ -128,7 +128,11 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pop(L, 3); return -3; } - + + // cleanup peertable + lua_pushvalue(L, TOLUA_NOPEER); + lua_setfenv(L, -2); + ud = (void**)lua_touserdata(L, -1); lua_pop(L, 1); /* stack: mt ubox */ if (ud == NULL) From 969b464b9b4097a6b57aa92182788a825763abcf Mon Sep 17 00:00:00 2001 From: ondesly Date: Wed, 23 Oct 2013 12:29:59 +0400 Subject: [PATCH 006/197] android & ios screen size change support --- cocos/2d/platform/android/CCApplication.cpp | 4 +++ cocos/2d/platform/android/CCApplication.h | 7 +++++ cocos/2d/platform/android/nativeactivity.cpp | 27 +++++++++++++++++++ cocos/2d/platform/ios/CCApplication.h | 7 +++++ cocos/2d/platform/ios/CCApplication.mm | 4 +++ .../proj.ios_mac/ios/RootViewController.mm | 11 +++++++- .../proj.ios_mac/ios/RootViewController.mm | 12 +++++++-- .../proj.ios_mac/ios/RootViewController.mm | 11 +++++++- 8 files changed, 79 insertions(+), 4 deletions(-) diff --git a/cocos/2d/platform/android/CCApplication.cpp b/cocos/2d/platform/android/CCApplication.cpp index 61b3f288cd..07c5814b3e 100644 --- a/cocos/2d/platform/android/CCApplication.cpp +++ b/cocos/2d/platform/android/CCApplication.cpp @@ -128,4 +128,8 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_ANDROID; } +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} + NS_CC_END diff --git a/cocos/2d/platform/android/CCApplication.h b/cocos/2d/platform/android/CCApplication.h index e321266c81..d9b7d00f34 100644 --- a/cocos/2d/platform/android/CCApplication.h +++ b/cocos/2d/platform/android/CCApplication.h @@ -50,6 +50,13 @@ public: */ virtual Platform getTargetPlatform(); + /** + @brief This function will be called when the application screen size is changed. + @param new width + @param new height + */ + virtual void applicationScreenSizeChanged(int newWidth, int newHeight); + protected: static Application * sm_pSharedApplication; }; diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index fa4fb434d4..1cc60c406c 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -12,6 +12,7 @@ #include #include +#include #include "CCDirector.h" #include "CCApplication.h" @@ -69,6 +70,9 @@ struct engine { struct saved_state state; }; +static bool isContentRectChanged = false; +static std::chrono::steady_clock::time_point timeRectChanged; + static struct engine engine; static char* editboxText = NULL; @@ -556,6 +560,11 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { } } +static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { + timeRectChanged = std::chrono::steady_clock::now(); + isContentRectChanged = true; +} + /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own @@ -584,6 +593,9 @@ void android_main(struct android_app* state) { engine.state = *(struct saved_state*)state->savedState; } + // Screen size change support + state->activity->callbacks->onContentRectChanged = onContentRectChanged; + // loop waiting for stuff to do. while (1) { @@ -671,5 +683,20 @@ void android_main(struct android_app* state) { } else { LOG_RENDER_DEBUG("android_main : !engine.animating"); } + + // Check if screen size changed + if (isContentRectChanged) { + std::chrono::duration duration( + std::chrono::duration_cast>(std::chrono::steady_clock::now() - timeRectChanged)); + + // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime + if (duration.count() > 30) { + isContentRectChanged = false; + + int32_t newWidth = ANativeWindow_getWidth(engine.app->window); + int32_t newHeight = ANativeWindow_getHeight(engine.app->window); + cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); + } + } } } diff --git a/cocos/2d/platform/ios/CCApplication.h b/cocos/2d/platform/ios/CCApplication.h index 86be67bd29..a281a4f554 100644 --- a/cocos/2d/platform/ios/CCApplication.h +++ b/cocos/2d/platform/ios/CCApplication.h @@ -76,6 +76,13 @@ public: */ virtual Platform getTargetPlatform(); + /** + @brief This function will be called when the application screen size is changed. + @param new width + @param new height + */ + virtual void applicationScreenSizeChanged(int newWidth, int newHeight); + protected: static Application * sm_pSharedApplication; }; diff --git a/cocos/2d/platform/ios/CCApplication.mm b/cocos/2d/platform/ios/CCApplication.mm index 8c8d543c2e..c09a0aa8a9 100644 --- a/cocos/2d/platform/ios/CCApplication.mm +++ b/cocos/2d/platform/ios/CCApplication.mm @@ -146,4 +146,8 @@ Application::Platform Application::getTargetPlatform() } } +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} + NS_CC_END diff --git a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm index 906aeaf082..187b274b91 100644 --- a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm @@ -1,5 +1,6 @@ #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -43,6 +44,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm index a0f626dcd6..187b274b91 100644 --- a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm @@ -1,6 +1,6 @@ - #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -44,6 +44,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm index a00da00584..093a9b4c3a 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm @@ -24,7 +24,8 @@ ****************************************************************************/ #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -68,6 +69,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { From fdcf0196659fd97de2d58643fbb77b937ab32204 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 25 Oct 2013 10:31:22 +0800 Subject: [PATCH 007/197] issue #2771: implement contact callbacks --- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsContact.cpp | 103 ++++++++++++++++++++--------- cocos/physics/CCPhysicsContact.h | 56 +++++++++++++--- cocos/physics/CCPhysicsJoint.cpp | 8 +-- cocos/physics/CCPhysicsSetting.h | 5 ++ cocos/physics/CCPhysicsShape.cpp | 4 +- cocos/physics/CCPhysicsWorld.cpp | 42 +++++++++--- cocos/physics/CCPhysicsWorld.h | 6 +- 8 files changed, 164 insertions(+), 62 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index f1715b0f1a..ad3ea332fa 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -142,7 +142,7 @@ public: /* * @brief get all joints the body have */ - inline const std::vector* getJoints() const { return &_joints; } + inline const std::vector& getJoints() const { return _joints; } /* * @brief get the sprite the body set to. diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 1ec9667d6f..71ed2beb01 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -32,6 +32,8 @@ #include "chipmunk/CCPhysicsContactInfo.h" #include "box2d/CCPhysicsContactInfo.h" +#include "chipmunk/CCPhysicsHelper.h" +#include "box2d/CCPhysicsHelper.h" NS_CC_BEGIN @@ -39,7 +41,11 @@ PhysicsContact::PhysicsContact() : _shapeA(nullptr) , _shapeB(nullptr) , _info(nullptr) +, _notify(true) +, _begin(false) , _data(nullptr) +, _contactInfo(nullptr) +, _contactData(nullptr) { } @@ -47,6 +53,7 @@ PhysicsContact::PhysicsContact() PhysicsContact::~PhysicsContact() { CC_SAFE_DELETE(_info); + CC_SAFE_DELETE(_contactData); } PhysicsContact* PhysicsContact::create(PhysicsShape* a, PhysicsShape* b) @@ -78,37 +85,69 @@ bool PhysicsContact::init(PhysicsShape* a, PhysicsShape* b) return false; } -// PhysicsContactPreSolve implementation -PhysicsContactPreSolve::PhysicsContactPreSolve() +void PhysicsContact::generateContactData() { + if (_contactInfo == nullptr) + { + return; + } + cpArbiter* arb = (cpArbiter*)_contactInfo; + _contactData = new PhysicsContactData(); + _contactData->count = cpArbiterGetCount(arb); + for (int i=0; i<_contactData->count; ++i) + { + _contactData->points[i] = PhysicsHelper::cpv2point(cpArbiterGetPoint(arb, i)); + } + + _contactData->normal = _contactData->count > 0 ? PhysicsHelper::cpv2point(cpArbiterGetNormal(arb, 0)) : Point::ZERO; +} + +// PhysicsContactPreSolve implementation +PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo) +: _preContactData(data) +, _contactInfo(contactInfo) +{ +} + +float PhysicsContactPreSolve::getElasticity() +{ + return ((cpArbiter*)_contactInfo)->e; +} + +float PhysicsContactPreSolve::getFriciton() +{ + return ((cpArbiter*)_contactInfo)->u; +} + +Point PhysicsContactPreSolve::getSurfaceVelocity() +{ + return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); +} + +void PhysicsContactPreSolve::setElasticity(float elasticity) +{ + ((cpArbiter*)_contactInfo)->e = elasticity; +} + +void PhysicsContactPreSolve::setFriction(float friction) +{ + ((cpArbiter*)_contactInfo)->u = friction; +} + +void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) +{ + ((cpArbiter*)_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); } PhysicsContactPreSolve::~PhysicsContactPreSolve() { - + CC_SAFE_DELETE(_preContactData); } -PhysicsContactPreSolve* PhysicsContactPreSolve::create() -{ - PhysicsContactPreSolve * solve = new PhysicsContactPreSolve(); - if(solve && solve->init()) - { - return solve; - } - - CC_SAFE_DELETE(solve); - return nullptr; -} - -bool PhysicsContactPreSolve::init() -{ - return true; -} - - // PhysicsContactPostSolve implementation -PhysicsContactPostSolve::PhysicsContactPostSolve() +PhysicsContactPostSolve::PhysicsContactPostSolve(void* contactInfo) +: _contactInfo(contactInfo) { } @@ -118,21 +157,19 @@ PhysicsContactPostSolve::~PhysicsContactPostSolve() } -PhysicsContactPostSolve* PhysicsContactPostSolve::create() +float PhysicsContactPostSolve::getElasticity() { - PhysicsContactPostSolve * solve = new PhysicsContactPostSolve(); - if(solve && solve->init()) - { - return solve; - } - - CC_SAFE_DELETE(solve); - return nullptr; + return ((cpArbiter*)_contactInfo)->e; } -bool PhysicsContactPostSolve::init() +float PhysicsContactPostSolve::getFriciton() { - return true; + return ((cpArbiter*)_contactInfo)->u; +} + +Point PhysicsContactPostSolve::getSurfaceVelocity() +{ + return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); } PhysicsContactListener::PhysicsContactListener() diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 9b9e3044c0..6c96539c92 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -38,6 +38,18 @@ class PhysicsWorld; class PhysicsContactInfo; + +typedef struct PhysicsContactData +{ + Point points[PHYSICS_CONTACT_POINT_MAX]; + int count; + Point normal; + + PhysicsContactData() + : count(0) + {} +}PhysicsContactData; + /** * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. */ @@ -52,6 +64,7 @@ public: * @brief get contact shape B. */ inline PhysicsShape* getShapeB() const { return _shapeB; } + inline const PhysicsContactData* getContactData() const { return _contactData; } /* * @brief get data. */ @@ -68,6 +81,8 @@ private: inline bool getNotify() { return _notify; } inline void setNotify(bool notify) { _notify = notify; } + void generateContactData(); + private: PhysicsContact(); ~PhysicsContact(); @@ -76,8 +91,12 @@ private: PhysicsShape* _shapeA; PhysicsShape* _shapeB; PhysicsContactInfo* _info; - void* _data; bool _notify; + bool _begin; + + void* _data; + void* _contactInfo; + PhysicsContactData* _contactData; friend class PhysicsWorld; friend class PhysicsWorldCallback; @@ -88,14 +107,27 @@ private: */ class PhysicsContactPreSolve { +public: + // getter/setter + float getElasticity(); + float getFriciton(); + Point getSurfaceVelocity(); + void setElasticity(float elasticity); + void setFriction(float friction); + void setSurfaceVelocity(Point surfaceVelocity); + private: - PhysicsContactPreSolve(); + PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo); ~PhysicsContactPreSolve(); - static PhysicsContactPreSolve* create(); - bool init(); +private: + float _elasticity; + float _friction; + Point _surfaceVelocity; + PhysicsContactData* _preContactData; + void* _contactInfo; - friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* @@ -103,14 +135,20 @@ private: */ class PhysicsContactPostSolve { +public: + // getter + float getElasticity(); + float getFriciton(); + Point getSurfaceVelocity(); + private: - PhysicsContactPostSolve(); + PhysicsContactPostSolve(void* contactInfo); ~PhysicsContactPostSolve(); - static PhysicsContactPostSolve* create(); - bool init(); +private: + void* _contactInfo; - friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 6cca90dd5b..5e475bf367 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -161,10 +161,10 @@ void PhysicsJoint::setCollisionEnable(bool enable) { _collisionEnable = enable; - for (auto shape : _bodyB->_shapes) - { - shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); - } +// for (auto shape : _bodyB->_shapes) +// { +// shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); +// } } } diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index b29b12054d..ee3214bcd7 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -46,6 +46,11 @@ namespace cocos2d { extern const float PHYSICS_INFINITY; + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + static const int PHYSICS_CONTACT_POINT_MAX = 4; +#else +#endif } #endif // __CCPHYSICS_SETTING_H__ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 6ffd7d86aa..77634e9113 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -272,12 +272,12 @@ void PhysicsShape::setBody(PhysicsBody *body) if (body == nullptr) { _info->setBody(nullptr); - _info->setGroup(CP_NO_GROUP); + //_info->setGroup(CP_NO_GROUP); _body = nullptr; }else { _info->setBody(body->_info->body); - _info->setGroup(body->_info->group); + //_info->setGroup(body->_info->group); _body = body; } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 9085805e1d..451c7b82a2 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -60,6 +60,8 @@ NS_CC_BEGIN #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +const float PHYSICS_INFINITY = INFINITY; + namespace { typedef struct RayCastCallbackInfo @@ -96,8 +98,6 @@ public: bool PhysicsWorldCallback::continues = true; -const float PHYSICS_INFINITY = INFINITY; - int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, PhysicsWorld *world) { CP_ARBITER_GET_SHAPES(arb, a, b); @@ -108,20 +108,19 @@ int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSp PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); arb->data = contact; + contact->_contactInfo = arb; - return world->collisionBeginCallback(*static_cast(arb->data)); + return world->collisionBeginCallback(*contact); } int PhysicsWorldCallback::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - return world->collisionPreSolveCallback(*static_cast(arb->data), - PhysicsContactPreSolve()); + return world->collisionPreSolveCallback(*static_cast(arb->data)); } void PhysicsWorldCallback::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - world->collisionPostSolveCallback(*static_cast(arb->data), - PhysicsContactPostSolve()); + world->collisionPostSolveCallback(*static_cast(arb->data)); } void PhysicsWorldCallback::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) @@ -445,7 +444,24 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) bool ret = true; PhysicsBody* bodyA = contact.getShapeA()->getBody(); PhysicsBody* bodyB = contact.getShapeB()->getBody(); + std::vector jointsA = bodyA->getJoints(); + // check the joint is collision enable or not + for (PhysicsJoint* joint : jointsA) + { + if (!joint->isCollisionEnable()) + { + PhysicsBody* body = joint->getBodyA() == bodyA ? bodyB : bodyA; + + if (body == bodyB) + { + contact.setNotify(false); + return false; + } + } + } + + // bitmask check if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0 || (bodyB->getContactTestBitmask() & bodyA->getCategoryBitmask()) == 0) { @@ -460,6 +476,9 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if (contact.getNotify() && _listener && _listener->onContactBegin) { + contact._begin = true; + contact.generateContactData(); + // the mask has high priority than _listener->onContactBegin. // so if the mask test is false, the two bodies won't have collision. if (ret) @@ -474,7 +493,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) return ret; } -int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve) +int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { if (!contact.getNotify()) { @@ -483,13 +502,17 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const Physi if (_listener && _listener->onContactPreSolve) { + PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); + contact._begin = false; + contact.generateContactData(); + return _listener->onContactPreSolve(*this, contact, solve); } return true; } -void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve) +void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { if (!contact.getNotify()) { @@ -498,6 +521,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const Phy if (_listener && _listener->onContactPreSolve) { + PhysicsContactPostSolve solve(contact._contactInfo); _listener->onContactPostSolve(*this, contact, solve); } } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 63c841cc93..34528d6270 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -40,8 +40,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class PhysicsContactPreSolve; -class PhysicsContactPostSolve; class PhysicsContactListener; class Array; @@ -135,8 +133,8 @@ protected: virtual int collisionBeginCallback(PhysicsContact& contact); - virtual int collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve); - virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); + virtual int collisionPreSolveCallback(PhysicsContact& contact); + virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); protected: From d0d869409195a4c9606b17486061ee3ce22028ea Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 28 Oct 2013 11:08:41 +0800 Subject: [PATCH 008/197] issue #2771: fix some retain/release bugs --- cocos/2d/CCNode.cpp | 8 + cocos/physics/CCPhysicsBody.cpp | 93 ++++++++-- cocos/physics/CCPhysicsBody.h | 11 +- cocos/physics/CCPhysicsJoint.cpp | 17 +- cocos/physics/CCPhysicsJoint.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 166 +++++++++++++----- cocos/physics/CCPhysicsWorld.h | 1 + .../Classes/PhysicsTest/PhysicsTest.cpp | 68 +++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 12 +- 9 files changed, 280 insertions(+), 98 deletions(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 2145829c34..99283b95a8 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -749,6 +749,14 @@ void Node::detachChild(Node *child, int childIndex, bool doCleanup) child->onExitTransitionDidStart(); child->onExit(); } + +#ifdef CC_USE_PHYSICS + if (child->_physicsBody != nullptr) + { + child->_physicsBody->removeFromWorld(); + } + +#endif // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 109fac9d6f..e3335c7c16 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -62,6 +62,7 @@ namespace PhysicsBody::PhysicsBody() : _owner(nullptr) +, _shapes(nullptr) , _world(nullptr) , _info(nullptr) , _dynamic(true) @@ -85,18 +86,23 @@ PhysicsBody::PhysicsBody() PhysicsBody::~PhysicsBody() { - CC_SAFE_DELETE(_info); + if (_world) + { + removeFromWorld(); + } removeAllShapes(); for (auto it = _joints.begin(); it != _joints.end(); ++it) { PhysicsJoint* joint = *it; - PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyA() : joint->getBodyB(); + PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA(); other->_joints.erase(std::find(other->_joints.begin(), other->_joints.end(), joint)); + delete joint; } + CC_SAFE_DELETE(_info); } PhysicsBody* PhysicsBody::create() @@ -112,6 +118,45 @@ PhysicsBody* PhysicsBody::create() return nullptr; } +PhysicsBody* PhysicsBody::create(float mass) +{ + PhysicsBody* body = new PhysicsBody(); + if (body) + { + body->_mass = mass; + body->_massDefault = false; + if (body->init()) + { + body->autorelease(); + return body; + } + } + + CC_SAFE_DELETE(body); + return nullptr; +} + +PhysicsBody* PhysicsBody::create(float mass, float moment) +{ + PhysicsBody* body = new PhysicsBody(); + if (body) + { + body->_mass = mass; + body->_massDefault = false; + body->_moment = moment; + body->_momentDefault = false; + if (body->init()) + { + body->autorelease(); + return body; + } + } + + CC_SAFE_DELETE(body); + return nullptr; + +} + PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); @@ -223,6 +268,9 @@ bool PhysicsBody::init() { _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); + _shapes = Array::create(); + CC_BREAK_IF(_shapes == nullptr); + _shapes->retain(); _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); _info->group = ++GROUP_INDEX; @@ -308,10 +356,9 @@ void PhysicsBody::addShape(PhysicsShape* shape) if (shape == nullptr) return; // add shape to body - if (std::find(_shapes.begin(), _shapes.end(), shape) == _shapes.end()) + if (_shapes->getIndexOfObject(shape) == UINT_MAX) { shape->setBody(this); - _shapes.push_back(shape); // calculate the area, mass, and desity // area must update before mass, because the density changes depend on it. @@ -324,7 +371,7 @@ void PhysicsBody::addShape(PhysicsShape* shape) _world->addShape(shape); } - shape->retain(); + _shapes->addObject(shape); } } @@ -519,8 +566,9 @@ void PhysicsBody::setMoment(float moment) PhysicsShape* PhysicsBody::getShapeByTag(int tag) { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { return shape; @@ -532,8 +580,9 @@ PhysicsShape* PhysicsBody::getShapeByTag(int tag) void PhysicsBody::removeShapeByTag(int tag) { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { removeShape(shape); @@ -544,9 +593,7 @@ void PhysicsBody::removeShapeByTag(int tag) void PhysicsBody::removeShape(PhysicsShape* shape) { - auto it = std::find(_shapes.begin(), _shapes.end(), shape); - - if (it != _shapes.end()) + if (_shapes->getIndexOfObject(shape) == UINT_MAX) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -559,25 +606,39 @@ void PhysicsBody::removeShape(PhysicsShape* shape) { _world->removeShape(shape); } - _shapes.erase(it); shape->setBody(nullptr); - shape->release(); + _shapes->removeObject(shape); } } void PhysicsBody::removeAllShapes() { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); + + // deduce the area, mass and moment + // area must update before mass, because the density changes depend on it. + _area -= shape->getArea(); + addMass(-shape->getMass()); + addMoment(-shape->getMoment()); + if (_world) { _world->removeShape(shape); } - - delete shape; + shape->setBody(nullptr); } - _shapes.clear(); + _shapes->removeAllObjects(); +} + +void PhysicsBody::removeFromWorld() +{ + if (_world) + { + _world->removeBody(this); + } } void PhysicsBody::setEnable(bool enable) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index ad3ea332fa..c1a3d4b1a1 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -30,6 +30,7 @@ #include "CCObject.h" #include "CCGeometry.h" +#include "CCArray.h" #include "CCPhysicsShape.h" @@ -53,6 +54,8 @@ class PhysicsBody : public Object//, public Clonable { public: static PhysicsBody* create(); + static PhysicsBody* create(float mass); + static PhysicsBody* create(float mass, float moment); /** * @brief Create a body contains a circle shape. */ @@ -119,11 +122,11 @@ public: /* * @brief get the body shapes. */ - inline std::vector& getShapes() { return _shapes; } + inline Array* getShapes() { return _shapes; } /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() { return _shapes.size() >= 1 ? _shapes.front() : nullptr; } + inline PhysicsShape* getShape() { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } PhysicsShape* getShapeByTag(int tag); /* * @brief remove a shape from body @@ -135,6 +138,8 @@ public: */ void removeAllShapes(); + void removeFromWorld(); + /* * @brief get the world body added to. */ @@ -258,7 +263,7 @@ protected: protected: Sprite* _owner; std::vector _joints; - std::vector _shapes; + Array* _shapes; PhysicsWorld* _world; PhysicsBodyInfo* _info; bool _dynamic; diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 5e475bf367..c7ca4ef2f9 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -61,9 +61,6 @@ PhysicsJoint::~PhysicsJoint() setCollisionEnable(true); CC_SAFE_DELETE(_info); - - CC_SAFE_RELEASE(_bodyA); - CC_SAFE_RELEASE(_bodyB); } bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) @@ -75,14 +72,12 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) if (a != nullptr) { _bodyA = a; - _bodyA->retain(); _bodyA->_joints.push_back(this); } if (b != nullptr) { _bodyB = b; - _bodyB->retain(); _bodyB->_joints.push_back(this); } @@ -174,7 +169,6 @@ PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, con if (joint && joint->init(a, b, anchr)) { - joint->autorelease(); return joint; } @@ -191,12 +185,12 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) // add a pivot joint to fixed two body together cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. joint = cpGearJointNew(bodyInfo(a)->body, bodyInfo(b)->body, 0, 1); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); setCollisionEnable(false); @@ -213,7 +207,6 @@ PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const P if (joint && joint->init(a, b, anchr)) { - joint->autorelease(); return joint; } @@ -230,7 +223,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -266,7 +259,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -302,7 +295,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 0, PhysicsHelper::float2cpfloat(anchr1.getDistance(anchr2))); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 04f85d0d0c..67e05cb858 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -40,7 +40,7 @@ class PhysicsBodyInfo; /* * @brief An PhysicsJoint object connects two physics bodies together. */ -class PhysicsJoint : public Object +class PhysicsJoint { protected: PhysicsJoint(); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 451c7b82a2..915daa040e 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -177,18 +177,27 @@ void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distanc bool PhysicsWorld::init() { - _info = new PhysicsWorldInfo(); + do + { + _info = new PhysicsWorldInfo(); + CC_BREAK_IF(_info == nullptr); + _bodys = Array::create(); + CC_BREAK_IF(_bodys == nullptr); + _bodys->retain(); + + cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); + + cpSpaceSetDefaultCollisionHandler(_info->space, + (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, + (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, + (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, + (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, + this); + + return true; + } while (false); - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); - - cpSpaceSetDefaultCollisionHandler(_info->space, - (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, - (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, - (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, - (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, - this); - - return true; + return false; } void PhysicsWorld::addJoint(PhysicsJoint* joint) @@ -197,8 +206,6 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) if (it == _joints.end()) { - _joints.push_back(joint); - for (auto subjoint : joint->_info->joints) { if (!cpSpaceContainsConstraint(_info->space, subjoint)) @@ -206,18 +213,44 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) cpSpaceAddConstraint(_info->space, subjoint); } } + + _joints.push_back(joint); } } void PhysicsWorld::removeJoint(PhysicsJoint* joint) { + auto it = std::find(_joints.begin(), _joints.end(), joint); + if (it != _joints.end()) + { + for (auto subjoint : joint->_info->joints) + { + if (cpSpaceContainsConstraint(_info->space, subjoint)) + { + cpSpaceRemoveConstraint(_info->space, subjoint); + } + } + + _joints.remove(joint); + } } void PhysicsWorld::removeAllJoints() { + for (auto joint : _joints) + { + for (auto subjoint : joint->_info->joints) + { + if (!cpSpaceContainsConstraint(_info->space, subjoint)) + { + cpSpaceRemoveConstraint(_info->space, subjoint); + } + } + } + _joints.clear(); } void PhysicsWorld::addShape(PhysicsShape* shape) @@ -243,8 +276,15 @@ void PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); + if (body->getWorld() != this && body->getWorld() != nullptr) + { + body->removeFromWorld(); + } + if (body->isEnable()) { + body->_world = this; + //is gravity enable if (!body->isGravityEnable()) { @@ -258,45 +298,40 @@ void PhysicsWorld::addBody(PhysicsBody* body) } // add shapes to space - for (auto shape : body->getShapes()) + for (auto shape : *body->getShapes()) { - addShape(shape); + addShape(dynamic_cast(shape)); } } - if (_bodys == nullptr) - { - _bodys = Array::create(body, NULL); - _bodys->retain(); - }else - { - _bodys->addObject(body); - } + _bodys->addObject(body); } void PhysicsWorld::removeBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() == this) + if (body->getWorld() != this) { - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } + return; + } + + // reset the gravity + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + } + + // remove joints + for (auto joint : body->_joints) + { + removeJoint(joint); } // remove shaps - for (auto shape : body->getShapes()) + for (auto shape : *body->getShapes()) { - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } + removeShape(dynamic_cast(shape)); } // remove body @@ -305,10 +340,8 @@ void PhysicsWorld::removeBody(PhysicsBody* body) cpSpaceRemoveBody(_info->space, body->_info->body); } - if (_bodys != nullptr) - { - _bodys->removeObject(body); - } + body->_world = nullptr; + _bodys->removeObject(body); } void PhysicsWorld::removeBodyByTag(int tag) @@ -324,6 +357,43 @@ void PhysicsWorld::removeBodyByTag(int tag) } } +void PhysicsWorld::removeAllBodys() +{ + for (Object* obj : *_bodys) + { + PhysicsBody* body = dynamic_cast(obj); + + // reset the gravity + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + } + + // remove joints + for (auto joint : body->_joints) + { + removeJoint(joint); + } + + // remove shaps + for (auto shape : *body->getShapes()) + { + removeShape(dynamic_cast(shape)); + } + + // remove body + if (cpSpaceContainsBody(_info->space, body->_info->body)) + { + cpSpaceRemoveBody(_info->space, body->_info->body); + } + + body->_world = nullptr; + } + + _bodys->removeAllObjects(); + CC_SAFE_RELEASE(_bodys); +} + void PhysicsWorld::removeShape(PhysicsShape* shape) { for (auto cps : shape->_info->shapes) @@ -366,11 +436,9 @@ void PhysicsWorld::debugDraw() { PhysicsBody* body = dynamic_cast(obj); - std::vector shapes = body->getShapes(); - - for (auto shape : shapes) + for (auto shape : *body->getShapes()) { - drawWithShape(_drawNode, shape); + drawWithShape(_drawNode, dynamic_cast(shape)); } } @@ -449,6 +517,11 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) // check the joint is collision enable or not for (PhysicsJoint* joint : jointsA) { + if (std::find(_joints.begin(), _joints.end(), joint) == _joints.end()) + { + continue; + } + if (!joint->isCollisionEnable()) { PhysicsBody* body = joint->getBodyA() == bodyA ? bodyB : bodyA; @@ -657,8 +730,9 @@ PhysicsWorld::PhysicsWorld() PhysicsWorld::~PhysicsWorld() { + removeAllBodys(); + removeAllJoints(); CC_SAFE_DELETE(_info); - CC_SAFE_RELEASE(_bodys); } NS_CC_END diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 34528d6270..9fa8b28240 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -116,6 +116,7 @@ public: virtual void removeBody(PhysicsBody* body); virtual void removeBodyByTag(int tag); + virtual void removeAllBodys(); protected: static PhysicsWorld* create(); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f0ceb3553c..304981c448 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -92,7 +92,6 @@ PhysicsDemo::PhysicsDemo() : _scene(nullptr) , _ball(nullptr) , _spriteTexture(nullptr) -, _mouse(nullptr) { } @@ -160,7 +159,7 @@ void PhysicsDemo::onEnter() #endif } -void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) +Sprite* PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) { #ifdef CC_USE_PHYSICS CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); @@ -178,6 +177,8 @@ void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); this->addChild(sp); sp->setPosition(p); + + return sp; #endif } @@ -367,28 +368,60 @@ Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial m return triangle; } -void PhysicsDemo::onTouchesBegan(const std::vector& touches, Event* event) +bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { - for( auto &touch: touches) + auto location = touch->getLocation(); + Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + + PhysicsShape* shape = nullptr; + for (Object* obj : *arr) { - auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + shape = dynamic_cast(obj); - PhysicsShape* shape = nullptr; - for (Object* obj : *arr) + if (shape->getTag() == 1) { - + break; } } + + if (shape != nullptr) + { + + Node* mouse = Node::create(); + mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); + mouse->getPhysicsBody()->setDynamic(false); + mouse->setPosition(location); + this->addChild(mouse); + PhysicsJoint* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + _scene->getPhysicsWorld()->addJoint(joint); + _mouses.insert(std::make_pair(touch->getID(), mouse)); + + return true; + } + + return false; +} + +void PhysicsDemo::onTouchMoved(Touch* touch, Event* event) +{ + auto it = _mouses.find(touch->getID()); + + if (it != _mouses.end()) + { + it->second->getPhysicsBody()->setVelocity((touch->getLocation() - it->second->getPosition()) * 60.0f); + it->second->setPosition(touch->getLocation()); + } } -void PhysicsDemo::onTouchesMoved(const std::vector& touches, Event* event) +void PhysicsDemo::onTouchEnded(Touch* touch, Event* event) { + auto it = _mouses.find(touch->getID()); -} - -void PhysicsDemo::onTouchesEnded(const std::vector& touches, Event* event) -{ + if (it != _mouses.end()) + { + this->removeChild(it->second); + _mouses.erase(it); + } } @@ -440,6 +473,9 @@ void PhysicsDemoPyramidStack::onEnter() { PhysicsDemo::onEnter(); + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(node); @@ -454,7 +490,9 @@ void PhysicsDemoPyramidStack::onEnter() { for(int j=0; j<=i; j++) { - addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); + auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); + + sp->getPhysicsBody()->setTag(1); } } } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 0c685ef98e..736c71574a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -5,6 +5,8 @@ #include "../testBasic.h" #include "../BaseTest.h" +#include + class PhysicsTestScene : public TestScene { @@ -36,19 +38,19 @@ public: void backCallback(Object* sender); void toggleDebugCallback(Object* sender); - void addGrossiniAtPosition(Point p, float scale = 1.0); + Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - void onTouchesBegan(const std::vector& touches, Event* event) override; - void onTouchesMoved(const std::vector& touches, Event* event) override; - void onTouchesEnded(const std::vector& touches, Event* event) override; + bool onTouchBegan(Touch* touch, Event* event) override; + void onTouchMoved(Touch* touch, Event* event) override; + void onTouchEnded(Touch* touch, Event* event) override; protected: Texture2D* _spriteTexture; // weak ref SpriteBatchNode* _ball; - DrawNode* _mouse; + std::map _mouses; }; class PhysicsDemoClickAdd : public PhysicsDemo From 66d1bbd89f7718cc42045670f612e451e72d6353 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 28 Oct 2013 16:17:19 +0800 Subject: [PATCH 009/197] issue #2771: edit physics effect with all bodies and fix some bugs --- cocos/2d/CCLayer.cpp | 24 ------- cocos/2d/CCLayer.h | 6 -- cocos/2d/CCNode.cpp | 14 ++++ cocos/2d/CCScene.cpp | 28 +++----- cocos/2d/CCScene.h | 2 +- cocos/2d/CCSpriteBatchNode.cpp | 11 --- cocos/physics/CCPhysicsBody.h | 6 +- cocos/physics/CCPhysicsJoint.cpp | 22 +++++- cocos/physics/CCPhysicsJoint.h | 8 ++- cocos/physics/CCPhysicsShape.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 70 +++++++++++++++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 6 +- 13 files changed, 124 insertions(+), 77 deletions(-) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 19346ea844..fe57da15fd 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -476,30 +476,6 @@ void Layer::onTouchesCancelled(const std::vector& pTouches, Event *pEven CC_UNUSED_PARAM(pEvent); } - -#ifdef CC_USE_PHYSICS -void Layer::addChild(Node* child) -{ - Node::addChild(child); -} - -void Layer::addChild(Node* child, int zOrder) -{ - Node::addChild(child, zOrder); -} - -void Layer::addChild(Node* child, int zOrder, int tag) -{ - Node::addChild(child, zOrder, tag); - - if (this->getParent() && - dynamic_cast(this->getParent()) != nullptr) - { - dynamic_cast(this->getParent())->addChildToPhysicsWorld(child); - } -} -#endif - // LayerRGBA LayerRGBA::LayerRGBA() : _displayedOpacity(255) diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 0dad16ff21..9280bdc6aa 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -179,12 +179,6 @@ public: * @lua NA */ virtual void onEnterTransitionDidFinish() override; - -#ifdef CC_USE_PHYSICS - virtual void addChild(Node* child) override; - virtual void addChild(Node* child, int zOrder) override; - virtual void addChild(Node* child, int zOrder, int tag) override; -#endif // CC_USE_PHYSICS protected: void addTouchListener(); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 99283b95a8..53ea8d3f18 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -43,6 +43,7 @@ THE SOFTWARE. #include "CCEventDispatcher.h" #include "CCEvent.h" #include "CCEventTouch.h" +#include "CCScene.h" #ifdef CC_USE_PHYSICS #include "CCPhysicsBody.h" @@ -626,6 +627,17 @@ void Node::addChild(Node *child, int zOrder, int tag) } this->insertChild(child, zOrder); + +#ifdef CC_USE_PHYSICS + for (Node* node = this->getParent(); node != nullptr; node = node->getParent()) + { + if (dynamic_cast(node) != nullptr) + { + (dynamic_cast(node))->addChildToPhysicsWorld(child); + break; + } + } +#endif child->_tag = tag; @@ -1392,10 +1404,12 @@ void Node::setPhysicsBody(PhysicsBody* body) { if (_physicsBody != nullptr) { + _physicsBody->_owner = nullptr; _physicsBody->release(); } _physicsBody = body; + _physicsBody->_owner = this; _physicsBody->retain(); _physicsBody->setPosition(getPosition()); _physicsBody->setRotation(getRotation()); diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index cc8654204b..5d0de936de 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -136,14 +136,8 @@ void Scene::addChildToPhysicsWorld(Node* child) std::function addToPhysicsWorldFunc = nullptr; addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void { - if (dynamic_cast(child) != nullptr) - { - Object* subChild = nullptr; - CCARRAY_FOREACH((dynamic_cast(child))->getChildren(), subChild) - { - addToPhysicsWorldFunc(subChild); - } - }else if (dynamic_cast(child) != nullptr) + + if (dynamic_cast(child) != nullptr) { Node* node = dynamic_cast(child); @@ -151,20 +145,16 @@ void Scene::addChildToPhysicsWorld(Node* child) { _physicsWorld->addBody(node->getPhysicsBody()); } + + Object* subChild = nullptr; + CCARRAY_FOREACH(node->getChildren(), subChild) + { + addToPhysicsWorldFunc(subChild); + } } }; - if(dynamic_cast(child) != nullptr) - { - Object* subChild = nullptr; - CCARRAY_FOREACH(child->getChildren(), subChild) - { - addToPhysicsWorldFunc(subChild); - } - }else - { - addToPhysicsWorldFunc(child); - } + addToPhysicsWorldFunc(child); } } diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 11e3e0fbb5..e0f69edd82 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -87,7 +87,7 @@ protected: PhysicsWorld* _physicsWorld; #endif // CC_USE_PHYSICS - friend class Layer; + friend class Node; friend class SpriteBatchNode; }; diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index b4be9bd045..af41111808 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -182,17 +182,6 @@ void SpriteBatchNode::addChild(Node *child, int zOrder, int tag) Node::addChild(child, zOrder, tag); appendChild(sprite); - - - if (this->getParent() && - dynamic_cast(this->getParent()) != nullptr) - { - if (this->getParent()->getParent() && - dynamic_cast(this->getParent()->getParent())) - { - dynamic_cast(this->getParent()->getParent())->addChildToPhysicsWorld(child); - } - } } // override reorderChild diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index c1a3d4b1a1..7d569075f8 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -44,7 +44,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(1.0f, 1.0f, 1.0f); +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.01f, 0.5f, 0.5f); /** * A body affect by physics. @@ -152,7 +152,7 @@ public: /* * @brief get the sprite the body set to. */ - inline Sprite* getOwner() const { return _owner; } + inline Node* getOwner() const { return _owner; } inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } inline int getCategoryBitmask() const { return _categoryBitmask; } @@ -261,7 +261,7 @@ protected: virtual ~PhysicsBody(); protected: - Sprite* _owner; + Node* _owner; std::vector _joints; Array* _shapes; PhysicsWorld* _world; diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index c7ca4ef2f9..0abca9e9a4 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -41,6 +41,7 @@ #include "box2d/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsHelper.h" #include "box2d/CCPhysicsHelper.h" +#include "CCNode.h" NS_CC_BEGIN @@ -149,6 +150,11 @@ PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const return body->_info; } +Node* PhysicsJoint::bodyOwner(PhysicsBody* body) const +{ + return body->_owner; +} + void PhysicsJoint::setCollisionEnable(bool enable) { @@ -182,6 +188,9 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { CC_BREAK_IF(!PhysicsJoint::init(a, b)); + bodyOwner(a)->setPosition(anchr); + bodyOwner(b)->setPosition(anchr); + // add a pivot joint to fixed two body together cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); @@ -219,7 +228,6 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); @@ -227,7 +235,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) _info->add(joint); - setCollisionEnable(false); + //setCollisionEnable(false); return true; } while (false); @@ -235,6 +243,16 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) return false; } +void PhysicsJointPin::setMaxForce(float force) +{ + _info->joints.front()->maxForce = PhysicsHelper::float2cpfloat(force); +} + +float PhysicsJointPin::getMaxForce() +{ + return PhysicsHelper::cpfloat2float(_info->joints.front()->maxForce); +} + PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) { PhysicsJointSliding* joint = new PhysicsJointSliding(); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 67e05cb858..d6c0d5df15 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -63,6 +63,7 @@ protected: * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. */ PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; + Node* bodyOwner(PhysicsBody* body) const; protected: PhysicsBody* _bodyA; @@ -82,7 +83,7 @@ protected: class PhysicsJointFixed : public PhysicsJoint { public: - PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); @@ -98,7 +99,7 @@ protected: class PhysicsJointSliding : public PhysicsJoint { public: - PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); + static PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); @@ -153,6 +154,9 @@ class PhysicsJointPin : public PhysicsJoint public: static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + void setMaxForce(float force); + float getMaxForce(); + protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 6cd5329f6d..02e6f604c0 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -57,7 +57,7 @@ typedef struct PhysicsMaterial {} }PhysicsMaterial; -const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 1.0f, 1.0f); +const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 0.5f, 0.5f); /** * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 915daa040e..c01f9ac640 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -524,7 +524,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if (!joint->isCollisionEnable()) { - PhysicsBody* body = joint->getBodyA() == bodyA ? bodyB : bodyA; + PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA(); if (body == bodyB) { diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 304981c448..51d5d3252c 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -10,6 +10,7 @@ namespace CL(PhysicsDemoPlink), CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), + CL(PhysicsDemoJoints), }; static int sceneIdx=-1; @@ -51,6 +52,7 @@ namespace } static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); + static const int DRAG_BODYS_TAG = 100; } @@ -378,7 +380,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { shape = dynamic_cast(obj); - if (shape->getTag() == 1) + if (shape->getTag() == DRAG_BODYS_TAG) { break; } @@ -392,7 +394,8 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); - PhysicsJoint* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + PhysicsJointPin* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + joint->setMaxForce(5000.0f); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); @@ -492,7 +495,7 @@ void PhysicsDemoPyramidStack::onEnter() { auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); - sp->getPhysicsBody()->setTag(1); + sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG); } } } @@ -741,15 +744,74 @@ std::string PhysicsDemoRayCast::title() } +PhysicsDemoJoints::PhysicsDemoJoints() +{ + +} + void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - _scene->getPhysicsWorld()->setGravity(Point::ZERO); + //_scene->getPhysicsWorld()->setGravity(Point::ZERO); + float width = (VisibleRect::getVisibleRect().size.width - 10) / 4; + float height = (VisibleRect::getVisibleRect().size.height - 50) / 4; + Node* node = Node::create(); + PhysicsBody* box = PhysicsBody::create(); + node->setPhysicsBody(box); + box->setDynamic(false); + node->setPosition(Point::ZERO); + + this->addChild(node); + + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + Point offset(VisibleRect::leftBottom().x + 5 + j * width + width/2, VisibleRect::leftBottom().y + 50 + i * height + height/2); + box->addShape(PhysicsShapeEdgeBox::create(Size(width, height), PHYSICSSHAPE_MATERIAL_DEFAULT, 1, offset)); + + switch (i*4 + j) + { + case 0: + { + auto sp1 = makeBall(offset.x - 30, offset.y, 10); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto sp2 = makeBall(offset.x + 30, offset.y, 10); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + + PhysicsJointPin* joint = PhysicsJointPin::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + _scene->getPhysicsWorld()->addJoint(joint); + + this->addChild(sp1); + this->addChild(sp2); + break; + } + case 1: + { + + auto sp1 = makeBall(offset.x - 30, offset.y, 10); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto sp2 = makeBox(offset.x + 30, offset.y, Size(30, 10)); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + + PhysicsJointFixed* joint = PhysicsJointFixed::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + _scene->getPhysicsWorld()->addJoint(joint); + + this->addChild(sp1); + this->addChild(sp2); + break; + } + default: + break; + } + } + } } std::string PhysicsDemoJoints::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 736c71574a..fe58196372 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -39,9 +39,9 @@ public: void toggleDebugCallback(Object* sender); Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); - Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); + Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); bool onTouchBegan(Touch* touch, Event* event) override; void onTouchMoved(Touch* touch, Event* event) override; From 2d3df6998257661005294c1303602f4c8e318448 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 29 Oct 2013 16:57:06 +0800 Subject: [PATCH 010/197] fix add display --- cocos/editor-support/cocostudio/CCArmature.cpp | 11 +++-------- cocos/editor-support/cocostudio/CCBone.cpp | 13 +++++++++++++ .../editor-support/cocostudio/CCDisplayManager.cpp | 1 + cocos/editor-support/cocostudio/CCSkin.cpp | 1 + 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 5c3b54e3df..ca935722c8 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -265,18 +265,12 @@ void Armature::addBone(Bone *bone, const char *parentName) } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } bone->setArmature(this); @@ -527,6 +521,7 @@ void Armature::draw() } } armature->draw(); + _atlas = armature->getTextureAtlas(); } break; default: diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index abd0cb85a5..574a66e1b0 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -167,6 +167,12 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); + CCBone *armatureParentBone = _armature->getParentBone(); + if (armatureParentBone && !_boneTransformDirty) + { + _boneTransformDirty = armatureParentBone->isTransformDirty(); + } + if (_boneTransformDirty) { if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) @@ -184,6 +190,13 @@ void Bone::update(float delta) { _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); } + else + { + if (armatureParentBone) + { + _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); + } + } } DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index b7d337e3a9..ae1ed19781 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -137,6 +137,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); + ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index afd6f5fc51..d1c66ddc3e 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -120,6 +120,7 @@ void Skin::setSkinData(const BaseData &var) setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); + updateArmatureTransform(); } const BaseData &Skin::getSkinData() const From cae9a3e54f0ceef46de85e5cafd516b3b8ef09b1 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 29 Oct 2013 17:31:35 +0800 Subject: [PATCH 011/197] issue #2771: add physics pump demo and fix bugs --- cocos/physics/CCPhysicsBody.cpp | 66 ++++- cocos/physics/CCPhysicsBody.h | 20 +- cocos/physics/CCPhysicsJoint.cpp | 43 ++++ cocos/physics/CCPhysicsJoint.h | 14 ++ cocos/physics/CCPhysicsShape.cpp | 15 ++ cocos/physics/CCPhysicsShape.h | 14 ++ cocos/physics/CCPhysicsWorld.cpp | 139 +++++++--- cocos/physics/CCPhysicsWorld.h | 12 +- cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp | 1 - cocos/physics/chipmunk/CCPhysicsBodyInfo.h | 7 +- cocos/physics/chipmunk/CCPhysicsContactInfo.h | 6 +- cocos/physics/chipmunk/CCPhysicsHelper.h | 6 +- cocos/physics/chipmunk/CCPhysicsJointInfo.h | 6 +- cocos/physics/chipmunk/CCPhysicsShapeInfo.h | 6 +- cocos/physics/chipmunk/CCPhysicsWorldInfo.h | 6 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 237 ++++++++++++++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 29 ++- 17 files changed, 529 insertions(+), 98 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index e3335c7c16..a4393c4435 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -57,7 +57,6 @@ namespace { static const float MASS_DEFAULT = 1.0; static const float MOMENT_DEFAULT = 200; - static float GROUP_INDEX = 0; } PhysicsBody::PhysicsBody() @@ -81,6 +80,7 @@ PhysicsBody::PhysicsBody() , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) , _contactTestBitmask(0) +, _group(0) { } @@ -273,7 +273,6 @@ bool PhysicsBody::init() _shapes->retain(); _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); - _info->group = ++GROUP_INDEX; CC_BREAK_IF(_info->body == nullptr); @@ -321,10 +320,10 @@ void PhysicsBody::setGravityEnable(bool enable) { if (enable) { - applyForce(_world->getGravity()); + applyForce(_world->getGravity() * _mass); }else { - applyForce(-_world->getGravity()); + applyForce(-_world->getGravity() * _mass); } } } @@ -351,9 +350,9 @@ float PhysicsBody::getRotation() const return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->body) / 3.14f * 180.0f); } -void PhysicsBody::addShape(PhysicsShape* shape) +PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) { - if (shape == nullptr) return; + if (shape == nullptr) return nullptr; // add shape to body if (_shapes->getIndexOfObject(shape) == UINT_MAX) @@ -372,7 +371,14 @@ void PhysicsBody::addShape(PhysicsShape* shape) } _shapes->addObject(shape); + + if (_group != CP_NO_GROUP && shape->getGroup() == CP_NO_GROUP) + { + shape->setGroup(_group); + } } + + return shape; } void PhysicsBody::applyForce(Point force) @@ -676,6 +682,54 @@ void PhysicsBody::update(float delta) } } +void PhysicsBody::setCategoryBitmask(int bitmask) +{ + _categoryBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setCategoryBitmask(bitmask); + } +} + +void PhysicsBody::setContactTestBitmask(int bitmask) +{ + _contactTestBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setContactTestBitmask(bitmask); + } +} + +void PhysicsBody::setCollisionBitmask(int bitmask) +{ + _collisionBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setCollisionBitmask(bitmask); + } +} + +void PhysicsBody::setGroup(int group) +{ + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setGroup(group); + } +} + +Point PhysicsBody::world2Local(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->body, PhysicsHelper::point2cpv(point))); +} + +Point PhysicsBody::local2World(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->body, PhysicsHelper::point2cpv(point))); +} + //Clonable* PhysicsBody::clone() const //{ // PhysicsBody* body = new PhysicsBody(); diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 7d569075f8..a82b7dc1d4 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -87,7 +87,7 @@ public: */ static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - virtual void addShape(PhysicsShape* shape); + virtual PhysicsShape* addShape(PhysicsShape* shape); /** * @brief Applies a immediate force to body. @@ -154,13 +154,16 @@ public: */ inline Node* getOwner() const { return _owner; } - inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } + void setCategoryBitmask(int bitmask); + void setContactTestBitmask(int bitmask); + void setCollisionBitmask(int bitmask); inline int getCategoryBitmask() const { return _categoryBitmask; } - inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } inline int getContactTestBitmask() const { return _contactTestBitmask; } - inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } inline int getCollisionBitmask() const { return _collisionBitmask; } + void setGroup(int group); + inline int getGroup() { return _group; } + /* * @brief get the body position. */ @@ -246,6 +249,8 @@ public: inline int getTag() { return _tag; } inline void setTag(int tag) { _tag = tag; } + Point world2Local(const Point& point); + Point local2World(const Point& point); protected: @@ -280,9 +285,10 @@ protected: float _angularDamping; int _tag; - int _categoryBitmask; - int _collisionBitmask; - int _contactTestBitmask; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsShape; diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 0abca9e9a4..1268ac2460 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -144,6 +144,16 @@ PhysicsJointLimit::~PhysicsJointLimit() } +PhysicsJointDistance::PhysicsJointDistance() +{ + +} + +PhysicsJointDistance::~PhysicsJointDistance() +{ + +} + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const { @@ -343,6 +353,39 @@ void PhysicsJointLimit::setMax(float max) cpSlideJointSetMax(_info->joints.front(), PhysicsHelper::float2cpfloat(max)); } +PhysicsJointDistance* PhysicsJointDistance::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +{ + PhysicsJointDistance* joint = new PhysicsJointDistance(); + + if (joint && joint->init(a, b, anchr1, anchr2)) + { + return joint; + } + + CC_SAFE_DELETE(joint); + return nullptr; +} + +bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +{ + do + { + CC_BREAK_IF(!PhysicsJoint::init(a, b)); + + cpConstraint* joint = cpPinJointNew(bodyInfo(a)->body, + bodyInfo(b)->body, + PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); + + CC_BREAK_IF(joint == nullptr); + + _info->add(joint); + + return true; + } while (false); + + return false; +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index d6c0d5df15..298992c5f3 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -165,6 +165,20 @@ protected: virtual ~PhysicsJointPin(); }; +class PhysicsJointDistance : public PhysicsJoint +{ + +public: + static PhysicsJointDistance* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + +protected: + bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + +protected: + PhysicsJointDistance(); + virtual ~PhysicsJointDistance(); +}; + NS_CC_END #endif // __CCPHYSICS_JOINT_H__ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 77634e9113..6b166da351 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -50,6 +50,10 @@ PhysicsShape::PhysicsShape() , _mass(0) , _moment(0) , _tag(0) +, _categoryBitmask(UINT_MAX) +, _collisionBitmask(UINT_MAX) +, _contactTestBitmask(0) +, _group(0) { } @@ -777,6 +781,17 @@ int PhysicsShapeEdgeChain::getPointsCount() return _info->shapes.size() + 1; } +void PhysicsShape::setGroup(int group) +{ + if (group < 0) + { + for (auto shape : _info->shapes) + { + cpShapeSetGroup(shape, (cpGroup)group); + } + } +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 02e6f604c0..8bc9224bf1 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -102,6 +102,16 @@ public: static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); static Point getPolyonCenter(Point* points, int count); + inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } + inline int getCategoryBitmask() const { return _categoryBitmask; } + inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } + inline int getContactTestBitmask() const { return _contactTestBitmask; } + inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } + inline int getCollisionBitmask() const { return _collisionBitmask; } + + void setGroup(int group); + inline int getGroup() { return _group; } + protected: bool init(Type type); @@ -125,6 +135,10 @@ protected: float _moment; PhysicsMaterial _material; int _tag; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsBody; diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index c01f9ac640..459261f896 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -181,9 +181,9 @@ bool PhysicsWorld::init() { _info = new PhysicsWorldInfo(); CC_BREAK_IF(_info == nullptr); - _bodys = Array::create(); - CC_BREAK_IF(_bodys == nullptr); - _bodys->retain(); + _bodies = Array::create(); + CC_BREAK_IF(_bodies == nullptr); + _bodies->retain(); cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); @@ -253,7 +253,7 @@ void PhysicsWorld::removeAllJoints() _joints.clear(); } -void PhysicsWorld::addShape(PhysicsShape* shape) +PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) { for (auto cps : shape->_info->shapes) { @@ -270,9 +270,11 @@ void PhysicsWorld::addShape(PhysicsShape* shape) cpSpaceAddShape(_info->space, cps); } } + + return shape; } -void PhysicsWorld::addBody(PhysicsBody* body) +PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -304,7 +306,9 @@ void PhysicsWorld::addBody(PhysicsBody* body) } } - _bodys->addObject(body); + _bodies->addObject(body); + + return body; } void PhysicsWorld::removeBody(PhysicsBody* body) @@ -341,12 +345,12 @@ void PhysicsWorld::removeBody(PhysicsBody* body) } body->_world = nullptr; - _bodys->removeObject(body); + _bodies->removeObject(body); } void PhysicsWorld::removeBodyByTag(int tag) { - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == tag) @@ -357,9 +361,9 @@ void PhysicsWorld::removeBodyByTag(int tag) } } -void PhysicsWorld::removeAllBodys() +void PhysicsWorld::removeAllBodies() { - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); @@ -390,8 +394,8 @@ void PhysicsWorld::removeAllBodys() body->_world = nullptr; } - _bodys->removeAllObjects(); - CC_SAFE_RELEASE(_bodys); + _bodies->removeAllObjects(); + CC_SAFE_RELEASE(_bodies); } void PhysicsWorld::removeShape(PhysicsShape* shape) @@ -407,7 +411,7 @@ void PhysicsWorld::removeShape(PhysicsShape* shape) void PhysicsWorld::update(float delta) { - for (auto body : *_bodys) + for (auto body : *_bodies) { body->update(delta); } @@ -428,11 +432,11 @@ void PhysicsWorld::update(float delta) void PhysicsWorld::debugDraw() { - if (_debugDraw && _bodys != nullptr) + if (_debugDraw && _bodies != nullptr) { _drawNode= DrawNode::create(); - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); @@ -442,6 +446,11 @@ void PhysicsWorld::debugDraw() } } + for (auto joint : _joints) + { + drawWithJoint(_drawNode, joint); + } + if (_scene) { _scene->addChild(_drawNode); @@ -454,6 +463,58 @@ void PhysicsWorld::setScene(Scene *scene) _scene = scene; } +void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) +{ + for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) + { + cpConstraint *constraint = *it; + + + cpBody *body_a = constraint->a; + cpBody *body_b = constraint->b; + + const cpConstraintClass *klass = constraint->klass_private; + if(klass == cpPinJointGetClass()){ + cpPinJoint *joint = (cpPinJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpSlideJointGetClass()){ + cpSlideJoint *joint = (cpSlideJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpPivotJointGetClass()){ + cpPivotJoint *joint = (cpPivotJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpGrooveJointGetClass()){ + cpGrooveJoint *joint = (cpGrooveJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->grv_a, body_a->rot)); + cpVect b = cpvadd(body_a->p, cpvrotate(joint->grv_b, body_a->rot)); + cpVect c = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(c), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpDampedSpringGetClass()){ + + } + } +} + void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) { for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) @@ -510,8 +571,10 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; - PhysicsBody* bodyA = contact.getShapeA()->getBody(); - PhysicsBody* bodyB = contact.getShapeB()->getBody(); + PhysicsShape* shapeA = contact.getShapeA(); + PhysicsShape* shapeB = contact.getShapeB(); + PhysicsBody* bodyA = shapeA->getBody(); + PhysicsBody* bodyB = shapeB->getBody(); std::vector jointsA = bodyA->getJoints(); // check the joint is collision enable or not @@ -534,17 +597,24 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) } } + // bitmask check - if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0 - || (bodyB->getContactTestBitmask() & bodyA->getCategoryBitmask()) == 0) + if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 + || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) { contact.setNotify(false); } - if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0 - || (bodyB->getCategoryBitmask() & bodyA->getCollisionBitmask()) == 0) + if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) { - ret = false; + ret = shapeA->getGroup() > 0; + }else + { + if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0 + || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0) + { + ret = false; + } } if (contact.getNotify() && _listener && _listener->onContactBegin) @@ -614,9 +684,9 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) void PhysicsWorld::setGravity(Point gravity) { - if (_bodys != nullptr) + if (_bodies != nullptr) { - for (auto child : *_bodys) + for (auto child : *_bodies) { PhysicsBody* body = dynamic_cast(child); @@ -694,9 +764,22 @@ PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) return shape == nullptr ? nullptr : PhysicsShapeInfo::map.find(shape)->second->shape; } -Array* PhysicsWorld::getAllBody() const +Array* PhysicsWorld::getAllBodies() const { - return _bodys; + return _bodies; +} + +PhysicsBody* PhysicsWorld::getBodyByTag(int tag) +{ + for (auto body : *_bodies) + { + if (((PhysicsBody*)body)->getTag() == tag) + { + return (PhysicsBody*)body; + } + } + + return nullptr; } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) @@ -720,7 +803,7 @@ PhysicsWorld::PhysicsWorld() , _speed(1.0f) , _info(nullptr) , _listener(nullptr) -, _bodys(nullptr) +, _bodies(nullptr) , _scene(nullptr) , _debugDraw(false) , _drawNode(nullptr) @@ -730,7 +813,7 @@ PhysicsWorld::PhysicsWorld() PhysicsWorld::~PhysicsWorld() { - removeAllBodys(); + removeAllBodies(); removeAllJoints(); CC_SAFE_DELETE(_info); } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 9fa8b28240..aff9119485 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -97,7 +97,8 @@ public: void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); Array* getShapesAtPoint(Point point); PhysicsShape* getShapeAtPoint(Point point); - Array* getAllBody() const; + Array* getAllBodies() const; + PhysicsBody* getBodyByTag(int tag); /** Register a listener to receive contact callbacks*/ inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } @@ -116,7 +117,7 @@ public: virtual void removeBody(PhysicsBody* body); virtual void removeBodyByTag(int tag); - virtual void removeAllBodys(); + virtual void removeAllBodies(); protected: static PhysicsWorld* create(); @@ -124,13 +125,14 @@ protected: void setScene(Scene* scene); - virtual void addBody(PhysicsBody* body); - virtual void addShape(PhysicsShape* shape); + virtual PhysicsBody* addBody(PhysicsBody* body); + virtual PhysicsShape* addShape(PhysicsShape* shape); virtual void removeShape(PhysicsShape* shape); virtual void update(float delta); virtual void debugDraw(); virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); + virtual void drawWithJoint(DrawNode* node, PhysicsJoint* joint); virtual int collisionBeginCallback(PhysicsContact& contact); @@ -145,7 +147,7 @@ protected: PhysicsContactListener* _listener; - Array* _bodys; + Array* _bodies; std::list _joints; Scene* _scene; diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp index 852dad1eeb..5fd8ceb171 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp @@ -28,7 +28,6 @@ NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() : body(nullptr) -, group(CP_NO_GROUP) { } diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo.h index ec84526b59..54e4313b38 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" @@ -37,7 +37,6 @@ class PhysicsBodyInfo : public Clonable { public: cpBody* body; - cpGroup group; private: PhysicsBodyInfo(); diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.h b/cocos/physics/chipmunk/CCPhysicsContactInfo.h index 6c302947b7..fb455cdfc5 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper.h index bf6f6d14db..8ad6fa29bd 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_HELPER_H__ #define __CCPHYSICS_HELPER_H__ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.h b/cocos/physics/chipmunk/CCPhysicsJointInfo.h index 04a2c716bf..5033e4aaba 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h index 83be655b02..9229ba6d7f 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_SHAPE_INFO_H__ #define __CCPHYSICS_SHAPE_INFO_H__ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #include #include #include "chipmunk.h" diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo.h index 71d56f0a5b..8c60cde415 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 51d5d3252c..ae7f7d07a4 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -11,6 +11,8 @@ namespace CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), CL(PhysicsDemoJoints), + CL(PhysicsDemoActions), + CL(PhysicsDemoPump), }; static int sceneIdx=-1; @@ -52,7 +54,7 @@ namespace } static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); - static const int DRAG_BODYS_TAG = 100; + static const int DRAG_BODYS_TAG = 0x80; } @@ -314,7 +316,7 @@ namespace } } -Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial material) +Sprite* PhysicsDemo::makeBall(Point point, float radius, PhysicsMaterial material) { Sprite* ball = nullptr; if (_ball != nullptr) @@ -329,12 +331,12 @@ Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial ma auto body = PhysicsBody::createCircle(radius, material); ball->setPhysicsBody(body); - ball->setPosition(Point(x, y)); + ball->setPosition(Point(point.x, point.y)); return ball; } -Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial material) +Sprite* PhysicsDemo::makeBox(Point point, Size size, PhysicsMaterial material) { auto box = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowSquare.png") : Sprite::create("Images/CyanSquare.png"); @@ -343,12 +345,12 @@ Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial materi auto body = PhysicsBody::createBox(size); box->setPhysicsBody(body); - box->setPosition(Point(x, y)); + box->setPosition(Point(point.x, point.y)); return box; } -Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial material) +Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial material) { auto triangle = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowTriangle.png") : Sprite::create("Images/CyanTriangle.png"); @@ -365,7 +367,7 @@ Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial m auto body = PhysicsBody::createPolygon(vers, 3); triangle->setPhysicsBody(body); - triangle->setPosition(Point(x, y)); + triangle->setPosition(Point(point.x, point.y)); return triangle; } @@ -380,7 +382,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { shape = dynamic_cast(obj); - if (shape->getTag() == DRAG_BODYS_TAG) + if ((shape->getTag() & DRAG_BODYS_TAG) != 0) { break; } @@ -395,7 +397,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) mouse->setPosition(location); this->addChild(mouse); PhysicsJointPin* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); - joint->setMaxForce(5000.0f); + joint->setMaxForce(5000.0f * shape->getBody()->getMass()); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); @@ -445,9 +447,9 @@ void PhysicsDemoLogoSmash::onEnter() float x_jitter = 0.05*frand(); float y_jitter = 0.05*frand(); - Node* ball = makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, - 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2, - 0.95f, PhysicsMaterial(1.0f, 0.0f, 0.0f)); + Node* ball = makeBall(Point(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, + 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2), + 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); @@ -459,7 +461,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(400, 0, 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); + auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -727,13 +729,13 @@ void PhysicsDemoRayCast::onTouchesEnded(const std::vector& touches, Even if (r < 1.0f/3.0f) { - addChild(makeBall(location.x, location.y, 5 + CCRANDOM_0_1()*10)); + addChild(makeBall(location, 5 + CCRANDOM_0_1()*10)); }else if(r < 2.0f/3.0f) { - addChild(makeBox(location.x, location.y, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); + addChild(makeBox(location, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); }else { - addChild(makeTriangle(location.x, location.y, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); + addChild(makeTriangle(location, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); } } } @@ -743,12 +745,6 @@ std::string PhysicsDemoRayCast::title() return "Ray Cast"; } - -PhysicsDemoJoints::PhysicsDemoJoints() -{ - -} - void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); @@ -780,9 +776,9 @@ void PhysicsDemoJoints::onEnter() { case 0: { - auto sp1 = makeBall(offset.x - 30, offset.y, 10); + auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - auto sp2 = makeBall(offset.x + 30, offset.y, 10); + auto sp2 = makeBall(offset + Point(30, 0), 10); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointPin* joint = PhysicsJointPin::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); @@ -795,9 +791,9 @@ void PhysicsDemoJoints::onEnter() case 1: { - auto sp1 = makeBall(offset.x - 30, offset.y, 10); + auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - auto sp2 = makeBox(offset.x + 30, offset.y, Size(30, 10)); + auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointFixed* joint = PhysicsJointFixed::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); @@ -817,4 +813,193 @@ void PhysicsDemoJoints::onEnter() std::string PhysicsDemoJoints::title() { return "Joints"; +} + +void PhysicsDemoActions::onEnter() +{ + PhysicsDemo::onEnter(); + + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + + auto node = Node::create(); + node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + node->setPosition(VisibleRect::center()); + this->addChild(node); + + Sprite* sp1 = addGrossiniAtPosition(VisibleRect::center()); + Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Point(50, 0)); + Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Point(20, 0)); + Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Point(50, -50)); + sp4->getPhysicsBody()->setGravityEnable(false); + + + auto actionTo = JumpTo::create(2, Point(100,100), 50, 4); + auto actionBy = JumpBy::create(2, Point(300,0), 50, 4); + auto actionUp = JumpBy::create(2, Point(0,50), 80, 4); + auto actionByBack = actionBy->reverse(); + + sp1->runAction(RepeatForever::create(actionUp)); + sp2->runAction(RepeatForever::create(Sequence::create(actionBy, actionByBack, NULL))); + sp3->runAction(actionTo); + sp4->runAction(RepeatForever::create(Sequence::create(actionBy->clone(), actionByBack->clone(), NULL))); +} + +std::string PhysicsDemoActions::title() +{ + return "Actions"; +} + +void PhysicsDemoPump::onEnter() +{ + PhysicsDemo::onEnter(); + + _distance = 0.0f; + _rotationV = 0.0f; + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + scheduleUpdate(); + + auto node = Node::create(); + auto body = PhysicsBody::create(); + body->setDynamic(false); + + PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, 0), VisibleRect::leftTop() + Point(50, -130), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(190, 0), VisibleRect::leftTop() + Point(100, -50), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -50), VisibleRect::leftTop() + Point(100, -90), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, -130), VisibleRect::leftTop() + Point(100, -145), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -145), VisibleRect::leftBottom() + Point(100, 80), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::leftBottom() + Point(150, 80), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::rightTop() + Point(-100, -150), staticMaterial, 2.0f)); + + body->setCategoryBitmask(0x01); + + // balls + for (int i = 0; i < 6; ++i) + { + auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.5f, 0.0f, 0.1f)); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + addChild(ball); + } + + node->setPhysicsBody(body); + this->addChild(node); + + Point vec[4] = + { + VisibleRect::leftTop() + Point(102, -146), + VisibleRect::leftTop() + Point(148, -159), + VisibleRect::leftBottom() + Point(148, 20), + VisibleRect::leftBottom() + Point(102, 20) + }; + + auto _world = _scene->getPhysicsWorld(); + + // small gear + auto sgear = Node::create(); + auto sgearB = PhysicsBody::createCircle(50); + sgear->setPhysicsBody(sgearB); + sgear->setPosition(VisibleRect::leftBottom() + Point(125, 0)); + this->addChild(sgear); + sgearB->setCategoryBitmask(0x04); + sgearB->setCollisionBitmask(0x04); + sgearB->setTag(1); + _world->addJoint(PhysicsJointPin::create(body, sgearB, sgearB->getPosition())); + + + // big gear + auto bgear = Node::create(); + auto bgearB = PhysicsBody::createCircle(100); + bgear->setPhysicsBody(bgearB); + bgear->setPosition(VisibleRect::leftBottom() + Point(275, 0)); + this->addChild(bgear); + bgearB->setCategoryBitmask(0x04); + _world->addJoint(PhysicsJointPin::create(body, bgearB, bgearB->getPosition())); + + + // pump + auto pump = Node::create(); + pump->setPosition(PhysicsShape::getPolyonCenter(vec, 4)); + auto pumpB = PhysicsBody::createPolygon(PhysicsShape::recenterPoints(vec, 4), 4); + pump->setPhysicsBody(pumpB); + this->addChild(pump); + pumpB->setCategoryBitmask(0x02); + pumpB->setGravityEnable(false); + _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -50))); + + // plugger + Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; + Point segCenter = (seg[1] + seg[0])/2; + seg[1] -= segCenter; + seg[0] -= segCenter; + auto plugger = Node::create(); + auto pluggerB = PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20); + pluggerB->setDynamic(true); + pluggerB->setMass(30); + pluggerB->setMoment(100000); + plugger->setPhysicsBody(pluggerB); + plugger->setPosition(segCenter); + this->addChild(plugger); + pluggerB->setCategoryBitmask(0x02); + sgearB->setCollisionBitmask(0x04 | 0x01); + _world->addJoint(PhysicsJointPin::create(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); + _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(50, 0))); +} + +void PhysicsDemoPump::update(float delta) +{ + for (auto obj : *_scene->getPhysicsWorld()->getAllBodies()) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) + { + body->getOwner()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); + body->setVelocity(Point(0, 0)); + } + } + + PhysicsBody* gear = _scene->getPhysicsWorld()->getBodyByTag(1); + + if (gear != nullptr) + { + if (_distance != 0.0f) + { + _rotationV += _distance/2500.0f; + + if (_rotationV > 30) _rotationV = 30.0f; + if (_rotationV < -30) _rotationV = -30.0f; + } + + gear->setAngularVelocity(_rotationV); + _rotationV *= 0.995; + } +} + +bool PhysicsDemoPump::onTouchBegan(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchBegan(touch, event); + + _distance = touch->getLocation().x - VisibleRect::center().x; + + return true; +} + +void PhysicsDemoPump::onTouchMoved(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchMoved(touch, event); + + _distance = touch->getLocation().x - VisibleRect::center().x; +} + +void PhysicsDemoPump::onTouchEnded(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchEnded(touch, event); + + _distance = 0; +} + +std::string PhysicsDemoPump::title() +{ + return "Pump"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index fe58196372..79932c60a7 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -39,9 +39,9 @@ public: void toggleDebugCallback(Object* sender); Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); - Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBall(Point point, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBox(Point point, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeTriangle(Point point, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); bool onTouchBegan(Touch* touch, Event* event) override; void onTouchMoved(Touch* touch, Event* event) override; @@ -107,14 +107,31 @@ private: class PhysicsDemoJoints : public PhysicsDemo { public: - PhysicsDemoJoints(); - + void onEnter() override; + std::string title() override; +}; + +class PhysicsDemoActions : public PhysicsDemo +{ public: void onEnter() override; std::string title() override; +}; + +class PhysicsDemoPump : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + void update(float delta) override; + + bool onTouchBegan(Touch* touch, Event* event) override; + void onTouchMoved(Touch* touch, Event* event) override; + void onTouchEnded(Touch* touch, Event* event) override; private: - PhysicsShape* _touchesShape; + float _distance; + float _rotationV; }; #endif From 8fa8b9f844ac723f1d9a38699f1d62206c1f8ced Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 30 Oct 2013 09:41:40 +0800 Subject: [PATCH 012/197] update develop --- .../editor-support/cocostudio/CCArmature.cpp | 52 +++- cocos/editor-support/cocostudio/CCArmature.h | 6 +- .../cocostudio/CCArmatureAnimation.cpp | 57 +++- .../cocostudio/CCArmatureAnimation.h | 37 ++- .../cocostudio/CCArmatureDataManager.cpp | 4 +- .../cocostudio/CCArmatureDefine.cpp | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 83 ++++++ cocos/editor-support/cocostudio/CCBatchNode.h | 8 +- cocos/editor-support/cocostudio/CCBone.cpp | 95 ++++-- cocos/editor-support/cocostudio/CCBone.h | 21 +- .../cocostudio/CCColliderDetector.cpp | 10 +- .../cocostudio/CCDataReaderHelper.cpp | 107 +++++-- .../cocostudio/CCDataReaderHelper.h | 24 +- .../cocostudio/CCDisplayFactory.cpp | 51 ++-- .../cocostudio/CCDisplayFactory.h | 7 +- .../cocostudio/CCDisplayManager.cpp | 20 +- .../cocostudio/CCDisplayManager.h | 3 + .../cocostudio/CCProcessBase.cpp | 12 +- .../editor-support/cocostudio/CCProcessBase.h | 3 +- cocos/editor-support/cocostudio/CCSkin.cpp | 61 ++-- cocos/editor-support/cocostudio/CCSkin.h | 3 +- .../cocostudio/CCSpriteFrameCacheHelper.cpp | 14 - .../cocostudio/CCSpriteFrameCacheHelper.h | 4 - .../cocostudio/CCTransformHelp.cpp | 21 +- cocos/editor-support/cocostudio/CCTween.cpp | 63 ++-- cocos/editor-support/cocostudio/CCTween.h | 13 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 276 +++++++++++++++++- .../CocoStudioArmatureTest/ArmatureScene.h | 54 +++- 28 files changed, 907 insertions(+), 204 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index ca935722c8..ac04de1af5 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -86,6 +86,7 @@ Armature::Armature() , _boneDic(NULL) , _topBoneList(NULL) , _animation(NULL) + , _textureAtlasDic(NULL) { } @@ -103,6 +104,7 @@ Armature::~Armature(void) CC_SAFE_DELETE(_topBoneList); } CC_SAFE_DELETE(_animation); + CC_SAFE_RELEASE_NULL(_textureAtlasDic); } @@ -130,6 +132,8 @@ bool Armature::init(const char *name) _topBoneList = new Array(); _topBoneList->init(); + CC_SAFE_DELETE(_textureAtlasDic); + _textureAtlasDic = new Dictionary(); _blendFunc.src = CC_BLEND_SRC; _blendFunc.dst = CC_BLEND_DST; @@ -458,7 +462,7 @@ void Armature::update(float dt) void Armature::draw() { - if (_parentBone == NULL) + if (_parentBone == NULL && _batchNode == NULL) { CC_NODE_DRAW_SETUP(); GL::blendFunc(_blendFunc.src, _blendFunc.dst); @@ -469,13 +473,12 @@ void Armature::draw() { if (Bone *bone = dynamic_cast(object)) { - DisplayManager *displayManager = bone->getDisplayManager(); - Node *node = displayManager->getDisplayRenderNode(); + Node *node = bone->getDisplayRenderNode(); if (NULL == node) continue; - switch (displayManager->getCurrentDecorativeDisplay()->getDisplayData()->displayType) + switch (bone->getDisplayRenderNodeType()) { case CS_DISPLAY_SPRITE: { @@ -667,7 +670,7 @@ Rect Armature::getBoundingBox() const } } - return boundingBox; + return RectApplyAffineTransform(boundingBox, getNodeToParentTransform()); } Bone *Armature::getBoneAtPoint(float x, float y) @@ -686,6 +689,45 @@ Bone *Armature::getBoneAtPoint(float x, float y) return NULL; } +TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) +{ + int key = texture->getName(); + + if (_parentBone && _parentBone->getArmature()) + { + return _parentBone->getArmature()->getTexureAtlasWithTexture(texture); + } + else if (_batchNode) + { + _batchNode->getTexureAtlasWithTexture(texture); + } + + TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); + if (atlas == NULL) + { + atlas = TextureAtlas::createWithTexture(texture, 4); + _textureAtlasDic->setObject(atlas, key); + } + return atlas; +} + +void Armature::setParentBone(Bone *parentBone) +{ + _parentBone = parentBone; + + DictElement *element = NULL; + CCDICT_FOREACH(_boneDic, element) + { + Bone *bone = static_cast(element->getObject()); + bone->setArmature(this); + } +} + +Bone *Armature::getParentBone() +{ + return _parentBone; +} + #if ENABLE_PHYSICS_BOX2D_DETECT b2Body *Armature::getBody() { diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 3e8c521011..15abe96079 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -173,6 +173,8 @@ public: virtual bool getArmatureTransformDirty(); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT @@ -197,7 +199,7 @@ protected: CC_SYNTHESIZE(cocos2d::TextureAtlas *, _atlas, TextureAtlas); - CC_SYNTHESIZE(Bone *, _parentBone, ParentBone); + CC_PROPERTY(Bone *, _parentBone, ParentBone); CC_SYNTHESIZE(float, _version, Version); @@ -214,6 +216,8 @@ protected: ArmatureAnimation *_animation; + cocos2d::Dictionary *_textureAtlasDic; + #if ENABLE_PHYSICS_BOX2D_DETECT CC_PROPERTY(b2Body *, _body, Body); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index a026fc33c9..ed6e383751 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -54,6 +54,8 @@ ArmatureAnimation::ArmatureAnimation() , _armature(NULL) , _movementID("") , _toIndex(0) + , _tweenList(NULL) + , _ignoreFrameEvent(false) , _movementEventCallFunc(NULL) , _frameEventCallFunc(NULL) @@ -268,6 +270,8 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura } } + + _armature->update(0); } @@ -280,7 +284,40 @@ void ArmatureAnimation::playByIndex(int animationIndex, int durationTo, int dura play(animationName.c_str(), durationTo, durationTween, loop, tweenEasing); } +void ArmatureAnimation::gotoAndPlay(int frameIndex) +{ + if (!_movementData || frameIndex < 0 || frameIndex >= _movementData->duration) + { + CCLOG("Please ensure you have played a movement, and the frameIndex is in the range."); + return; + } + bool ignoreFrameEvent = _ignoreFrameEvent; + _ignoreFrameEvent = true; + + _isPlaying = true; + _isComplete = _isPause = false; + + ProcessBase::gotoFrame(frameIndex); + _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; + _currentFrame = _nextFrameIndex * _currentPercent; + + Object *object = NULL; + CCARRAY_FOREACH(_tweenList, object) + { + static_cast(object)->gotoAndPlay(frameIndex); + } + + _armature->update(0); + + _ignoreFrameEvent = ignoreFrameEvent; +} + +void ArmatureAnimation::gotoAndPause(int frameIndex) +{ + gotoAndPlay(frameIndex); + pause(); +} int ArmatureAnimation::getMovementCount() { @@ -295,6 +332,18 @@ void ArmatureAnimation::update(float dt) { static_cast(object)->update(dt); } + + while (_frameEventQueue.size() > 0) + { + FrameEvent *frameEvent = _frameEventQueue.front(); + _frameEventQueue.pop(); + + _ignoreFrameEvent = true; + (_frameEventTarget->*_frameEventCallFunc)(frameEvent->bone, frameEvent->frameEventName, frameEvent->originFrameIndex, frameEvent->currentFrameIndex); + _ignoreFrameEvent = false; + + CC_SAFE_DELETE(frameEvent); + } } void ArmatureAnimation::updateHandler() @@ -402,7 +451,13 @@ void ArmatureAnimation::frameEvent(Bone *bone, const char *frameEventName, int o { if (_frameEventTarget && _frameEventCallFunc) { - (_frameEventTarget->*_frameEventCallFunc)(bone, frameEventName, originFrameIndex, currentFrameIndex); + FrameEvent *frameEvent = new FrameEvent(); + frameEvent->bone = bone; + frameEvent->frameEventName = frameEventName; + frameEvent->originFrameIndex = originFrameIndex; + frameEvent->currentFrameIndex = currentFrameIndex; + + _frameEventQueue.push(frameEvent); } } } diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 9551f97ff9..5fe23543bf 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -27,6 +27,7 @@ THE SOFTWARE. #define __CCANIMATION_H__ #include "cocostudio/CCProcessBase.h" +#include namespace cocostudio { @@ -48,6 +49,13 @@ typedef void (cocos2d::Object::*SEL_FrameEventCallFunc)(Bone *, const char *, in #define movementEvent_selector(_SELECTOR) (cocostudio::SEL_MovementEventCallFunc)(&_SELECTOR) #define frameEvent_selector(_SELECTOR) (cocostudio::SEL_FrameEventCallFunc)(&_SELECTOR) +struct FrameEvent +{ + Bone *bone; + const char *frameEventName; + int originFrameIndex; + int currentFrameIndex; +}; class ArmatureAnimation : public ProcessBase { @@ -76,10 +84,11 @@ public: /** * Scale animation play speed. + * This method is deprecated, please use setSpeedScale. * @param animationScale Scale value */ - virtual void setAnimationScale(float animationScale); - virtual float getAnimationScale() const; + CC_DEPRECATED_ATTRIBUTE virtual void setAnimationScale(float animationScale); + CC_DEPRECATED_ATTRIBUTE virtual float getAnimationScale() const; /** * Scale animation play speed. @@ -123,10 +132,27 @@ public: /** * Play animation by index, the other param is the same to play. - * @param _animationIndex the animation index you want to play + * @param animationIndex the animation index you want to play */ void playByIndex(int animationIndex, int durationTo = -1, int durationTween = -1, int loop = -1, int tweenEasing = TWEEN_EASING_MAX); + /** + * Go to specified frame and play current movement. + * You need first switch to the movement you want to play, then call this function. + * + * example : playByIndex(0); + * gotoAndPlay(0); + * playByIndex(1); + * gotoAndPlay(0); + * gotoAndPlay(15); + */ + virtual void gotoAndPlay(int frameIndex); + + /** + * Go to specified frame and pause current movement. + */ + virtual void gotoAndPause(int frameIndex); + /** * Pause the Process */ @@ -183,6 +209,8 @@ protected: */ void frameEvent(Bone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + inline bool isIgnoreFrameEvent() { return _ignoreFrameEvent; } + friend class Tween; protected: //! AnimationData save all MovementDatas this animation used. @@ -201,6 +229,9 @@ protected: cocos2d::Array *_tweenList; + bool _ignoreFrameEvent; + + std::queue _frameEventQueue; protected: /** * MovementEvent CallFunc. diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 113ff33202..13ca184768 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -186,7 +186,7 @@ void ArmatureDataManager::addArmatureFileInfo(const char *configFilePath) void ArmatureDataManager::addArmatureFileInfoAsync(const char *configFilePath, Object *target, SEL_SCHEDULE selector) { _autoLoadSpriteFile = true; - DataReaderHelper::getInstance()->addDataFromFileAsync(configFilePath, target, selector); + DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char *plistPath, const char *configFilePath) @@ -199,7 +199,7 @@ void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char void ArmatureDataManager::addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, Object *target, SEL_SCHEDULE selector) { _autoLoadSpriteFile = false; - DataReaderHelper::getInstance()->addDataFromFileAsync(configFilePath, target, selector); + DataReaderHelper::getInstance()->addDataFromFileAsync(imagePath, plistPath, configFilePath, target, selector); addSpriteFrameFromFile(plistPath, imagePath); } diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.cpp b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp index 3672943778..4f48e0024e 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp @@ -28,7 +28,7 @@ namespace cocostudio { const char *armatureVersion() { - return "0.4.0.0"; + return "1.0.0.0"; } } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 7ef2188fb8..bb84576d66 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -25,6 +25,7 @@ THE SOFTWARE. #include "cocostudio/CCBatchNode.h" #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmature.h" +#include "cocostudio/CCSkin.h" using namespace cocos2d; @@ -44,16 +45,36 @@ BatchNode *BatchNode::create() BatchNode::BatchNode() : _atlas(NULL) + , _textureAtlasDic(NULL) { } +BatchNode::~BatchNode() +{ + CC_SAFE_RELEASE_NULL(_textureAtlasDic); +} + bool BatchNode::init() { bool ret = Node::init(); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + + CC_SAFE_DELETE(_textureAtlasDic); + _textureAtlasDic = new Dictionary(); + return ret; } +void BatchNode::addChild(Node *pChild) +{ + Node::addChild(pChild); +} + +void BatchNode::addChild(Node *child, int zOrder) +{ + Node::addChild(child, zOrder); +} + void BatchNode::addChild(Node *child, int zOrder, int tag) { Node::addChild(child, zOrder, tag); @@ -61,9 +82,58 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) if (armature != NULL) { armature->setBatchNode(this); + + Dictionary *dict = armature->getBoneDic(); + DictElement *element = NULL; + CCDICT_FOREACH(dict, element) + { + Bone *bone = static_cast(element->getObject()); + + Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); + Object *object = NULL; + CCARRAY_FOREACH(displayList, object) + { + DecorativeDisplay *display = static_cast(object); + + if (Skin *skin = dynamic_cast(display->getDisplay())) + { + skin->setTextureAtlas(getTexureAtlasWithTexture(skin->getTexture())); + } + } + } } } +void BatchNode::removeChild(Node* child, bool cleanup) +{ + Armature *armature = dynamic_cast(child); + if (armature != NULL) + { + armature->setBatchNode(NULL); + + Dictionary *dict = armature->getBoneDic(); + DictElement *element = NULL; + CCDICT_FOREACH(dict, element) + { + Bone *bone = static_cast(element->getObject()); + + Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); + Object *object = NULL; + CCARRAY_FOREACH(displayList, object) + { + DecorativeDisplay *display = static_cast(object); + + if (Skin *skin = dynamic_cast(display->getDisplay())) + { + skin->setTextureAtlas(armature->getTexureAtlasWithTexture(skin->getTexture())); + } + } + } + } + + Node::removeChild(child, cleanup); +} + void BatchNode::visit() { // quick return if not visible. children won't be drawn. @@ -118,4 +188,17 @@ void BatchNode::draw() } } +TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) +{ + int key = texture->getName(); + + TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); + if (atlas == NULL) + { + atlas = CCTextureAtlas::createWithTexture(texture, 4); + _textureAtlasDic->setObject(atlas, key); + } + return atlas; +} + } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index df33e44e0b..44f10872c2 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -38,14 +38,20 @@ public: * @js ctor */ BatchNode(); + ~BatchNode(); virtual bool init(); - virtual void addChild(cocos2d::Node *child, int zOrder, int tag); + virtual void addChild(cocos2d::Node *pChild); + virtual void addChild(cocos2d::Node *pChild, int zOrder); + virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag); + virtual void removeChild(cocos2d::Node* child, bool cleanup); virtual void visit(); void draw(); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); protected: cocos2d::TextureAtlas *_atlas; + cocos2d::Dictionary *_textureAtlasDic; }; } diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 574a66e1b0..804ea5d65a 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -75,6 +75,10 @@ Bone::Bone() _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); _boneTransformDirty = true; _blendType = BLEND_NORMAL; + _worldInfo = NULL; + + _armatureParentBone = NULL; + _dataVersion = 0; } @@ -84,6 +88,7 @@ Bone::~Bone(void) CC_SAFE_DELETE(_children); CC_SAFE_DELETE(_tween); CC_SAFE_DELETE(_displayManager); + CC_SAFE_DELETE(_worldInfo); if(_boneData) { @@ -121,6 +126,8 @@ bool Bone::init(const char *name) _displayManager = new DisplayManager(); _displayManager->init(this); + CC_SAFE_DELETE(_worldInfo); + _worldInfo = new BaseData(); bRet = true; } @@ -153,6 +160,12 @@ void Bone::setArmature(Armature *armature) if (_armature) { _tween->setAnimation(_armature->getAnimation()); + _dataVersion = _armature->getArmatureData()->dataVersion; + _armatureParentBone = _armature->getParentBone(); + } + else + { + _armatureParentBone = NULL; } } @@ -167,39 +180,50 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); - CCBone *armatureParentBone = _armature->getParentBone(); - if (armatureParentBone && !_boneTransformDirty) + if (_armatureParentBone && !_boneTransformDirty) { - _boneTransformDirty = armatureParentBone->isTransformDirty(); + _boneTransformDirty = _armatureParentBone->isTransformDirty(); } if (_boneTransformDirty) { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) + if (_dataVersion >= VERSION_COMBINED) { TransformHelp::nodeConcat(*_tweenData, *_boneData); _tweenData->scaleX -= 1; _tweenData->scaleY -= 1; } - TransformHelp::nodeToMatrix(*_tweenData, _worldTransform); + _worldInfo->copy(_tweenData); - _worldTransform = AffineTransformConcat(getNodeToParentTransform(), _worldTransform); + _worldInfo->x = _tweenData->x + _position.x; + _worldInfo->y = _tweenData->y + _position.y; + _worldInfo->scaleX = _tweenData->scaleX * _scaleX; + _worldInfo->scaleY = _tweenData->scaleY * _scaleY; + _worldInfo->skewX = _tweenData->skewX + _skewX + _rotationX; + _worldInfo->skewY = _tweenData->skewY + _skewY - _rotationY; if(_parentBone) { - _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); + applyParentTransform(_parentBone); } else { - if (armatureParentBone) + if (_armatureParentBone) { - _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); + applyParentTransform(_armatureParentBone); } } + + TransformHelp::nodeToMatrix(*_worldInfo, _worldTransform); + + if (_armatureParentBone) + { + _worldTransform = AffineTransformConcat(_worldTransform, _armature->getNodeToParentTransform()); + } } - DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); + DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); Object *object = NULL; CCARRAY_FOREACH(_children, object) @@ -211,6 +235,18 @@ void Bone::update(float delta) _boneTransformDirty = false; } +void Bone::applyParentTransform(Bone *parent) +{ + float x = _worldInfo->x; + float y = _worldInfo->y; + _worldInfo->x = x * parent->_worldTransform.a + y * parent->_worldTransform.c + parent->_worldInfo->x; + _worldInfo->y = x * parent->_worldTransform.b + y * parent->_worldTransform.d + parent->_worldInfo->y; + _worldInfo->scaleX = _worldInfo->scaleX * parent->_worldInfo->scaleX; + _worldInfo->scaleY = _worldInfo->scaleY * parent->_worldInfo->scaleY; + _worldInfo->skewX = _worldInfo->skewX + parent->_worldInfo->skewX; + _worldInfo->skewY = _worldInfo->skewY + parent->_worldInfo->skewY; +} + void Bone::updateDisplayedColor(const Color3B &parentColor) { @@ -226,6 +262,18 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } +void Bone::setColor(const Color3B& color) +{ + NodeRGBA::setColor(color); + updateColor(); +} + +void Bone::setOpacity(GLubyte opacity) +{ + NodeRGBA::setOpacity(opacity); + updateColor(); +} + void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); @@ -239,7 +287,7 @@ void Bone::updateColor() void Bone::updateZOrder() { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) + if (_dataVersion >= VERSION_COMBINED) { int zorder = _tweenData->zOrder + _boneData->zOrder; setZOrder(zorder); @@ -313,6 +361,11 @@ void Bone::setChildArmature(Armature *armature) { if (_childArmature != armature) { + if (armature == NULL && _childArmature) + { + _childArmature->setParentBone(NULL); + } + CC_SAFE_RETAIN(armature); CC_SAFE_RELEASE(_childArmature); _childArmature = armature; @@ -335,16 +388,6 @@ void Bone::setZOrder(int zOrder) Node::setZOrder(zOrder); } -void Bone::setTransformDirty(bool dirty) -{ - _boneTransformDirty = dirty; -} - -bool Bone::isTransformDirty() -{ - return _boneTransformDirty; -} - AffineTransform Bone::getNodeToArmatureTransform() const { return _worldTransform; @@ -360,6 +403,11 @@ Node *Bone::getDisplayRenderNode() return _displayManager->getDisplayRenderNode(); } +DisplayType Bone::getDisplayRenderNodeType() +{ + return _displayManager->getDisplayRenderNodeType(); +} + void Bone::addDisplay(DisplayData *displayData, int index) { _displayManager->addDisplay(displayData, index); @@ -370,6 +418,11 @@ void Bone::addDisplay(Node *display, int index) _displayManager->addDisplay(display, index); } +void Bone::removeDisplay(int index) +{ + _displayManager->removeDisplay(index); +} + void Bone::changeDisplayByIndex(int index, bool force) { _displayManager->changeDisplayByIndex(index, force); diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 1163738515..1a1d3c26d6 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -86,6 +86,8 @@ public: void addDisplay(cocos2d::Node *display, int index); + void removeDisplay(int index); + void changeDisplayByIndex(int index, bool force); /** @@ -127,6 +129,9 @@ public: void updateDisplayedColor(const cocos2d::Color3B &parentColor); void updateDisplayedOpacity(GLubyte parentOpacity); + virtual void setColor(const cocos2d::Color3B& color) override; + virtual void setOpacity(GLubyte opacity) override; + //! Update color to render display void updateColor(); @@ -140,14 +145,14 @@ public: /* * Whether or not the bone's transform property changed. if true, the bone will update the transform. */ - virtual void setTransformDirty(bool dirty); - - virtual bool isTransformDirty(); + virtual inline void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } + virtual inline bool isTransformDirty() { return _boneTransformDirty; } virtual cocos2d::AffineTransform getNodeToArmatureTransform() const; virtual cocos2d::AffineTransform getNodeToWorldTransform() const override; Node *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); /* * Get the ColliderBody list in this bone. The object in the Array is ColliderBody. @@ -177,6 +182,8 @@ public: CC_SYNTHESIZE(BlendType, _blendType, BlendType) protected: + void applyParentTransform(Bone *parent); + Tween *_tween; //! Calculate tween effect //! Used for making tween effect in every frame @@ -189,6 +196,14 @@ protected: //! self Transform, use this to change display's state cocos2d::AffineTransform _worldTransform; + + CC_SYNTHESIZE_READONLY(BaseData*, _worldInfo, WorldInfo); + + //! Armature's parent bone + Bone *_armatureParentBone; + + //! Data version + float _dataVersion; }; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 0839a30d7a..341bf503e6 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -197,7 +197,10 @@ void ColliderDetector::setActive(bool active) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - cpSpaceAddShape(_body->space_private, shape); + if(shape->space_private == NULL) + { + cpSpaceAddShape(_body->space_private, shape); + } } } else @@ -206,7 +209,10 @@ void ColliderDetector::setActive(bool active) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - cpSpaceRemoveShape(_body->space_private, shape); + if (shape->space_private != NULL) + { + cpSpaceRemoveShape(_body->space_private, shape); + } } } } diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 4749f5eaf9..83151322c5 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -133,13 +133,14 @@ static const char *VERTEX_POINT = "vertex"; static const char *COLOR_INFO = "color"; static const char *CONFIG_FILE_PATH = "config_file_path"; - +static const char *CONTENT_SCALE = "content_scale"; namespace cocostudio { - std::vector s_arrConfigFileList; +std::vector s_arrConfigFileList; float s_PositionReadScale = 1; +float s_ContentScale = 1; static float s_FlashToolVersion = VERSION_2_0; static float s_CocoStudioVersion = VERSION_COMBINED; @@ -312,7 +313,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) } } -void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target, SEL_SCHEDULE selector) +void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, Object *target, SEL_SCHEDULE selector) { /* * Check if file is already added to ArmatureDataManager, if then return. @@ -338,15 +339,16 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target s_arrConfigFileList.push_back(filePath); //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of("/"); + if (pos != std::string::npos) { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); + basefilePath = s_BasefilePath.substr(0, pos + 1); } else { - s_BasefilePath = ""; + basefilePath = ""; } @@ -378,11 +380,13 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target // generate async struct AsyncStruct *data = new AsyncStruct(); data->filename = filePath; - data->baseFilePath = s_BasefilePath; + data->baseFilePath = basefilePath; data->target = target; data->selector = selector; data->autoLoadSpriteFile = ArmatureDataManager::getInstance()->isAutoLoadSpriteFile(); + data->imagePath = imagePath; + data->plistPath = plistPath; std::string filePathStr = filePath; size_t startPos = filePathStr.find_last_of("."); @@ -428,10 +432,20 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) AsyncStruct *pAsyncStruct = pDataInfo->asyncStruct; + + if (pAsyncStruct->imagePath != "" && pAsyncStruct->plistPath != "") + { + _getFileMutex.lock(); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile(pAsyncStruct->plistPath.c_str(), pAsyncStruct->imagePath.c_str()); + _getFileMutex.unlock(); + } + while (!pDataInfo->configFileQueue.empty()) { std::string configPath = pDataInfo->configFileQueue.front(); + _getFileMutex.lock(); ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str()); + _getFileMutex.unlock(); pDataInfo->configFileQueue.pop(); } @@ -1123,12 +1137,21 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); + if (dataInfo) + { + dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); + } + else + { + s_ContentScale = json.getItemFloatValue(CONTENT_SCALE, 1); + } + // Decode armatures int length = json.getArrayItemCount(ARMATURE_DATA); for (int i = 0; i < length; i++) { JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); - ArmatureData *armatureData = decodeArmature(*armatureDic); + ArmatureData *armatureData = decodeArmature(*armatureDic, dataInfo); if (dataInfo) { @@ -1148,7 +1171,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d for (int i = 0; i < length; i++) { JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); - AnimationData *animationData = decodeAnimation(*animationDic); + AnimationData *animationData = decodeAnimation(*animationDic, dataInfo); if (dataInfo) { @@ -1215,7 +1238,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } } -ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) +ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *dataInfo) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); @@ -1232,7 +1255,7 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); - BoneData *boneData = decodeBone(*dic); + BoneData *boneData = decodeBone(*dic, dataInfo); armatureData->addBoneData(boneData); boneData->release(); @@ -1242,12 +1265,12 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) return armatureData; } -BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) +BoneData *DataReaderHelper::decodeBone(JsonDictionary &json, DataInfo *dataInfo) { BoneData *boneData = new BoneData(); boneData->init(); - decodeNode(boneData, json); + decodeNode(boneData, json, dataInfo); const char *str = json.getItemStringValue(A_NAME); if(str != NULL) @@ -1266,7 +1289,7 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); - DisplayData *displayData = decodeBoneDisplay(*dic); + DisplayData *displayData = decodeBoneDisplay(*dic, dataInfo); boneData->addDisplayData(displayData); displayData->release(); @@ -1276,7 +1299,7 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) +DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo) { DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); @@ -1304,6 +1327,18 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) sdd->skinData.scaleY = dic->getItemFloatValue(A_SCALE_Y, 1); sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); + + if (dataInfo) + { + sdd->skinData.x *= dataInfo->contentScale; + sdd->skinData.y *= dataInfo->contentScale; + } + else + { + sdd->skinData.x *= s_ContentScale; + sdd->skinData.y *= s_ContentScale; + } + delete dic; } } @@ -1327,7 +1362,14 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) const char *plist = json.getItemStringValue(A_PLIST); if(plist != NULL) { - ((ParticleDisplayData *)displayData)->plist = s_BasefilePath + plist; + if (dataInfo != NULL) + { + static_cast(displayData)->plist = dataInfo->asyncStruct->baseFilePath + plist; + } + else + { + static_cast(displayData)->plist = s_BasefilePath + plist; + } } } break; @@ -1343,7 +1385,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) +AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json, DataInfo *dataInfo) { AnimationData *aniData = new AnimationData(); @@ -1358,7 +1400,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); - MovementData *movementData = decodeMovement(*dic); + MovementData *movementData = decodeMovement(*dic, dataInfo); aniData->addMovement(movementData); movementData->release(); @@ -1368,7 +1410,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) return aniData; } -MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) +MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *dataInfo) { MovementData *movementData = new MovementData(); @@ -1389,7 +1431,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); - MovementBoneData *movementBoneData = decodeMovementBone(*dic); + MovementBoneData *movementBoneData = decodeMovementBone(*dic, dataInfo); movementData->addMovementBoneData(movementBoneData); movementBoneData->release(); @@ -1399,7 +1441,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) return movementData; } -MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) +MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo) { MovementBoneData *movementBoneData = new MovementBoneData(); movementBoneData->init(); @@ -1416,7 +1458,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); - FrameData *frameData = decodeFrame(*dic); + FrameData *frameData = decodeFrame(*dic, dataInfo); movementBoneData->addFrameData(frameData); frameData->release(); @@ -1471,11 +1513,11 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) return movementBoneData; } -FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json) +FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInfo) { FrameData *frameData = new FrameData(); - decodeNode(frameData, json); + decodeNode(frameData, json, dataInfo); frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); @@ -1554,10 +1596,23 @@ ContourData *DataReaderHelper::decodeContour(JsonDictionary &json) return contourData; } -void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json) +void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo) { node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; + + if (dataInfo) + { + node->x *= dataInfo->contentScale; + node->y *= dataInfo->contentScale; + } + else + { + node->x *= s_ContentScale; + node->y *= s_ContentScale; + } + + node->zOrder = json.getItemIntValue(A_Z, 0); node->skewX = json.getItemFloatValue(A_SKEW_X, 0); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index d5c8a0d6f5..a9159ef39e 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -63,12 +63,16 @@ protected: cocos2d::Object *target; cocos2d::SEL_SCHEDULE selector; bool autoLoadSpriteFile; + + std::string imagePath; + std::string plistPath; } AsyncStruct; typedef struct _DataInfo { AsyncStruct *asyncStruct; std::queue configFileQueue; + float contentScale; } DataInfo; public: @@ -99,7 +103,7 @@ public: ~DataReaderHelper(); void addDataFromFile(const char *filePath); - void addDataFromFileAsync(const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); + void addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); @@ -145,20 +149,20 @@ public: public: static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); - static ArmatureData *decodeArmature(JsonDictionary &json); - static BoneData *decodeBone(JsonDictionary &json); - static DisplayData *decodeBoneDisplay(JsonDictionary &json); + static ArmatureData *decodeArmature(JsonDictionary &json, DataInfo *dataInfo); + static BoneData *decodeBone(JsonDictionary &json, DataInfo *dataInfo); + static DisplayData *decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo); - static AnimationData *decodeAnimation(JsonDictionary &json); - static MovementData *decodeMovement(JsonDictionary &json); - static MovementBoneData *decodeMovementBone(JsonDictionary &json); - static FrameData *decodeFrame(JsonDictionary &json); + static AnimationData *decodeAnimation(JsonDictionary &json, DataInfo *dataInfo); + static MovementData *decodeMovement(JsonDictionary &json, DataInfo *dataInfo); + static MovementBoneData *decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo); + static FrameData *decodeFrame(JsonDictionary &json, DataInfo *dataInfo); static TextureData *decodeTexture(JsonDictionary &json); static ContourData *decodeContour(JsonDictionary &json); - static void decodeNode(BaseData *node, JsonDictionary &json); + static void decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo); protected: void loadData(); @@ -177,6 +181,8 @@ protected: std::mutex _addDataMutex; + std::mutex _getFileMutex; + unsigned long _asyncRefCount; unsigned long _asyncRefTotalCount; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 034f115481..b130428ab1 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -70,13 +70,15 @@ void DisplayFactory::createDisplay(Bone *bone, DecorativeDisplay *decoDisplay) } } -void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, float dt, bool dirty) +void DisplayFactory::updateDisplay(Bone *bone, float dt, bool dirty) { - CS_RETURN_IF(!decoDisplay); + Node *display = bone->getDisplayRenderNode(); + CS_RETURN_IF(!display); #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT if (dirty) { + DecorativeDisplay *decoDisplay = bone->getDisplayManager()->getCurrentDecorativeDisplay(); ColliderDetector *detector = decoDisplay->getColliderDetector(); if (detector) { @@ -84,9 +86,8 @@ void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, f { CC_BREAK_IF(!detector->getBody()); - Node *node = decoDisplay->getDisplay(); - AffineTransform displayTransform = node->getNodeToParentTransform(); - Point anchorPoint = node->getAnchorPointInPoints(); + AffineTransform displayTransform = display->getNodeToParentTransform(); + Point anchorPoint = display->getAnchorPointInPoints(); anchorPoint = PointApplyAffineTransform(anchorPoint, displayTransform); displayTransform.tx = anchorPoint.x; displayTransform.ty = anchorPoint.y; @@ -98,18 +99,19 @@ void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, f } #endif - Node *display = decoDisplay->getDisplay(); - - switch(decoDisplay->getDisplayData()->displayType) + switch(bone->getDisplayRenderNodeType()) { case CS_DISPLAY_SPRITE: - updateSpriteDisplay(bone, display, dt, dirty); + if (dirty) + { + static_cast(display)->updateArmatureTransform(); + } break; case CS_DISPLAY_PARTICLE: - updateParticleDisplay(bone, display, dt, dirty); + updateParticleDisplay(bone, display, dt); break; case CS_DISPLAY_ARMATURE: - updateArmatureDisplay(bone, display, dt, dirty); + updateArmatureDisplay(bone, display, dt); break; default: { @@ -153,6 +155,13 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp skin = Skin::createWithSpriteFrameName((textureName + ".png").c_str()); } + decoDisplay->setDisplay(skin); + + if (skin == NULL) + { + return; + } + skin->setBone(bone); initSpriteDisplay(bone, decoDisplay, displayData->displayName.c_str(), skin); @@ -170,8 +179,6 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp } } - decoDisplay->setDisplay(skin); - } void DisplayFactory::initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin) @@ -206,17 +213,11 @@ void DisplayFactory::initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDispla #endif } -void DisplayFactory::updateSpriteDisplay(Bone *bone, Node *display, float dt, bool dirty) -{ - CS_RETURN_IF(!dirty); - Skin *skin = (Skin *)display; - skin->updateArmatureTransform(); -} void DisplayFactory::addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { - ArmatureDisplayData *adp = ArmatureDisplayData::create(); ; + ArmatureDisplayData *adp = ArmatureDisplayData::create(); adp->copy((ArmatureDisplayData *)displayData); decoDisplay->setDisplayData(adp); @@ -228,15 +229,9 @@ void DisplayFactory::createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDi Armature *armature = Armature::create(displayData->displayName.c_str(), bone); - /* - * because this bone have called this name, so armature should change it's name, or it can't add to - * Armature's bone children. - */ - armature->setName((bone->getName() + "_armatureChild").c_str()); - decoDisplay->setDisplay(armature); } -void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt, bool dirty) +void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt) { Armature *armature = (Armature *)display; if(armature) @@ -262,7 +257,7 @@ void DisplayFactory::createParticleDisplay(Bone *bone, DecorativeDisplay *decoDi ParticleSystem *system = ParticleSystemQuad::create(displayData->plist.c_str()); decoDisplay->setDisplay(system); } -void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt, bool dirty) +void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt) { ParticleSystem *system = (ParticleSystem *)display; BaseData node; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.h b/cocos/editor-support/cocostudio/CCDisplayFactory.h index 3ef0725ff0..a62329d548 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.h +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.h @@ -40,21 +40,20 @@ class DisplayFactory public: static void addDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, float dt, bool dirty); + static void updateDisplay(Bone *bone, float dt, bool dirty); static void addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay); static void initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin); - static void updateSpriteDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); static void addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); + static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt); static void addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); + static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt); }; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index ae1ed19781..bffcf80c64 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -48,6 +48,7 @@ DisplayManager *DisplayManager::create(Bone *bone) DisplayManager::DisplayManager() : _decoDisplayList(NULL) , _displayRenderNode(NULL) + , _displayType(CS_DISPLAY_MAX) , _currentDecoDisplay(NULL) , _displayIndex(-1) , _forceChangeDisplay(false) @@ -137,7 +138,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); - ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; + ((SpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { @@ -172,12 +173,13 @@ void DisplayManager::addDisplay(Node *display, int index) void DisplayManager::removeDisplay(int index) { - _decoDisplayList->removeObjectAtIndex(index); - if(index == _displayIndex) { setCurrentDecorativeDisplay(NULL); + _displayIndex = -1; } + + _decoDisplayList->removeObjectAtIndex(index); } Array *DisplayManager::getDecorativeDisplayList() @@ -265,6 +267,12 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) _displayRenderNode->retain(); _displayRenderNode->setVisible(_visible); + + _displayType = _currentDecoDisplay->getDisplayData()->displayType; + } + else + { + _displayType = CS_DISPLAY_MAX; } } @@ -273,6 +281,12 @@ Node *DisplayManager::getDisplayRenderNode() return _displayRenderNode; } + +DisplayType DisplayManager::getDisplayRenderNodeType() +{ + return _displayType; +} + int DisplayManager::getCurrentDisplayIndex() { return _displayIndex; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.h b/cocos/editor-support/cocostudio/CCDisplayManager.h index 9953d77995..0856886c57 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/CCDisplayManager.h @@ -91,6 +91,7 @@ public: cocos2d::Node *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); int getCurrentDisplayIndex(); @@ -133,6 +134,8 @@ protected: cocos2d::Array *_decoDisplayList; //! Display render node. cocos2d::Node *_displayRenderNode; + //! Display render node type + DisplayType _displayType; //! Include current display information, like contour sprite, etc. DecorativeDisplay *_currentDecoDisplay; //! Current display index diff --git a/cocos/editor-support/cocostudio/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp index c3e1bfbc20..1c9bd8965e 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -141,8 +141,18 @@ void ProcessBase::update(float dt) void ProcessBase::gotoFrame(int frameIndex) { + if (_loopType == ANIMATION_NO_LOOP) + { + _loopType = ANIMATION_MAX; + } + else if (_loopType == ANIMATION_TO_LOOP_FRONT) + { + _loopType = ANIMATION_LOOP_FRONT; + } + _curFrameIndex = frameIndex; - pause(); + + _nextFrameIndex = _durationTween; } int ProcessBase::getCurrentFrameIndex() diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index 9f80fb2ea7..77c5da4ebb 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -104,8 +104,6 @@ public: virtual void stop(); - virtual void gotoFrame(int frameIndex); - /** * You should never call this function, unless you know what you do * Update the Process, include current process, current frame and son on @@ -118,6 +116,7 @@ public: protected: + virtual void gotoFrame(int frameIndex); /** * Update(float dt) will call this handler, you can handle your logic here diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index d1c66ddc3e..5cb8483a95 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -37,6 +37,8 @@ namespace cocostudio { #define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) #endif +#define SET_VERTEX3F(_v_, _x_, _y_, _z_) (_v_).x = (_x_); (_v_).y = (_y_); (_v_).z = (_z_); + Skin *Skin::create() { Skin *skin = new Skin(); @@ -75,6 +77,7 @@ Skin *Skin::create(const char *pszFileName) Skin::Skin() : _bone(NULL) + , _armature(NULL) , _displayName("") { _skinTransform = AffineTransformIdentity; @@ -82,15 +85,22 @@ Skin::Skin() bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) { - bool ret = Sprite::initWithSpriteFrameName(pszSpriteFrameName); + CCAssert(pszSpriteFrameName != NULL, ""); - if (ret) + SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pszSpriteFrameName); + bool ret = true; + + if (pFrame != NULL) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszSpriteFrameName; + ret = initWithSpriteFrame(pFrame); } + else + { + CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", pszSpriteFrameName); + ret = false; + } + + _displayName = pszSpriteFrameName; return ret; } @@ -99,13 +109,7 @@ bool Skin::initWithFile(const char *pszFilename) { bool ret = Sprite::initWithFile(pszFilename); - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszFilename; - } + _displayName = pszFilename; return ret; } @@ -116,7 +120,8 @@ void Skin::setSkinData(const BaseData &var) setScaleX(_skinData.scaleX); setScaleY(_skinData.scaleY); - setRotation(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationX(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationY(CC_RADIANS_TO_DEGREES(-_skinData.skewY)); setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); @@ -131,6 +136,10 @@ const BaseData &Skin::getSkinData() const void Skin::updateArmatureTransform() { _transform = AffineTransformConcat(_skinTransform, _bone->getNodeToArmatureTransform()); + if(_armature && _armature->getBatchNode()) + { + _transform = AffineTransformConcat(_transform, _armature->getNodeToParentTransform()); + } } void Skin::updateTransform() @@ -173,10 +182,10 @@ void Skin::updateTransform() float dx = x1 * cr - y2 * sr2 + x; float dy = x1 * sr + y2 * cr2 + y; - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); + SET_VERTEX3F( _quad.bl.vertices, RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); + SET_VERTEX3F( _quad.br.vertices, RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); + SET_VERTEX3F( _quad.tl.vertices, RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); + SET_VERTEX3F( _quad.tr.vertices, RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); } // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS @@ -204,4 +213,20 @@ AffineTransform Skin::getNodeToWorldTransformAR() const return AffineTransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); } +void Skin::setBone(Bone *bone) +{ + _bone = bone; + if(Armature *armature = _bone->getArmature()) + { + _armature = armature; + TextureAtlas *atlas = armature->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); + } +} + +Bone *Skin::getBone() +{ + return _bone; +} + } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 3494c48436..2d934b8e4b 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -49,9 +49,10 @@ public: cocos2d::AffineTransform getNodeToWorldTransformAR() const; CC_PROPERTY_PASS_BY_REF(BaseData, _skinData, SkinData); - CC_SYNTHESIZE(Bone *, _bone, Bone); + CC_PROPERTY(Bone *, _bone, Bone); protected: + Armature *_armature; cocos2d::AffineTransform _skinTransform; CC_SYNTHESIZE_READONLY(std::string, _displayName, DisplayName) }; diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index d783c4ba4e..68fa7ebfb5 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -52,26 +52,12 @@ void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *plistPath, const CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); } -TextureAtlas *SpriteFrameCacheHelper::getTexureAtlasWithTexture(Texture2D *texture) -{ - int key = texture->getName(); - TextureAtlas *atlas = (TextureAtlas *)_textureAtlasDic->objectForKey(key); - if (atlas == NULL) - { - atlas = TextureAtlas::createWithTexture(texture, 4); - _textureAtlasDic->setObject(atlas, key); - } - return atlas; -} - SpriteFrameCacheHelper::SpriteFrameCacheHelper() { - _textureAtlasDic = new Dictionary(); } SpriteFrameCacheHelper::~SpriteFrameCacheHelper() { - CC_SAFE_RELEASE_NULL(_textureAtlasDic); } } diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index 150fe96aaa..81ccf1b1f9 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -47,8 +47,6 @@ public: */ void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); - cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); - private: /** * @js ctor @@ -60,8 +58,6 @@ private: */ ~SpriteFrameCacheHelper(); - cocos2d::Dictionary *_textureAtlasDic; - static SpriteFrameCacheHelper *_spriteFrameCacheHelper; }; diff --git a/cocos/editor-support/cocostudio/CCTransformHelp.cpp b/cocos/editor-support/cocostudio/CCTransformHelp.cpp index a836055c16..0107760a3b 100644 --- a/cocos/editor-support/cocostudio/CCTransformHelp.cpp +++ b/cocos/editor-support/cocostudio/CCTransformHelp.cpp @@ -96,10 +96,23 @@ void TransformHelp::transformToParentWithoutScale(BaseData &node, const BaseData void TransformHelp::nodeToMatrix(const BaseData &node, AffineTransform &matrix) { - matrix.a = node.scaleX * cos(node.skewY); - matrix.b = node.scaleX * sin(node.skewY); - matrix.c = node.scaleY * sin(node.skewX); - matrix.d = node.scaleY * cos(node.skewX); + if (node.skewX == -node.skewY) + { + double sine = sin(node.skewX); + double cosine = cos(node.skewX); + + matrix.a = node.scaleX * cosine; + matrix.b = node.scaleX * -sine; + matrix.c = node.scaleY * sine; + matrix.d = node.scaleY * cosine; + } + else + { + matrix.a = node.scaleX * cos(node.skewY); + matrix.b = node.scaleX * sin(node.skewY); + matrix.c = node.scaleY * sin(node.skewX); + matrix.d = node.scaleY * cos(node.skewX); + } matrix.tx = node.x; matrix.ty = node.y; diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 8fec95b2a0..5704867a61 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -99,7 +99,14 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio { ProcessBase::play(NULL, durationTo, durationTween, loop, tweenEasing); - _loopType = (AnimationType)loop; + if (loop) + { + _loopType = ANIMATION_TO_LOOP_FRONT; + } + else + { + _loopType = ANIMATION_NO_LOOP; + } _totalDuration = 0; _betweenDuration = 0; @@ -135,15 +142,6 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio } else if (_movementBoneData->frameList.count() > 1) { - if (loop) - { - _loopType = ANIMATION_TO_LOOP_BACK; - } - else - { - _loopType = ANIMATION_NO_LOOP; - } - _durationTween = durationTween * _movementBoneData->scale; if (loop && _movementBoneData->delay != 0) @@ -166,6 +164,27 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio tweenNodeTo(0); } +void Tween::gotoAndPlay(int frameIndex) +{ + ProcessBase::gotoFrame(frameIndex); + + _totalDuration = 0; + _betweenDuration = 0; + _fromIndex = _toIndex = 0; + + _isPlaying = true; + _isComplete = _isPause = false; + + _currentPercent = (float)_curFrameIndex / (float)_rawDuration; + _currentFrame = _nextFrameIndex * _currentPercent; +} + +void Tween::gotoAndPause(int frameIndex) +{ + gotoAndPlay(frameIndex); + pause(); +} + void Tween::updateHandler() { if (_currentPercent >= 1) @@ -211,9 +230,9 @@ void Tween::updateHandler() } } break; - case ANIMATION_TO_LOOP_BACK: + case ANIMATION_TO_LOOP_FRONT: { - _loopType = ANIMATION_LOOP_BACK; + _loopType = ANIMATION_LOOP_FRONT; _nextFrameIndex = _durationTween > 0 ? _durationTween : 1; @@ -244,10 +263,6 @@ void Tween::updateHandler() default: { _currentFrame = fmodf(_currentFrame, _nextFrameIndex); - - _totalDuration = 0; - _betweenDuration = 0; - _fromIndex = _toIndex = 0; } break; } @@ -342,7 +357,7 @@ FrameData *Tween::tweenNodeTo(float percent, FrameData *node) if (!_from->isTween) { - return _from; + percent = 0; } node->x = _from->x + percent * _between->x; @@ -393,6 +408,7 @@ float Tween::updateFrameData(float currentPercent) FrameData *from = NULL; FrameData *to = NULL; + bool passLastFrame = false; if (playedTime < frames[0]->frameID) { @@ -402,32 +418,31 @@ float Tween::updateFrameData(float currentPercent) } else if(playedTime >= frames[length - 1]->frameID) { - from = to = frames[length - 1]; - setBetween(from, to); - return currentPercent; + passLastFrame = true; } do { + _fromIndex = _toIndex; from = frames[_fromIndex]; _totalDuration = from->frameID; - if (++_toIndex >= length) + _toIndex = _fromIndex + 1; + if (_toIndex >= length) { _toIndex = 0; } - _fromIndex = _toIndex; to = frames[_toIndex]; //! Guaranteed to trigger frame event - if(from->strEvent.length() != 0) + if(from->strEvent.length() != 0 && !_animation->isIgnoreFrameEvent()) { _animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime); } - if (playedTime == from->frameID) + if (playedTime == from->frameID || (passLastFrame && _fromIndex == length-1)) { break; } diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 80b6c6d7e9..5e5bea6356 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -83,14 +83,11 @@ public: */ virtual void play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing); - inline void setAnimation(ArmatureAnimation *animation) - { - _animation = animation; - } - inline ArmatureAnimation *getAnimation() const - { - return _animation; - } + inline void setAnimation(ArmatureAnimation *animation) { _animation = animation; } + inline ArmatureAnimation *getAnimation() const { return _animation; } + + virtual void gotoAndPlay(int frameIndex); + virtual void gotoAndPause(int frameIndex); protected: /** diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 1cd233ffd2..4421be8ccb 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -30,6 +30,9 @@ Layer *CreateLayer(int index) case TEST_PERFORMANCE: pLayer = new TestPerformance(); break; + case TEST_PERFORMANCE_BATCHNODE: + pLayer = new TestPerformanceBatchNode(); + break; case TEST_CHANGE_ZORDER: pLayer = new TestChangeZorder(); break; @@ -54,6 +57,9 @@ Layer *CreateLayer(int index) case TEST_ARMATURE_NESTING: pLayer = new TestArmatureNesting(); break; + case TEST_ARMATURE_NESTING_2: + pLayer = new TestArmatureNesting2(); + break; default: break; } @@ -235,6 +241,9 @@ void TestAsynchronousLoading::onEnter() ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/Cowboy.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/hero.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/horse.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/bear.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); //! load data directly // ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml"); @@ -314,6 +323,8 @@ std::string TestDragonBones20::title() +#define ArmaturePerformanceTag 20000 + TestPerformance::~TestPerformance() { } @@ -321,10 +332,22 @@ void TestPerformance::onEnter() { ArmatureTestLayer::onEnter(); + + MenuItemFont::setFontSize(65); + MenuItemFont *decrease = MenuItemFont::create(" - ", this, menu_selector(TestPerformance::onDecrease)); + decrease->setColor(ccc3(0,200,20)); + MenuItemFont *increase = MenuItemFont::create(" + ", this, menu_selector(TestPerformance::onIncrease)); + increase->setColor(ccc3(0,200,20)); + + Menu *menu = Menu::create(decrease, increase, NULL); + menu->alignItemsHorizontally(); + menu->setPosition(ccp(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); + addChild(menu, 10000); + armatureCount = frames = times = lastTimes = 0; generated = false; - scheduleUpdate(); + addArmature(100); } std::string TestPerformance::title() @@ -335,37 +358,76 @@ std::string TestPerformance::subtitle() { return "Current Armature Count : "; } -void TestPerformance::addArmature(Armature *armature) +void TestPerformance::onIncrease(Object* pSender) { - armatureCount++; - addChild(armature, armatureCount); + addArmature(20); } -void TestPerformance::update(float delta) +void TestPerformance::onDecrease(Object* pSender) { - frames ++; - times += delta; + if (armatureCount == 0) + return; - if (frames / times > 58) + for (int i = 0; i<20; i++) { + removeArmatureFromParent(ArmaturePerformanceTag + armatureCount); + armatureCount --; + refreshTitile(); + } +} +void TestPerformance::addArmature(int number) +{ + for (int i = 0; iinit("Knight_f/Knight"); armature->getAnimation()->playByIndex(0); armature->setPosition(50 + armatureCount * 2, 150); armature->setScale(0.6f); - addArmature(armature); + addArmatureToParent(armature); armature->release(); - - char pszCount[255]; - sprintf(pszCount, "%s %i", subtitle().c_str(), armatureCount); - LabelTTF *label = (LabelTTF *)getChildByTag(10001); - label->setString(pszCount); } + + refreshTitile(); +} +void TestPerformance::addArmatureToParent(cocostudio::Armature *armature) +{ + addChild(armature, 0, ArmaturePerformanceTag + armatureCount); +} +void TestPerformance::removeArmatureFromParent(int tag) +{ + removeChildByTag(ArmaturePerformanceTag + armatureCount); +} +void TestPerformance::refreshTitile() +{ + char pszCount[255]; + sprintf(pszCount, "%s %i", subtitle().c_str(), armatureCount); + LabelTTF *label = (LabelTTF *)getChildByTag(10001); + label->setString(pszCount); } +void TestPerformanceBatchNode::onEnter() +{ + batchNode = BatchNode::create(); + addChild(batchNode); - + TestPerformance::onEnter(); +} +std::string TestPerformanceBatchNode::title() +{ + return "Test Performance of using BatchNode"; +} +void TestPerformanceBatchNode::addArmatureToParent(cocostudio::Armature *armature) +{ + batchNode->addChild(armature, 0, ArmaturePerformanceTag + armatureCount); +} +void TestPerformanceBatchNode::removeArmatureFromParent(int tag) +{ + batchNode->removeChildByTag(ArmaturePerformanceTag + armatureCount); +} void TestChangeZorder::onEnter() @@ -905,7 +967,7 @@ void TestBoundingBox::draw() { CC_NODE_DRAW_SETUP(); - rect = RectApplyAffineTransform(armature->getBoundingBox(), armature->getNodeToParentTransform()); + rect = armature->getBoundingBox(); DrawPrimitives::setDrawColor4B(100, 100, 100, 255); DrawPrimitives::drawRect(rect.origin, Point(rect.getMaxX(), rect.getMaxY())); @@ -977,3 +1039,185 @@ void TestArmatureNesting::onTouchesEnded(const std::vector& touches, Eve armature->getBone("armOutside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); } } + + + + +Hero *Hero::create(const char *name) +{ + Hero *hero = new Hero(); + if (hero && hero->init(name)) + { + hero->autorelease(); + return hero; + } + CC_SAFE_DELETE(hero); + return NULL; +} + +Hero::Hero() + : m_pMount(NULL) + , m_pLayer(NULL) +{ +} + +void Hero::changeMount(Armature *armature) +{ + if (armature == NULL) + { + retain(); + + playByIndex(0); + //Remove hero from display list + m_pMount->getBone("hero")->removeDisplay(0); + m_pMount->stopAllActions(); + + //Set position to current position + setPosition(m_pMount->getPosition()); + //Add to layer + m_pLayer->addChild(this); + + release(); + + setMount(armature); + } + else + { + setMount(armature); + + retain(); + //Remove from layer + removeFromParentAndCleanup(false); + + //Get the hero bone + Bone *bone = armature->getBone("hero"); + //Add hero as a display to this bone + bone->addDisplay(this, 0); + //Change this bone's display + bone->changeDisplayByIndex(0, true); + bone->setIgnoreMovementBoneData(true); + + setPosition(ccp(0,0)); + //Change animation + playByIndex(1); + + setScale(1); + + release(); + } + +} + +void Hero::playByIndex(int index) +{ + _animation->playByIndex(index); + if (m_pMount) + { + m_pMount->getAnimation()->playByIndex(index); + } +} + +void TestArmatureNesting2::onEnter() +{ + ArmatureTestLayer::onEnter(); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting2::onTouchesEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + + touchedMenu = false; + + LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); + MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(TestArmatureNesting2::ChangeMountCallback)); + + Menu* pMenu =Menu::create(pMenuItem, NULL); + + pMenu->setPosition( CCPointZero ); + pMenuItem->setPosition( ccp( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); + + addChild(pMenu, 2); + + //Create a hero + hero = Hero::create("hero"); + hero->setLayer(this); + hero->playByIndex(0); + hero->setPosition(ccp(VisibleRect::left().x + 20, VisibleRect::left().y)); + addChild(hero); + + //Create 3 mount + horse = createMount("horse", VisibleRect::center()); + + horse2 = createMount("horse", ccp(120, 200)); + horse2->setOpacity(200); + + bear = createMount("bear", ccp(300,70)); +} +void TestArmatureNesting2::onExit() +{ + ArmatureTestLayer::onExit(); +} +std::string TestArmatureNesting2::title() +{ + return "Test CCArmature Nesting 2"; +} +std::string TestArmatureNesting2::subtitle() +{ + return "Move to a mount and press the ChangeMount Button."; +} +void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Event* event) +{ + Point point = touches[0]->getLocation(); + + Armature *armature = hero->getMount() == NULL ? hero : hero->getMount(); + + //Set armature direction + if (point.x < armature->getPositionX()) + { + armature->setScaleX(-1); + } + else + { + armature->setScaleX(1); + } + + ActionInterval *move = CCMoveTo::create(2, point); + armature->stopAllActions(); + armature->runAction(Sequence::create(move, CallFunc::create(this, NULL), NULL)); +} + +void TestArmatureNesting2::ChangeMountCallback(Object* pSender) +{ + hero->stopAllActions(); + + if (hero->getMount()) + { + hero->changeMount(NULL); + } + else + { + if (ccpDistance(hero->getPosition(), horse->getPosition()) < 20) + { + hero->changeMount(horse); + } + else if (ccpDistance(hero->getPosition(), horse2->getPosition()) < 20) + { + hero->changeMount(horse2); + } + else if (ccpDistance(hero->getPosition(), bear->getPosition()) < 30) + { + hero->changeMount(bear); + } + } +} + +Armature * TestArmatureNesting2::createMount(const char *name, Point position) +{ + Armature *armature = Armature::create(name); + armature->getAnimation()->playByIndex(0); + armature->setPosition(position); + addChild(armature); + + return armature; +} + diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index 51b47085b5..f5a7787168 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -30,6 +30,7 @@ enum { TEST_COCOSTUDIO_WITH_SKELETON, TEST_DRAGON_BONES_2_0, TEST_PERFORMANCE, + TEST_PERFORMANCE_BATCHNODE, TEST_CHANGE_ZORDER, TEST_ANIMATION_EVENT, TEST_PARTICLE_DISPLAY, @@ -38,6 +39,7 @@ enum { TEST_BOUDINGBOX, TEST_ANCHORPOINT, TEST_ARMATURE_NESTING, + TEST_ARMATURE_NESTING_2, TEST_LAYER_COUNT }; @@ -97,8 +99,12 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); - virtual void addArmature(cocostudio::Armature *armature); - void update(float delta); + virtual void onIncrease(Object* pSender); + virtual void onDecrease(Object* pSender); + virtual void addArmature(int number); + virtual void addArmatureToParent(cocostudio::Armature *armature); + virtual void removeArmatureFromParent(int tag); + virtual void refreshTitile(); int armatureCount; @@ -108,6 +114,15 @@ public: bool generated; }; +class TestPerformanceBatchNode : public TestPerformance +{ + virtual void onEnter(); + virtual std::string title(); + virtual void addArmatureToParent(cocostudio::Armature *armature); + virtual void removeArmatureFromParent(int tag); + + cocostudio::BatchNode *batchNode; +}; class TestChangeZorder : public ArmatureTestLayer { @@ -256,4 +271,39 @@ public: cocostudio::Armature *armature; int weaponIndex; }; + +class Hero : public cocostudio::Armature +{ +public: + static Hero *create(const char *name); + Hero(); + + virtual void changeMount(cocostudio::Armature *armature); + virtual void playByIndex(int index); + + CC_SYNTHESIZE(cocostudio::Armature*, m_pMount, Mount); + CC_SYNTHESIZE(cocos2d::Layer*, m_pLayer, Layer); +}; + +class TestArmatureNesting2 : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual void onExit(); + virtual std::string title(); + virtual std::string subtitle(); + void onTouchesEnded(const std::vector& touches, Event* event); + + virtual void ChangeMountCallback(Object* pSender); + virtual cocostudio::Armature *createMount(const char *name, Point position); + + Hero *hero; + + cocostudio::Armature *horse; + cocostudio::Armature *horse2; + cocostudio::Armature *bear; + + + bool touchedMenu; +}; #endif // __HELLOWORLD_SCENE_H__ \ No newline at end of file From ef973b5737f8d441f3333c2470e97aae9a91d5eb Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 30 Oct 2013 09:54:05 +0800 Subject: [PATCH 013/197] upload resource --- .../Cpp/TestCpp/Resources/armature/Dragon.xml | 354 ++++++++++++------ 1 file changed, 241 insertions(+), 113 deletions(-) diff --git a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml b/samples/Cpp/TestCpp/Resources/armature/Dragon.xml index 0b4f52cf06..f531349f7c 100644 --- a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml +++ b/samples/Cpp/TestCpp/Resources/armature/Dragon.xml @@ -1,56 +1,56 @@ - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + @@ -58,158 +58,286 @@ - - - + + + - + - + - + - - - + + + - - - + + + - + - - - + + + - - - + + + - - - + + + - + - + - + - + - + - - - + + + - + - - - + + + - + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - + - - - + + + - - - + + + - - - + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 80b97be6f4378a2bc0b1b58ead232b98f53ad280 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 30 Oct 2013 11:34:16 +0800 Subject: [PATCH 014/197] update develop --- .../cocostudio/CCDataReaderHelper.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 33 +++++++++---------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 83151322c5..3fb1b69fb8 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -344,7 +344,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p if (pos != std::string::npos) { - basefilePath = s_BasefilePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); } else { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 4421be8ccb..625308dd01 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -334,14 +334,14 @@ void TestPerformance::onEnter() MenuItemFont::setFontSize(65); - MenuItemFont *decrease = MenuItemFont::create(" - ", this, menu_selector(TestPerformance::onDecrease)); - decrease->setColor(ccc3(0,200,20)); - MenuItemFont *increase = MenuItemFont::create(" + ", this, menu_selector(TestPerformance::onIncrease)); - increase->setColor(ccc3(0,200,20)); + MenuItemFont *decrease = MenuItemFont::create(" - ", CC_CALLBACK_1(TestPerformance::onDecrease, this)); + decrease->setColor(Color3B(0,200,20)); + MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); + increase->setColor(Color3B(0,200,20)); Menu *menu = Menu::create(decrease, increase, NULL); menu->alignItemsHorizontally(); - menu->setPosition(ccp(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); + menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); addChild(menu, 10000); armatureCount = frames = times = lastTimes = 0; @@ -1097,7 +1097,7 @@ void Hero::changeMount(Armature *armature) bone->changeDisplayByIndex(0, true); bone->setIgnoreMovementBoneData(true); - setPosition(ccp(0,0)); + setPosition(Point(0,0)); //Change animation playByIndex(1); @@ -1125,16 +1125,15 @@ void TestArmatureNesting2::onEnter() listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting2::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - touchedMenu = false; LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); - MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(TestArmatureNesting2::ChangeMountCallback)); + MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::ChangeMountCallback, this)); Menu* pMenu =Menu::create(pMenuItem, NULL); - pMenu->setPosition( CCPointZero ); - pMenuItem->setPosition( ccp( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); + pMenu->setPosition( Point() ); + pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); addChild(pMenu, 2); @@ -1142,16 +1141,16 @@ void TestArmatureNesting2::onEnter() hero = Hero::create("hero"); hero->setLayer(this); hero->playByIndex(0); - hero->setPosition(ccp(VisibleRect::left().x + 20, VisibleRect::left().y)); + hero->setPosition(Point(VisibleRect::left().x + 20, VisibleRect::left().y)); addChild(hero); //Create 3 mount horse = createMount("horse", VisibleRect::center()); - horse2 = createMount("horse", ccp(120, 200)); + horse2 = createMount("horse", Point(120, 200)); horse2->setOpacity(200); - bear = createMount("bear", ccp(300,70)); + bear = createMount("bear", Point(300,70)); } void TestArmatureNesting2::onExit() { @@ -1183,7 +1182,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev ActionInterval *move = CCMoveTo::create(2, point); armature->stopAllActions(); - armature->runAction(Sequence::create(move, CallFunc::create(this, NULL), NULL)); + armature->runAction(Sequence::create(move, NULL)); } void TestArmatureNesting2::ChangeMountCallback(Object* pSender) @@ -1196,15 +1195,15 @@ void TestArmatureNesting2::ChangeMountCallback(Object* pSender) } else { - if (ccpDistance(hero->getPosition(), horse->getPosition()) < 20) + if (hero->getPosition().getDistance(horse->getPosition()) < 20) { hero->changeMount(horse); } - else if (ccpDistance(hero->getPosition(), horse2->getPosition()) < 20) + else if (hero->getPosition().getDistance(horse2->getPosition()) < 20) { hero->changeMount(horse2); } - else if (ccpDistance(hero->getPosition(), bear->getPosition()) < 30) + else if (hero->getPosition().getDistance(bear->getPosition()) < 30) { hero->changeMount(bear); } From 391cda44ef17d514eec4994118a1651f2fec7eb4 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 30 Oct 2013 15:53:58 +0800 Subject: [PATCH 016/197] issue #2771: edit listener --- cocos/physics/CCPhysicsContact.cpp | 99 +++++++++++++++++++ cocos/physics/CCPhysicsContact.h | 31 +++++- .../Classes/PhysicsTest/PhysicsTest.cpp | 25 +++++ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 7 ++ 4 files changed, 159 insertions(+), 3 deletions(-) diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 71ed2beb01..400dc10477 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -186,5 +186,104 @@ PhysicsContactListener::~PhysicsContactListener() } +PhysicsContactListener* PhysicsContactListener::create() +{ + PhysicsContactListener* obj = new PhysicsContactListener(); + + if (obj != nullptr) + { + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool PhysicsContactListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + CC_UNUSED_PARAM(shapeA); + CC_UNUSED_PARAM(shapeB); + return true; +} + +bool PhysicsContactListener::checkAvaiable() +{ + if (onContactBegin == nullptr && onContactPreSolve == nullptr + && onContactPostSolve == nullptr && onContactEnd == nullptr) + { + CCASSERT(false, "Invalid PhysicsContactListener."); + return false; + } + + return true; +} + +EventListener* PhysicsContactListener::clone() +{ + PhysicsContactListener* obj = PhysicsContactListener::create(); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactEnd = onContactEnd; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + + + + +PhysicsContactWithBodysListener* PhysicsContactWithBodysListener::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + PhysicsContactWithBodysListener* obj = new PhysicsContactWithBodysListener(); + + if (obj != nullptr) + { + obj->_a = shapeA; + obj->_b = shapeB; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool PhysicsContactWithBodysListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if ((shapeA == _a && shapeB == _b) + || (shapeA == _b && shapeB == _a)) + { + return true; + } + + return false; +} + +EventListener* PhysicsContactWithBodysListener::clone() +{ + PhysicsContactWithBodysListener* obj = PhysicsContactWithBodysListener::create(_a, _b); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactEnd = onContactEnd; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 6c96539c92..48c234b1ad 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -30,6 +30,7 @@ #include "CCObject.h" #include "CCGeometry.h" +#include "CCEventListener.h" NS_CC_BEGIN @@ -154,11 +155,14 @@ private: /* * @brief contact listener. */ -class PhysicsContactListener +class PhysicsContactListener : public EventListener { public: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); + static PhysicsContactListener* create(); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool checkAvaiable(); + virtual EventListener* clone(); public: /* @@ -178,6 +182,27 @@ public: * onContactBegin and onContactEnd will called in pairs. */ std::function onContactEnd; + +protected: + PhysicsContactListener(); + virtual ~PhysicsContactListener(); +}; + +class PhysicsContactWithBodysListener : public PhysicsContactListener +{ +public: + static PhysicsContactWithBodysListener* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual EventListener* clone(); + +protected: + PhysicsShape* _a; + PhysicsShape* _b; + +protected: + PhysicsContactWithBodysListener(); + virtual ~PhysicsContactWithBodysListener(); }; NS_CC_END diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index ae7f7d07a4..554782bc2d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -1002,4 +1002,29 @@ void PhysicsDemoPump::onTouchEnded(Touch* touch, Event* event) std::string PhysicsDemoPump::title() { return "Pump"; +} + + +void PhysicsDemoOneWayPlatform::onEnter() +{ + PhysicsDemo::onEnter(); + + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + + auto ground = Node::create(); + ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(ground); + + auto platform = Node::create(); + platform->setPhysicsBody(PhysicsBody::createEdgeBox(Size(200, 50))); + platform->setPosition(VisibleRect::center()); + this->addChild(platform); + + this->addChild(makeBall(VisibleRect::center() + Point(0, 50), 5)); +} + +std::string PhysicsDemoOneWayPlatform::title() +{ + return "One Way Platform"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 79932c60a7..7054291dbd 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -134,4 +134,11 @@ private: float _rotationV; }; +class PhysicsDemoOneWayPlatform : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; +}; + #endif From 005d3c012103ddb31a2867251ae24276695825c4 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Thu, 31 Oct 2013 17:28:14 +0800 Subject: [PATCH 017/197] 1. fix if frame event is at the last frame, it may emit event several times 2. add method for removing single data info 3. add test TEST_DIRECT_LOADING 4. add test TEST_FRAME_EVENT 5. add method for getting calculated collider vertex --- .../cocostudio/CCArmatureDataManager.cpp | 113 ++++++++++++++---- .../cocostudio/CCArmatureDataManager.h | 27 +++-- .../cocostudio/CCArmatureDefine.h | 4 + .../cocostudio/CCColliderDetector.cpp | 36 ++++++ .../cocostudio/CCColliderDetector.h | 4 + .../cocostudio/CCDataReaderHelper.cpp | 102 +++++++++------- .../cocostudio/CCDataReaderHelper.h | 5 +- cocos/editor-support/cocostudio/CCTween.cpp | 18 ++- cocos/editor-support/cocostudio/CCTween.h | 19 +-- .../CocoStudioArmatureTest/ArmatureScene.cpp | 80 ++++++++++++- .../CocoStudioArmatureTest/ArmatureScene.h | 21 ++++ 11 files changed, 339 insertions(+), 90 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 13ca184768..ca1945b418 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -65,7 +65,21 @@ ArmatureDataManager::ArmatureDataManager(void) ArmatureDataManager::~ArmatureDataManager(void) { - removeAll(); + if( _animationDatas ) + { + _animationDatas->removeAllObjects(); + } + if( _armarureDatas ) + { + _armarureDatas->removeAllObjects(); + } + + if( _textureDatas ) + { + _textureDatas->removeAllObjects(); + } + + _relativeDatas.clear(); CC_SAFE_DELETE(_animationDatas); CC_SAFE_DELETE(_armarureDatas); @@ -97,10 +111,45 @@ bool ArmatureDataManager::init() return bRet; } -void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armatureData) +void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) +{ + if (RelativeData *data = getRelativeData(configFilePath)) + { + for (std::vector::iterator i = data->armatures.begin(); i != data->armatures.end(); i++) + { + removeArmatureData(i->c_str()); + } + + for (std::vector::iterator i = data->animations.begin(); i != data->animations.end(); i++) + { + removeAnimationData(i->c_str()); + } + + for (std::vector::iterator i = data->textures.begin(); i != data->textures.end(); i++) + { + removeTextureData(i->c_str()); + } + + for (std::vector::iterator i = data->plistFiles.begin(); i != data->plistFiles.end(); i++) + { + SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(i->c_str()); + } + + _relativeDatas.erase(configFilePath); + DataReaderHelper::sharedDataReaderHelper()->removeConfigFile(configFilePath); + } +} + + +void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armatureData, const char *configFilePath) { if(_armarureDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->armatures.push_back(id); + } + _armarureDatas->setObject(armatureData, id); } } @@ -123,10 +172,15 @@ void ArmatureDataManager::removeArmatureData(const char *id) } } -void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animationData) +void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animationData, const char *configFilePath) { if(_animationDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->animations.push_back(id); + } + _animationDatas->setObject(animationData, id); } } @@ -149,10 +203,15 @@ void ArmatureDataManager::removeAnimationData(const char *id) } } -void ArmatureDataManager::addTextureData(const char *id, TextureData *textureData) +void ArmatureDataManager::addTextureData(const char *id, TextureData *textureData, const char *configFilePath) { if(_textureDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->textures.push_back(id); + } + _textureDatas->setObject(textureData, id); } } @@ -179,18 +238,24 @@ void ArmatureDataManager::removeTextureData(const char *id) void ArmatureDataManager::addArmatureFileInfo(const char *configFilePath) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = true; DataReaderHelper::getInstance()->addDataFromFile(configFilePath); } void ArmatureDataManager::addArmatureFileInfoAsync(const char *configFilePath, Object *target, SEL_SCHEDULE selector) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = true; DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char *plistPath, const char *configFilePath) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = false; DataReaderHelper::getInstance()->addDataFromFile(configFilePath); addSpriteFrameFromFile(plistPath, imagePath); @@ -198,36 +263,23 @@ void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char void ArmatureDataManager::addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, Object *target, SEL_SCHEDULE selector) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = false; DataReaderHelper::getInstance()->addDataFromFileAsync(imagePath, plistPath, configFilePath, target, selector); addSpriteFrameFromFile(plistPath, imagePath); } -void ArmatureDataManager::addSpriteFrameFromFile(const char *plistPath, const char *imagePath) +void ArmatureDataManager::addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->plistFiles.push_back(plistPath); + } SpriteFrameCacheHelper::getInstance()->addSpriteFrameFromFile(plistPath, imagePath); } -void ArmatureDataManager::removeAll() -{ - if( _animationDatas ) - { - _animationDatas->removeAllObjects(); - } - if( _armarureDatas ) - { - _armarureDatas->removeAllObjects(); - } - - if( _textureDatas ) - { - _textureDatas->removeAllObjects(); - } - - DataReaderHelper::clear(); -} - bool ArmatureDataManager::isAutoLoadSpriteFile() { return _autoLoadSpriteFile; @@ -246,4 +298,17 @@ Dictionary *ArmatureDataManager::getTextureDatas() const return _textureDatas; } +void CCArmatureDataManager::addRelativeData(const char *configFilePath) +{ + if (_relativeDatas.find(configFilePath) == _relativeDatas.end()) + { + _relativeDatas[configFilePath] = RelativeData(); + } +} + +RelativeData *CCArmatureDataManager::getRelativeData(const char* configFilePath) +{ + return &_relativeDatas[configFilePath]; +} + } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.h b/cocos/editor-support/cocostudio/CCArmatureDataManager.h index 1bd426784d..b73dc99ef9 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.h +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.h @@ -31,6 +31,14 @@ THE SOFTWARE. namespace cocostudio { +struct RelativeData +{ + std::vector plistFiles; + std::vector armatures; + std::vector animations; + std::vector textures; +}; + /** * @brief format and manage armature configuration and armature animation */ @@ -69,7 +77,7 @@ public: * @param id The id of the armature data * @param armatureData ArmatureData * */ - void addArmatureData(const char *id, ArmatureData *armatureData); + void addArmatureData(const char *id, ArmatureData *armatureData, const char *configFilePath = ""); /** * @brief get armature data @@ -89,7 +97,7 @@ public: * @param id the id of the animation data * @return AnimationData * */ - void addAnimationData(const char *id, AnimationData *animationData); + void addAnimationData(const char *id, AnimationData *animationData, const char *configFilePath = ""); /** * @brief get animation data from _animationDatas(Dictionary) @@ -109,7 +117,7 @@ public: * @param id the id of the texture data * @return TextureData * */ - void addTextureData(const char *id, TextureData *textureData); + void addTextureData(const char *id, TextureData *textureData, const char *configFilePath = ""); /** * @brief get texture data @@ -149,13 +157,10 @@ public: /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); + void addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath = ""); + virtual void removeArmatureFileInfo(const char *configFilePath); - /** - * @brief Clear the data in the _armarureDatas and _animationDatas, and set _armarureDatas and _animationDatas to NULL - */ - void removeAll(); /** * @brief Juge whether or not need auto load sprite file @@ -166,6 +171,10 @@ public: cocos2d::Dictionary *getArmatureDatas() const; cocos2d::Dictionary *getAnimationDatas() const; cocos2d::Dictionary *getTextureDatas() const; + +protected: + void addRelativeData(const char* configFilePath); + RelativeData *getRelativeData(const char* configFilePath); private: /** * @brief save amature datas @@ -189,6 +198,8 @@ private: cocos2d::Dictionary *_textureDatas; bool _autoLoadSpriteFile; + + std::map _relativeDatas; }; diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 8b7cb42312..b3fca84e01 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -44,6 +44,10 @@ THE SOFTWARE. #define ENABLE_PHYSICS_CHIPMUNK_DETECT 1 #endif +#ifndef ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 0 +#endif + #define CS_RETURN_IF(cond) if (cond) return #define CS_RETURN_NULL_IF(cond) if (cond) return NULL; diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 341bf503e6..8857832c99 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -44,6 +44,11 @@ ColliderBody::ColliderBody(ContourData *contourData) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + _calculatedVertexList = Array::create(); + CC_SAFE_RETAIN(_calculatedVertexList); +#endif } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT @@ -52,6 +57,11 @@ ColliderBody::ColliderBody(ContourData *contourData) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + _calculatedVertexList = Array::create(); + CC_SAFE_RETAIN(_calculatedVertexList); +#endif } #endif @@ -59,6 +69,10 @@ ColliderBody::~ColliderBody() { CC_SAFE_RELEASE(_contourData); +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SAFE_RELEASE(_calculatedVertexList); +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT CC_SAFE_DELETE(_filter); #endif @@ -125,6 +139,19 @@ void ColliderDetector::addContourData(ContourData *contourData) ColliderBody *colliderBody = new ColliderBody(contourData); _colliderBodyList->addObject(colliderBody); colliderBody->release(); + + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CCArray *calculatedVertexList = colliderBody->getCalculatedVertexList(); + + int num = contourData->vertexList.count(); + for (int i = 0; i < num; i++) + { + ContourVertex2 *newVertex = new ContourVertex2(0, 0); + calculatedVertexList->addObject(newVertex); + newVertex->release(); + } +#endif } void ColliderDetector::addContourDataList(Array *contourDataList) @@ -262,12 +289,21 @@ void ColliderDetector::updateTransform(AffineTransform &t) int num = contourData->vertexList.count(); ContourVertex2 **vs = (ContourVertex2 **)contourData->vertexList.data->arr; +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + ContourVertex2 **cvs = (ContourVertex2 **)colliderBody->getCalculatedVertexList()->data->arr; +#endif + for (int i = 0; i < num; i++) { helpPoint.setPoint( vs[i]->x, vs[i]->y); helpPoint = PointApplyAffineTransform(helpPoint, t); +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + cvs[i]->x = helpPoint.x; + cvs[i]->y = helpPoint.y; +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT if (shape != NULL) { diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 4f6fbeebfe..9e8b7246c6 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -65,6 +65,10 @@ public: } private: ContourData *_contourData; + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SYNTHESIZE_READONLY(CCArray *, _calculatedVertexList, CalculatedVertexList); +#endif }; /* diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 3fb1b69fb8..c64a469c71 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -138,13 +138,14 @@ static const char *CONTENT_SCALE = "content_scale"; namespace cocostudio { -std::vector s_arrConfigFileList; + float s_PositionReadScale = 1; float s_ContentScale = 1; static float s_FlashToolVersion = VERSION_2_0; static float s_CocoStudioVersion = VERSION_COMBINED; -static std::string s_BasefilePath = ""; +std::vector DataReaderHelper::_configFileList; +std::string DataReaderHelper::_basefilePath = ""; DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; @@ -184,7 +185,7 @@ void DataReaderHelper::loadData() _asyncStructQueueMutex.unlock(); } - // generate image info + // generate data info DataInfo *pDataInfo = new DataInfo(); pDataInfo->asyncStruct = pAsyncStruct; @@ -236,14 +237,10 @@ float DataReaderHelper::getPositionReadScale() void DataReaderHelper::purge() { - DataReaderHelper::clear(); + _configFileList.clear(); CC_SAFE_RELEASE_NULL(_dataReaderHelper); } -void DataReaderHelper::clear() -{ - s_arrConfigFileList.clear(); -} DataReaderHelper::DataReaderHelper() : _loadingThread(nullptr) @@ -272,26 +269,26 @@ void DataReaderHelper::addDataFromFile(const char *filePath) /* * Check if file is already added to ArmatureDataManager, if then return. */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) + for(unsigned int i = 0; i < _configFileList.size(); i++) { - if (s_arrConfigFileList[i].compare(filePath) == 0) + if (_configFileList[i].compare(filePath) == 0) { return; } } - s_arrConfigFileList.push_back(filePath); + _configFileList.push_back(filePath); //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); + _basefilePath = filePath; + size_t pos = _basefilePath.find_last_of("/"); if (pos != std::string::npos) { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); + _basefilePath = _basefilePath.substr(0, pos + 1); } else { - s_BasefilePath = ""; + _basefilePath = ""; } @@ -303,13 +300,17 @@ void DataReaderHelper::addDataFromFile(const char *filePath) std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); + DataInfo dataInfo; + dataInfo.filename = filePathStr; + dataInfo.asyncStruct = NULL; + if (str.compare(".xml") == 0) { - DataReaderHelper::addDataFromCache(pFileContent); + DataReaderHelper::addDataFromCache(pFileContent, &dataInfo); } else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) { - DataReaderHelper::addDataFromJsonCache(pFileContent); + DataReaderHelper::addDataFromJsonCache(pFileContent, &dataInfo); } } @@ -318,9 +319,9 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p /* * Check if file is already added to ArmatureDataManager, if then return. */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) + for(unsigned int i = 0; i < _configFileList.size(); i++) { - if (s_arrConfigFileList[i].compare(filePath) == 0) + if (_configFileList[i].compare(filePath) == 0) { if (target && selector) { @@ -336,7 +337,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p return; } } - s_arrConfigFileList.push_back(filePath); + _configFileList.push_back(filePath); //! find the base file path std::string basefilePath = filePath; @@ -474,7 +475,22 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) } +void DataReaderHelper::removeConfigFile(const char *configFile) +{ + std::vector::iterator it = _configFileList.end(); + for (std::vector::iterator i = _configFileList.begin(); i != _configFileList.end(); i++) + { + if (*i == configFile) + { + it = i; + } + } + if (it != _configFileList.end()) + { + _configFileList.erase(it); + } +} @@ -498,13 +514,13 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data { ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); + ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData, dataInfo->filename.c_str()); armatureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -521,13 +537,13 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data while(animationXML) { AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); + ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData, dataInfo->filename.c_str()); animationData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -544,13 +560,13 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data { TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); + ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData, dataInfo->filename.c_str()); textureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1137,7 +1153,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); - if (dataInfo) + if (dataInfo->asyncStruct) { dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); } @@ -1153,13 +1169,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); ArmatureData *armatureData = decodeArmature(*armatureDic, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); armatureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1173,13 +1189,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); AnimationData *animationData = decodeAnimation(*animationDic, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); animationData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1193,13 +1209,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); TextureData *textureData = decodeTexture(*textureDic); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); textureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1207,7 +1223,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } // Auto load sprite file - bool autoLoad = dataInfo == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; + bool autoLoad = dataInfo->asyncStruct == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; if (autoLoad) { length = json.getArrayItemCount(CONFIG_FILE_PATH); @@ -1223,7 +1239,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string filePath = path; filePath = filePath.erase(filePath.find_last_of(".")); - if (dataInfo != NULL) + if (dataInfo->asyncStruct) { dataInfo->configFileQueue.push(filePath); } @@ -1232,7 +1248,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string plistPath = filePath + ".plist"; std::string pngPath = filePath + ".png"; - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((s_BasefilePath + plistPath).c_str(), (s_BasefilePath + pngPath).c_str()); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile((_basefilePath + plistPath).c_str(), (_basefilePath + pngPath).c_str()); } } } @@ -1328,7 +1344,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); - if (dataInfo) + if (dataInfo->asyncStruct) { sdd->skinData.x *= dataInfo->contentScale; sdd->skinData.y *= dataInfo->contentScale; @@ -1362,13 +1378,13 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo const char *plist = json.getItemStringValue(A_PLIST); if(plist != NULL) { - if (dataInfo != NULL) + if (dataInfo->asyncStruct) { static_cast(displayData)->plist = dataInfo->asyncStruct->baseFilePath + plist; } else { - static_cast(displayData)->plist = s_BasefilePath + plist; + static_cast(displayData)->plist = _basefilePath + plist; } } } @@ -1601,7 +1617,7 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; - if (dataInfo) + if (dataInfo->asyncStruct) { node->x *= dataInfo->contentScale; node->y *= dataInfo->contentScale; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index a9159ef39e..c2df44b512 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -73,6 +73,7 @@ protected: AsyncStruct *asyncStruct; std::queue configFileQueue; float contentScale; + std::string filename; } DataInfo; public: @@ -90,7 +91,6 @@ public: static float getPositionReadScale(); static void purge(); - static void clear(); public: /** * @js ctor @@ -107,6 +107,7 @@ public: void addDataAsyncCallBack(float dt); + void removeConfigFile(const char *configFile); public: /** @@ -192,6 +193,8 @@ protected: std::queue *_asyncStructQueue; std::queue *_dataQueue; + static std::string _basefilePath; + static std::vector _configFileList; static DataReaderHelper *_dataReaderHelper; }; diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 5704867a61..77f9a3b2ff 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -61,6 +61,7 @@ Tween::Tween() , _fromIndex(0) , _toIndex(0) , _animation(NULL) + , _passLastFrame(false) { } @@ -408,7 +409,6 @@ float Tween::updateFrameData(float currentPercent) FrameData *from = NULL; FrameData *to = NULL; - bool passLastFrame = false; if (playedTime < frames[0]->frameID) { @@ -416,9 +416,19 @@ float Tween::updateFrameData(float currentPercent) setBetween(from, to); return currentPercent; } - else if(playedTime >= frames[length - 1]->frameID) + + if(playedTime >= frames[length - 1]->frameID) { - passLastFrame = true; + // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. + if (_passLastFrame) + { + return _currentPercent; + } + _passLastFrame = true; + } + else + { + _passLastFrame = false; } @@ -442,7 +452,7 @@ float Tween::updateFrameData(float currentPercent) _animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime); } - if (playedTime == from->frameID || (passLastFrame && _fromIndex == length-1)) + if (playedTime == from->frameID || (_passLastFrame && _fromIndex == length-1)) { break; } diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 5e5bea6356..61213371e8 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -123,25 +123,26 @@ protected: //! A weak reference to the current MovementBoneData. The data is in the data pool CC_SYNTHESIZE(MovementBoneData *, _movementBoneData, MovementBoneData) - FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData - FrameData *_from; //! From frame data, used for calculate between value - FrameData *_to; //! To frame data, used for calculate between value - FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value + FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData + FrameData *_from; //! From frame data, used for calculate between value + FrameData *_to; //! To frame data, used for calculate between value + FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value - Bone *_bone; //! A weak reference to the Bone + Bone *_bone; //! A weak reference to the Bone - CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use + CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use - int _betweenDuration; //! Current key frame will last _betweenDuration frames + int _betweenDuration; //! Current key frame will last _betweenDuration frames int _totalDuration; - int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex - int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex + int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex + int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex ArmatureAnimation *_animation; + bool _passLastFrame; //! If current frame index is more than the last frame's index }; } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 625308dd01..35db4c129b 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -21,6 +21,9 @@ Layer *CreateLayer(int index) case TEST_ASYNCHRONOUS_LOADING: pLayer = new TestAsynchronousLoading(); break; + case TEST_DIRECT_LOADING: + pLayer = new TestDirectLoading(); + break; case TEST_DRAGON_BONES_2_0: pLayer = new TestDragonBones20(); break; @@ -39,6 +42,9 @@ Layer *CreateLayer(int index) case TEST_ANIMATION_EVENT: pLayer = new TestAnimationEvent(); break; + case TEST_FRAME_EVENT: + pLayer = new TestFrameEvent(); + break; case TEST_PARTICLE_DISPLAY: pLayer = new TestParticleDisplay(); break; @@ -244,6 +250,7 @@ void TestAsynchronousLoading::onEnter() ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/hero.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/horse.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/bear.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/HeroAnimation.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); //! load data directly // ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml"); @@ -263,6 +270,12 @@ std::string TestAsynchronousLoading::subtitle() { return "current percent : "; } + +void TestAsynchronousLoading::restartCallback(CCObject* pSender) +{ + ArmatureDataManager::getInstance()->purge(); + ArmatureTestLayer::restartCallback(pSender); +} void TestAsynchronousLoading::dataLoaded(float percent) { LabelTTF *label = (LabelTTF *)getChildByTag(10001); @@ -282,6 +295,26 @@ void TestAsynchronousLoading::dataLoaded(float percent) } +void TestDirectLoading::onEnter() +{ + ArmatureTestLayer::onEnter(); + + // remove sigle resource + ArmatureDataManager::getInstance()->removeArmatureFileInfo("armature/bear.ExportJson"); + + // load resource directly + ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/bear.ExportJson"); + + Armature *armature = Armature::create("bear"); + armature->getAnimation()->playByIndex(0); + armature->setPosition(ccp(VisibleRect::center().x, VisibleRect::center().y)); + addChild(armature); +} +std::string TestDirectLoading::title() +{ + return "Test Direct Loading"; +} + void TestCSWithSkeleton::onEnter() { @@ -535,6 +568,51 @@ void TestAnimationEvent::callback2() +#define FRAME_EVENT_ACTION_TAG 10000 + +void TestFrameEvent::onEnter() +{ + ArmatureTestLayer::onEnter(); + Armature *armature = Armature::create("HeroAnimation"); + armature->getAnimation()->play("attack"); + armature->getAnimation()->setSpeedScale(0.5); + armature->setPosition(Point(VisibleRect::center().x - 50, VisibleRect::center().y -100)); + + /* + * Set armature's frame event callback function + * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + */ + armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestFrameEvent::onFrameEvent)); + + addChild(armature); + + schedule( schedule_selector(TestFrameEvent::checkAction) ); +} +std::string TestFrameEvent::title() +{ + return "Test Frame Event"; +} +void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex) +{ + CCLOG("(%s) emit a frame event (%s) at frame index (%d).", bone->getName().c_str(), evt, currentFrameIndex); + + + if (!this->getActionByTag(FRAME_EVENT_ACTION_TAG) || this->getActionByTag(FRAME_EVENT_ACTION_TAG)->isDone()) + { + this->stopAllActions(); + + ActionInterval *action = ShatteredTiles3D::create(0.2f, Size(16,12), 5, false); + action->setTag(FRAME_EVENT_ACTION_TAG); + this->runAction(action); + } +} +void TestFrameEvent::checkAction(float dt) +{ + if ( this->numberOfRunningActions() == 0 && this->getGrid() != NULL) + this->setGrid(NULL); +} + + void TestParticleDisplay::onEnter() { @@ -926,7 +1004,7 @@ void TestColliderDetector::initWorld() bullet->setCPBody(body); - body = cpBodyNew(INFINITY, INFINITY); + body = cpBodyNew(1.0f, INFINITY); cpSpaceAddBody(space, body); armature2->setBody(body); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index f5a7787168..f8429fc595 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -27,12 +27,14 @@ public: enum { TEST_ASYNCHRONOUS_LOADING = 0, + TEST_DIRECT_LOADING, TEST_COCOSTUDIO_WITH_SKELETON, TEST_DRAGON_BONES_2_0, TEST_PERFORMANCE, TEST_PERFORMANCE_BATCHNODE, TEST_CHANGE_ZORDER, TEST_ANIMATION_EVENT, + TEST_FRAME_EVENT, TEST_PARTICLE_DISPLAY, TEST_USE_DIFFERENT_PICTURE, TEST_BCOLLIDER_DETECTOR, @@ -72,10 +74,18 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); + virtual void restartCallback(CCObject* pSender); void dataLoaded(float percent); }; +class TestDirectLoading : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual std::string title(); +}; + class TestCSWithSkeleton : public ArmatureTestLayer { virtual void onEnter(); @@ -147,6 +157,17 @@ public: cocostudio::Armature *armature; }; + +class TestFrameEvent : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual std::string title(); + void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); + void checkAction(float dt); +}; + + class TestUseMutiplePicture : public ArmatureTestLayer { virtual void onEnter(); From 4eaaaddc3405cef7d3274a8af7b530abd1b52193 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Thu, 31 Oct 2013 17:29:03 +0800 Subject: [PATCH 018/197] upload resource --- .../Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id | 1 + .../Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id | 1 + 2 files changed, 2 insertions(+) create mode 100644 samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id create mode 100644 samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id new file mode 100644 index 0000000000..43ba518703 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id @@ -0,0 +1 @@ +d73c3774258671e491d1579a4991bba7c4b4c24c \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id new file mode 100644 index 0000000000..f92a9b8f72 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id @@ -0,0 +1 @@ +ac19b290421fc75a284f603891442ab9796c132a \ No newline at end of file From 2efef34144afd5435e0ad5070e04a6e2ef95986c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 31 Oct 2013 18:18:02 +0800 Subject: [PATCH 019/197] issue #2771: fix vs compile errors --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/Android.mk | 20 +-- cocos/2d/Makefile | 20 +-- cocos/2d/cocos2d.vcxproj | 44 +++--- cocos/2d/cocos2d.vcxproj.filters | 132 +++++++++--------- cocos/physics/CCPhysicsBody.cpp | 22 +-- cocos/physics/CCPhysicsContact.cpp | 8 +- cocos/physics/CCPhysicsJoint.cpp | 16 +-- cocos/physics/CCPhysicsShape.cpp | 10 +- cocos/physics/CCPhysicsWorld.cpp | 22 +-- ...dyInfo.cpp => CCPhysicsBodyInfo_box2d.cpp} | 2 +- ...csBodyInfo.h => CCPhysicsBodyInfo_box2d.h} | 2 + ...nfo.cpp => CCPhysicsContactInfo_box2d.cpp} | 2 +- ...actInfo.h => CCPhysicsContactInfo_box2d.h} | 1 + ...hysicsHelper.h => CCPhysicsHelper_box2d.h} | 1 - ...tInfo.cpp => CCPhysicsJointInfo_box2d.cpp} | 2 +- ...JointInfo.h => CCPhysicsJointInfo_box2d.h} | 1 + ...eInfo.cpp => CCPhysicsShapeInfo_box2d.cpp} | 2 +- ...ShapeInfo.h => CCPhysicsShapeInfo_box2d.h} | 1 + ...dInfo.cpp => CCPhysicsWorldInfo_box2d.cpp} | 2 +- ...WorldInfo.h => CCPhysicsWorldInfo_box2d.h} | 1 + ...nfo.cpp => CCPhysicsBodyInfo_chipmunk.cpp} | 2 +- ...odyInfo.h => CCPhysicsBodyInfo_chipmunk.h} | 5 +- ....cpp => CCPhysicsContactInfo_chipmunk.cpp} | 2 +- ...Info.h => CCPhysicsContactInfo_chipmunk.h} | 5 +- ...icsHelper.h => CCPhysicsHelper_chipmunk.h} | 6 +- ...fo.cpp => CCPhysicsJointInfo_chipmunk.cpp} | 2 +- ...ntInfo.h => CCPhysicsJointInfo_chipmunk.h} | 5 +- ...fo.cpp => CCPhysicsShapeInfo_chipmunk.cpp} | 2 +- ...peInfo.h => CCPhysicsShapeInfo_chipmunk.h} | 6 +- ...fo.cpp => CCPhysicsWorldInfo_chipmunk.cpp} | 2 +- ...ldInfo.h => CCPhysicsWorldInfo_chipmunk.h} | 5 +- 32 files changed, 182 insertions(+), 173 deletions(-) rename cocos/physics/box2d/{CCPhysicsBodyInfo.cpp => CCPhysicsBodyInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsBodyInfo.h => CCPhysicsBodyInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsContactInfo.cpp => CCPhysicsContactInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsContactInfo.h => CCPhysicsContactInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsHelper.h => CCPhysicsHelper_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsJointInfo.cpp => CCPhysicsJointInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsJointInfo.h => CCPhysicsJointInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsShapeInfo.cpp => CCPhysicsShapeInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsShapeInfo.h => CCPhysicsShapeInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsWorldInfo.cpp => CCPhysicsWorldInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsWorldInfo.h => CCPhysicsWorldInfo_box2d.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsBodyInfo.cpp => CCPhysicsBodyInfo_chipmunk.cpp} (97%) rename cocos/physics/chipmunk/{CCPhysicsBodyInfo.h => CCPhysicsBodyInfo_chipmunk.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsContactInfo.cpp => CCPhysicsContactInfo_chipmunk.cpp} (97%) rename cocos/physics/chipmunk/{CCPhysicsContactInfo.h => CCPhysicsContactInfo_chipmunk.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsHelper.h => CCPhysicsHelper_chipmunk.h} (100%) rename cocos/physics/chipmunk/{CCPhysicsJointInfo.cpp => CCPhysicsJointInfo_chipmunk.cpp} (98%) rename cocos/physics/chipmunk/{CCPhysicsJointInfo.h => CCPhysicsJointInfo_chipmunk.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsShapeInfo.cpp => CCPhysicsShapeInfo_chipmunk.cpp} (98%) rename cocos/physics/chipmunk/{CCPhysicsShapeInfo.h => CCPhysicsShapeInfo_chipmunk.h} (100%) rename cocos/physics/chipmunk/{CCPhysicsWorldInfo.cpp => CCPhysicsWorldInfo_chipmunk.cpp} (97%) rename cocos/physics/chipmunk/{CCPhysicsWorldInfo.h => CCPhysicsWorldInfo_chipmunk.h} (99%) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 17e0cee1da..3084c15190 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b695026fc3d856d540590ff09112696f66379c22 \ No newline at end of file +a9f1e2dab211d674c7a17bb7c268d613af6d5797 \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 6a25764f44..52009a4638 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -147,16 +147,16 @@ platform/CCThread.cpp \ ../physics/CCPhysicsJoint.cpp \ ../physics/CCPhysicsShape.cpp \ ../physics/CCPhysicsWorld.cpp \ -../physics/box2d/CCPhysicsBodyInfo.cpp \ -../physics/box2d/CCPhysicsContactInfo.cpp \ -../physics/box2d/CCPhysicsJointInfo.cpp \ -../physics/box2d/CCPhysicsShapeInfo.cpp \ -../physics/box2d/CCPhysicsWorldInfo.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo.cpp \ -../physics/chipmunk/CCPhysicsContactInfo.cpp \ -../physics/chipmunk/CCPhysicsJointInfo.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ +../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ +../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ +../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ +../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ +../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../../external/tinyxml2/tinyxml2.cpp \ ../../external/unzip/ioapi.cpp \ ../../external/unzip/unzip.cpp diff --git a/cocos/2d/Makefile b/cocos/2d/Makefile index d88604b130..d84d5ed6d1 100644 --- a/cocos/2d/Makefile +++ b/cocos/2d/Makefile @@ -73,16 +73,16 @@ CCParticleExamples.cpp \ CCParticleSystem.cpp \ CCParticleSystemQuad.cpp \ CCParticleBatchNode.cpp \ -../physics/box2d/CCPhysicsContactInfo.cpp \ -../physics/box2d/CCPhysicsJointInfo.cpp \ -../physics/box2d/CCPhysicsShapeInfo.cpp \ -../physics/box2d/CCPhysicsBodyInfo.cpp \ -../physics/box2d/CCPhysicsWorldInfo.cpp \ -../physics/chipmunk/CCPhysicsContactInfo.cpp \ -../physics/chipmunk/CCPhysicsJointInfo.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ +../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ +../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ +../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ +../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ +../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../physics/CCPhysicsBody.cpp \ ../physics/CCPhysicsContact.cpp \ ../physics/CCPhysicsShape.cpp \ diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index a7f030bb9f..21150abf4a 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -192,21 +192,21 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - + + + + + - - - - - + + + + + @@ -359,24 +359,24 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - - + + + + + + - - - - - - + + + + + + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 2028e708c8..29fad13db6 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -129,36 +129,6 @@ physics - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - base_nodes @@ -572,6 +542,36 @@ support + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + @@ -592,42 +592,6 @@ physics - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - base_nodes @@ -1152,5 +1116,41 @@ base + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + \ No newline at end of file diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index a4393c4435..70bfe275b8 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -25,6 +25,7 @@ #ifdef CC_USE_PHYSICS #include +#include #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" @@ -36,17 +37,16 @@ #include "CCPhysicsJoint.h" #include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "box2d/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" - -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" +#include "box2d/CCPhysicsWorldInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 7c3c609ebc..6f08fc6b24 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -30,10 +30,10 @@ #include "Box2D.h" #endif -#include "chipmunk/CCPhysicsContactInfo.h" -#include "box2d/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsContactInfo_chipmunk.h" +#include "box2d/CCPhysicsContactInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 1268ac2460..e35b8d241c 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -33,14 +33,14 @@ #include "CCPhysicsBody.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" #include "CCNode.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 6b166da351..bb17c54501 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -34,11 +34,11 @@ #include "CCPhysicsBody.h" #include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 459261f896..a8d3d962c7 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -37,17 +37,17 @@ #include "CCPhysicsJoint.h" #include "CCPhysicsContact.h" -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "box2d/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsContactInfo.h" -#include "box2d/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" +#include "box2d/CCPhysicsWorldInfo_box2d.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsContactInfo_chipmunk.h" +#include "box2d/CCPhysicsContactInfo_box2d.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" #include "CCDrawNode.h" #include "CCArray.h" diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsBodyInfo.cpp rename to cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp index bfa20b616a..059619a264 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsBodyInfo.h" +#include "CCPhysicsBodyInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsBodyInfo.h rename to cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h index 5c89ac5f19..ed5135bf36 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h @@ -27,7 +27,9 @@ #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ + #include "CCPlatformMacros.h" + NS_CC_BEGIN class PhysicsBodyInfo diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.cpp b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsContactInfo.cpp rename to cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp index 41eaa4f831..4edb6ce3a2 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsContactInfo.h" +#include "CCPhysicsContactInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsContactInfo.h rename to cocos/physics/box2d/CCPhysicsContactInfo_box2d.h index f1e41ef572..c8d4a262d5 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsHelper.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsHelper.h rename to cocos/physics/box2d/CCPhysicsHelper_box2d.h index 61dd2b6e4c..01f156628d 100644 --- a/cocos/physics/box2d/CCPhysicsHelper.h +++ b/cocos/physics/box2d/CCPhysicsHelper_box2d.h @@ -27,7 +27,6 @@ #ifndef __CCPHYSICS_HELPER_H__ #define __CCPHYSICS_HELPER_H__ - #include "CCPlatformMacros.h" #include "CCGeometry.h" diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.cpp b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsJointInfo.cpp rename to cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp index 753ba41534..a0b6363cde 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsJointInfo.h" +#include "CCPhysicsJointInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsJointInfo.h rename to cocos/physics/box2d/CCPhysicsJointInfo_box2d.h index a60ecdb97e..c8223b6f8c 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsShapeInfo.cpp rename to cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp index a89ba7dae7..fc3aa61491 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsShapeInfo.h" +#include "CCPhysicsShapeInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsShapeInfo.h rename to cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h index 8608f0bad1..cd1fc6abcc 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_SHAPE_INFO_H__ #define __CCPHYSICS_SHAPE_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsWorldInfo.cpp rename to cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp index 0de6c00d82..fbe3be06d4 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsWorldInfo.h" +#include "CCPhysicsWorldInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsWorldInfo.h rename to cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index 662fa19843..9df3ec46cd 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp similarity index 97% rename from cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 5fd8ceb171..42ce5cc7ec 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsBodyInfo.h" +#include "CCPhysicsBodyInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsBodyInfo.h rename to cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index 54e4313b38..19e43c23fb 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp similarity index 97% rename from cocos/physics/chipmunk/CCPhysicsContactInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index 53b4f29b14..283a4998ab 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsContactInfo.h" +#include "CCPhysicsContactInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsContactInfo.h rename to cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index fb455cdfc5..7dc6561fec 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h similarity index 100% rename from cocos/physics/chipmunk/CCPhysicsHelper.h rename to cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index 8ad6fa29bd..bf6f6d14db 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifndef __CCPHYSICS_HELPER_H__ +#define __CCPHYSICS_HELPER_H__ + #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp similarity index 98% rename from cocos/physics/chipmunk/CCPhysicsJointInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index b3fc376710..82053ce4b1 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsJointInfo.h" +#include "CCPhysicsJointInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsJointInfo.h rename to cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 5033e4aaba..8116c48eae 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp similarity index 98% rename from cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index 07e5c2f932..74abfc75f1 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsShapeInfo.h" +#include "CCPhysicsShapeInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h similarity index 100% rename from cocos/physics/chipmunk/CCPhysicsShapeInfo.h rename to cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 9229ba6d7f..83be655b02 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifndef __CCPHYSICS_SHAPE_INFO_H__ +#define __CCPHYSICS_SHAPE_INFO_H__ + #include #include #include "chipmunk.h" diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp similarity index 97% rename from cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index 57f601ead7..f58eebadf2 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsWorldInfo.h" +#include "CCPhysicsWorldInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsWorldInfo.h rename to cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 8c60cde415..158f074c77 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN From a9054ba14abd41c836d3f8de177ede612e2d0fb7 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Fri, 1 Nov 2013 14:36:44 +0800 Subject: [PATCH 020/197] 1.add method to set collider filter --- .../editor-support/cocostudio/CCArmature.cpp | 10 ++ cocos/editor-support/cocostudio/CCArmature.h | 2 + cocos/editor-support/cocostudio/CCBone.cpp | 27 +++++ cocos/editor-support/cocostudio/CCBone.h | 2 + .../cocostudio/CCColliderDetector.cpp | 98 +++++++++++++++---- .../cocostudio/CCColliderDetector.h | 47 +++++++-- .../CocoStudioArmatureTest/ArmatureScene.cpp | 8 +- 7 files changed, 161 insertions(+), 33 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index ac04de1af5..baa56ddfb7 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -728,6 +728,16 @@ Bone *Armature::getParentBone() return _parentBone; } +void CCArmature::setColliderFilter(ColliderFilter *filter) +{ + DictElement *element = NULL; + CCDICT_FOREACH(_boneDic, element) + { + Bone *bone = static_cast(element->getObject()); + bone->setColliderFilter(filter); + } +} + #if ENABLE_PHYSICS_BOX2D_DETECT b2Body *Armature::getBody() { diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 15abe96079..bf11841f7e 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -175,6 +175,8 @@ public: virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + virtual void setColliderFilter(ColliderFilter *filter); + #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 804ea5d65a..3132acec79 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -441,4 +441,31 @@ Array *Bone::getColliderBodyList() } + +void Bone::setColliderFilter(ColliderFilter *filter) +{ + Array *array = _displayManager->getDecorativeDisplayList(); + Object *object = NULL; + CCARRAY_FOREACH(array, object) + { + DecorativeDisplay *decoDisplay = static_cast(object); + if (ColliderDetector *detector = decoDisplay->getColliderDetector()) + { + detector->setColliderFilter(filter); + } + } +} +ColliderFilter *Bone::getColliderFilter() +{ + if (DecorativeDisplay *decoDisplay = _displayManager->getCurrentDecorativeDisplay()) + { + if (ColliderDetector *detector = decoDisplay->getColliderDetector()) + { + return detector->getColliderFilter(); + } + } + return NULL; +} + + } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 1a1d3c26d6..6edd3fe8cb 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -159,6 +159,8 @@ public: */ virtual cocos2d::Array *getColliderBodyList(); + virtual void setColliderFilter(ColliderFilter *filter); + virtual ColliderFilter *getColliderFilter(); public: /* * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 8857832c99..cceb1a9b72 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -37,13 +37,44 @@ using namespace cocos2d; namespace cocostudio { +#if ENABLE_PHYSICS_BOX2D_DETECT +ColliderFilter::ColliderFilter(unsigned short categoryBits, unsigned short maskBits, signed short groupIndex) + : _categoryBits(categoryBits) + , _maskBits(maskBits) + , _groupIndex(groupIndex) +{ +} + +void ColliderFilter::updateShape(b2Fixture *fixture) +{ + b2Filter filter; + filter.categoryBits = _categoryBits; + filter.groupIndex = _groupIndex; + filter.maskBits = _maskBits; + + fixture->SetFilterData(filter); +} + +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT +ColliderFilter::ColliderFilter(cpCollisionType collisionType, cpGroup group) + : _collisionType(collisionType) + , _group(group) +{ +} +void ColliderFilter::updateShape(cpShape *shape) +{ + shape->collision_type = _collisionType; + shape->group = _group; +} +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT ColliderBody::ColliderBody(ContourData *contourData) : _fixture(NULL) - , _filter(NULL) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + _filter = new ColliderFilter(); #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX _calculatedVertexList = Array::create(); @@ -57,6 +88,7 @@ ColliderBody::ColliderBody(ContourData *contourData) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + _filter = new ColliderFilter(); #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX _calculatedVertexList = Array::create(); @@ -68,14 +100,20 @@ ColliderBody::ColliderBody(ContourData *contourData) ColliderBody::~ColliderBody() { CC_SAFE_RELEASE(_contourData); + CC_SAFE_DELETE(_filter); #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX CC_SAFE_RELEASE(_calculatedVertexList); #endif +} -#if ENABLE_PHYSICS_BOX2D_DETECT - CC_SAFE_DELETE(_filter); -#endif +void ColliderBody::setColliderFilter(ColliderFilter *filter) +{ + *_filter = *filter; +} +ColliderFilter *ColliderBody::getColliderFilter() +{ + return _filter; } @@ -106,6 +144,7 @@ ColliderDetector *ColliderDetector::create(Bone *bone) ColliderDetector::ColliderDetector() : _colliderBodyList(NULL) + , _filter(NULL) , _active(false) { _body = NULL; @@ -115,6 +154,7 @@ ColliderDetector::~ColliderDetector() { _colliderBodyList->removeAllObjects(); CC_SAFE_DELETE(_colliderBodyList); + CC_SAFE_DELETE(_filter); } bool ColliderDetector::init() @@ -123,6 +163,8 @@ bool ColliderDetector::init() CCASSERT(_colliderBodyList, "create _colliderBodyList failed!"); _colliderBodyList->retain(); + _filter = new ColliderFilter(); + return true; } @@ -206,9 +248,6 @@ void ColliderDetector::setActive(bool active) ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); - b2Filter *filter = colliderBody->getB2Filter(); - *filter = fixture->GetFilterData(); - _body->DestroyFixture(fixture); colliderBody->setB2Fixture(NULL); } @@ -256,6 +295,34 @@ Array *ColliderDetector::getColliderBodyList() return _colliderBodyList; } +void ColliderDetector::setColliderFilter(ColliderFilter *filter) +{ + *_filter = *filter; + + Object *object = NULL; + CCARRAY_FOREACH(_colliderBodyList, object) + { + ColliderBody *colliderBody = (ColliderBody *)object; + colliderBody->setColliderFilter(filter); + +#if ENABLE_PHYSICS_BOX2D_DETECT + if (colliderBody->getB2Fixture()) + { + colliderBody->getColliderFilter()->updateShape(colliderBody->getB2Fixture()); + } +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + if (colliderBody->getShape()) + { + colliderBody->getColliderFilter()->updateShape(colliderBody->getShape()); + } +#endif + } +} +ColliderFilter *ColliderDetector::getColliderFilter() +{ + return _filter; +} + Point helpPoint; @@ -378,15 +445,7 @@ void ColliderDetector::setBody(b2Body *pBody) } colliderBody->setB2Fixture(fixture); - if (colliderBody->getB2Filter() == NULL) - { - b2Filter *filter = new b2Filter; - colliderBody->setB2Filter(filter); - } - else - { - fixture->SetFilterData(*colliderBody->getB2Filter()); - } + colliderBody->getColliderFilter()->updateShape(fixture); } } @@ -420,9 +479,14 @@ void ColliderDetector::setBody(cpBody *pBody) shape->sensor = true; shape->data = _bone; - cpSpaceAddShape(_body->space_private, shape); + + if (_active) + { + cpSpaceAddShape(_body->space_private, shape); + } colliderBody->setShape(shape); + colliderBody->getColliderFilter()->updateShape(shape); delete []verts; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 9e8b7246c6..e2da724c80 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -33,24 +33,48 @@ THE SOFTWARE. #endif +#if ENABLE_PHYSICS_CHIPMUNK_DETECT +#include "chipmunk.h" +struct cpBody; +struct cpShape; +#elif ENABLE_PHYSICS_BOX2D_DETECT class b2Body; class b2Fixture; struct b2Filter; - -struct cpBody; -struct cpShape; +#endif namespace cocostudio { class Bone; + +class ColliderFilter +{ +public: + ~ColliderFilter() { } +#if ENABLE_PHYSICS_BOX2D_DETECT +public: + ColliderFilter(unsigned short categoryBits = 0x0001, unsigned short maskBits = 0xFFFF, signed short groupIndex = 0); + void updateShape(b2Fixture *fixture); +protected: + CC_SYNTHESIZE(unsigned short, _categoryBits, CategoryBits); + CC_SYNTHESIZE(unsigned short, _maskBits, MaskBits); + CC_SYNTHESIZE(signed short, _groupIndex, GroupIndex); +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT +public: + ColliderFilter(cpCollisionType collisionType = 0, cpGroup group = 0); + void updateShape(cpShape *shape); +protected: + CC_SYNTHESIZE(cpCollisionType, _collisionType, CollisionType); + CC_SYNTHESIZE(cpGroup, _group, Group); +#endif +}; + class ColliderBody : public cocos2d::Object { public: #if ENABLE_PHYSICS_BOX2D_DETECT CC_SYNTHESIZE(b2Fixture *, _fixture, B2Fixture) - CC_SYNTHESIZE(b2Filter *, _filter, B2Filter) - #elif ENABLE_PHYSICS_CHIPMUNK_DETECT CC_SYNTHESIZE(cpShape *, _shape, Shape) #endif @@ -59,12 +83,13 @@ public: ColliderBody(ContourData *contourData); ~ColliderBody(); - inline ContourData *getContourData() - { - return _contourData; - } + inline ContourData *getContourData() { return _contourData; } + + void setColliderFilter(ColliderFilter *filter); + ColliderFilter *getColliderFilter(); private: ContourData *_contourData; + ColliderFilter *_filter; #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX CC_SYNTHESIZE_READONLY(CCArray *, _calculatedVertexList, CalculatedVertexList); @@ -106,8 +131,12 @@ public: cocos2d::Array *getColliderBodyList(); + virtual void setColliderFilter(ColliderFilter *filter); + virtual ColliderFilter *getColliderFilter(); protected: cocos2d::Array *_colliderBodyList; + ColliderFilter *_filter; + CC_SYNTHESIZE(Bone *, _bone, Bone); #if ENABLE_PHYSICS_BOX2D_DETECT diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 35db4c129b..a6dfd04092 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1008,13 +1008,7 @@ void TestColliderDetector::initWorld() cpSpaceAddBody(space, body); armature2->setBody(body); - shape = armature2->getShapeList(); - while(shape) - { - cpShape *next = shape->next_private; - shape->collision_type = eEnemyTag; - shape = next; - } + armature2->setColliderFilter(&ColliderFilter(eEnemyTag)); cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); } From b2951b70ff7ffd56a865a376db8c23e2bc563f4f Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 1 Nov 2013 14:50:06 +0800 Subject: [PATCH 021/197] issue #2771: enhance Listener use EventListener mechanism --- cocos/2d/CCScene.cpp | 3 +- cocos/base/CCObject.h | 1 + cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsContact.cpp | 268 +++++++++++++++--- cocos/physics/CCPhysicsContact.h | 104 +++++-- cocos/physics/CCPhysicsWorld.cpp | 89 ++---- cocos/physics/CCPhysicsWorld.h | 15 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 25 +- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 2 + 9 files changed, 373 insertions(+), 136 deletions(-) diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 5d0de936de..3f05e43c83 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -102,8 +102,7 @@ bool Scene::initWithPhysics() Director * pDirector; CC_BREAK_IF( ! (pDirector = Director::getInstance()) ); this->setContentSize(pDirector->getWinSize()); - CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create())); - _physicsWorld->setScene(this); + CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create(*this))); this->scheduleUpdate(); // success diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index 3c3e6c5321..dc1a6adfd2 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -207,6 +207,7 @@ typedef int (Object::*SEL_Compare)(Object*); #define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__) #define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__) #define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__) +#define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ##__VA_ARGS__) // end of base_nodes group /// @} diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index a82b7dc1d4..6073207dbd 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -44,7 +44,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.01f, 0.5f, 0.5f); +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); /** * A body affect by physics. diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 6f08fc6b24..744302cb46 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -30,22 +30,30 @@ #include "Box2D.h" #endif +#include "CCPhysicsBody.h" + #include "chipmunk/CCPhysicsContactInfo_chipmunk.h" #include "box2d/CCPhysicsContactInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" #include "box2d/CCPhysicsHelper_box2d.h" +#include "CCEventCustom.h" + NS_CC_BEGIN PhysicsContact::PhysicsContact() -: _shapeA(nullptr) +: Event(Event::Type::CUSTOM) +, _world(nullptr) +, _shapeA(nullptr) , _shapeB(nullptr) +, _eventCode(EventCode::NONE) , _info(nullptr) , _notify(true) , _begin(false) , _data(nullptr) , _contactInfo(nullptr) , _contactData(nullptr) +, _result(true) { } @@ -172,25 +180,106 @@ Point PhysicsContactPostSolve::getSurfaceVelocity() return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); } -PhysicsContactListener::PhysicsContactListener() +EventListenerPhysicsContact::EventListenerPhysicsContact() : onContactBegin(nullptr) , onContactPreSolve(nullptr) , onContactPostSolve(nullptr) -, onContactEnd(nullptr) +, onContactSeperate(nullptr) +{ +} + +bool EventListenerPhysicsContact::init() +{ + auto func = [this](EventCustom* event) -> void + { + return onEvent(event); + }; + + return EventListenerCustom::init(std::hash()(PHYSICSCONTACT_EVENT_NAME), func); +} + +void EventListenerPhysicsContact::onEvent(EventCustom* event) +{ + PhysicsContact& contact = *(PhysicsContact*)(event->getUserData()); + + switch (contact.getEventCode()) + { + case PhysicsContact::EventCode::BEGIN: + { + bool ret = true; + + if (onContactBegin != nullptr + && contact.getNotify() + && test(contact.getShapeA(), contact.getShapeB())) + { + contact._begin = true; + contact.generateContactData(); + + // the mask has high priority than _listener->onContactBegin. + // so if the mask test is false, the two bodies won't have collision. + if (ret) + { + ret = onContactBegin(event, contact); + }else + { + onContactBegin(event, contact); + } + } + + contact.setResult(ret); + break; + } + case PhysicsContact::EventCode::PRESOLVE: + { + bool ret = true; + + if (onContactPreSolve != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); + contact._begin = false; + contact.generateContactData(); + + ret = onContactPreSolve(event, contact, solve); + } + + contact.setResult(ret); + break; + } + case PhysicsContact::EventCode::POSTSOLVE: + { + if (onContactPreSolve != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + PhysicsContactPostSolve solve(contact._contactInfo); + onContactPostSolve(event, contact, solve); + } + break; + } + case PhysicsContact::EventCode::SEPERATE: + { + if (onContactSeperate != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + onContactSeperate(event, contact); + } + break; + } + default: + break; + } +} + +EventListenerPhysicsContact::~EventListenerPhysicsContact() { } -PhysicsContactListener::~PhysicsContactListener() +EventListenerPhysicsContact* EventListenerPhysicsContact::create() { + EventListenerPhysicsContact* obj = new EventListenerPhysicsContact(); -} - -PhysicsContactListener* PhysicsContactListener::create() -{ - PhysicsContactListener* obj = new PhysicsContactListener(); - - if (obj != nullptr) + if (obj != nullptr && obj->init()) { obj->autorelease(); return obj; @@ -200,17 +289,17 @@ PhysicsContactListener* PhysicsContactListener::create() return nullptr; } -bool PhysicsContactListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +bool EventListenerPhysicsContact::test(PhysicsShape* shapeA, PhysicsShape* shapeB) { CC_UNUSED_PARAM(shapeA); CC_UNUSED_PARAM(shapeB); return true; } -bool PhysicsContactListener::checkAvailable() +bool EventListenerPhysicsContact::checkAvailable() { if (onContactBegin == nullptr && onContactPreSolve == nullptr - && onContactPostSolve == nullptr && onContactEnd == nullptr) + && onContactPostSolve == nullptr && onContactSeperate == nullptr) { CCASSERT(false, "Invalid PhysicsContactListener."); return false; @@ -219,16 +308,16 @@ bool PhysicsContactListener::checkAvailable() return true; } -EventListener* PhysicsContactListener::clone() +EventListenerPhysicsContact* EventListenerPhysicsContact::clone() { - PhysicsContactListener* obj = PhysicsContactListener::create(); + EventListenerPhysicsContact* obj = EventListenerPhysicsContact::create(); if (obj != nullptr) { obj->onContactBegin = onContactBegin; obj->onContactPreSolve = onContactPreSolve; obj->onContactPostSolve = onContactPostSolve; - obj->onContactEnd = onContactEnd; + obj->onContactSeperate = onContactSeperate; return obj; } @@ -237,14 +326,79 @@ EventListener* PhysicsContactListener::clone() return nullptr; } - - - -PhysicsContactWithBodysListener* PhysicsContactWithBodysListener::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +EventListenerPhysicsContactWithBodies* EventListenerPhysicsContactWithBodies::create(PhysicsBody* bodyA, PhysicsBody* bodyB) { - PhysicsContactWithBodysListener* obj = new PhysicsContactWithBodysListener(); + EventListenerPhysicsContactWithBodies* obj = new EventListenerPhysicsContactWithBodies(); + + if (obj != nullptr && obj->init()) + { + obj->_a = bodyA; + obj->_b = bodyB; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithBodies::EventListenerPhysicsContactWithBodies() +: _a(nullptr) +, _b(nullptr) +{ + +} + +EventListenerPhysicsContactWithBodies::~EventListenerPhysicsContactWithBodies() +{ + +} + + +bool EventListenerPhysicsContactWithBodies::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if ((shapeA->getBody() == _a && shapeB->getBody() == _b) + || (shapeA->getBody() == _b && shapeB->getBody() == _a)) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithBodies* EventListenerPhysicsContactWithBodies::clone() +{ + EventListenerPhysicsContactWithBodies* obj = EventListenerPhysicsContactWithBodies::create(_a, _b); if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithShapes::EventListenerPhysicsContactWithShapes() +: _a(nullptr) +, _b(nullptr) +{ +} + +EventListenerPhysicsContactWithShapes::~EventListenerPhysicsContactWithShapes() +{ +} + +EventListenerPhysicsContactWithShapes* EventListenerPhysicsContactWithShapes::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + EventListenerPhysicsContactWithShapes* obj = new EventListenerPhysicsContactWithShapes(); + + if (obj != nullptr && obj->init()) { obj->_a = shapeA; obj->_b = shapeB; @@ -256,17 +410,7 @@ PhysicsContactWithBodysListener* PhysicsContactWithBodysListener::create(Physics return nullptr; } -PhysicsContactWithBodysListener::PhysicsContactWithBodysListener() -{ - -} - -PhysicsContactWithBodysListener::~PhysicsContactWithBodysListener() -{ - -} - -bool PhysicsContactWithBodysListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +bool EventListenerPhysicsContactWithShapes::test(PhysicsShape* shapeA, PhysicsShape* shapeB) { if ((shapeA == _a && shapeB == _b) || (shapeA == _b && shapeB == _a)) @@ -277,16 +421,68 @@ bool PhysicsContactWithBodysListener::test(PhysicsShape* shapeA, PhysicsShape* s return false; } -EventListener* PhysicsContactWithBodysListener::clone() +EventListenerPhysicsContactWithShapes* EventListenerPhysicsContactWithShapes::clone() { - PhysicsContactWithBodysListener* obj = PhysicsContactWithBodysListener::create(_a, _b); + EventListenerPhysicsContactWithShapes* obj = EventListenerPhysicsContactWithShapes::create(_a, _b); if (obj != nullptr) { obj->onContactBegin = onContactBegin; obj->onContactPreSolve = onContactPreSolve; obj->onContactPostSolve = onContactPostSolve; - obj->onContactEnd = onContactEnd; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithGroup::EventListenerPhysicsContactWithGroup() +: _group(CP_NO_GROUP) +{ +} + +EventListenerPhysicsContactWithGroup::~EventListenerPhysicsContactWithGroup() +{ +} + +EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::create(int group) +{ + EventListenerPhysicsContactWithGroup* obj = new EventListenerPhysicsContactWithGroup(); + + if (obj != nullptr && obj->init()) + { + obj->_group = group; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool EventListenerPhysicsContactWithGroup::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if (shapeA->getGroup() == _group || shapeB->getGroup() == _group) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::clone() +{ + EventListenerPhysicsContactWithGroup* obj = EventListenerPhysicsContactWithGroup::create(_group); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; return obj; } diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 82a47a8c23..a4b0454e37 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -30,11 +30,13 @@ #include "CCObject.h" #include "CCGeometry.h" -#include "CCEventListener.h" +#include "CCEventListenerCustom.h" +#include "CCEvent.h" NS_CC_BEGIN class PhysicsShape; +class PhysicsBody; class PhysicsWorld; class PhysicsContactInfo; @@ -54,9 +56,19 @@ typedef struct PhysicsContactData /** * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. */ -class PhysicsContact +class PhysicsContact : Event { public: + + enum class EventCode + { + NONE, + BEGIN, + PRESOLVE, + POSTSOLVE, + SEPERATE + }; + /* * @brief get contact shape A. */ @@ -75,12 +87,19 @@ public: */ inline void setData(void* data) { _data = data; } + EventCode getEventCode() { return _eventCode; }; + private: static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); bool init(PhysicsShape* a, PhysicsShape* b); + void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; inline bool getNotify() { return _notify; } inline void setNotify(bool notify) { _notify = notify; } + inline PhysicsWorld* getWorld() { return _world; } + inline void setWorld(PhysicsWorld* world) { _world = world; } + inline void setResult(bool result) { _result = result; } + inline bool resetResult() { bool ret = _result; _result = true; return ret; } void generateContactData(); @@ -89,18 +108,22 @@ private: ~PhysicsContact(); private: + PhysicsWorld* _world; PhysicsShape* _shapeA; PhysicsShape* _shapeB; + EventCode _eventCode; PhysicsContactInfo* _info; bool _notify; bool _begin; + bool _result; void* _data; void* _contactInfo; PhysicsContactData* _contactData; - friend class PhysicsWorld; + friend class EventListenerPhysicsContact; friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* @@ -128,7 +151,7 @@ private: PhysicsContactData* _preContactData; void* _contactInfo; - friend class PhysicsWorld; + friend class EventListenerPhysicsContact; }; /* @@ -149,60 +172,99 @@ private: private: void* _contactInfo; - friend class PhysicsWorld; + friend class EventListenerPhysicsContact; }; +static const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; + /* * @brief contact listener. */ -class PhysicsContactListener : public EventListener +class EventListenerPhysicsContact : public EventListenerCustom { public: - static PhysicsContactListener* create(); + static EventListenerPhysicsContact* create(); virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); - virtual bool checkAvailable(); - virtual EventListener* clone(); + virtual bool checkAvailable() override; + virtual EventListenerPhysicsContact* clone() override; public: /* * @brief it will called at two shapes start to contact, and only call it once. */ - std::function onContactBegin; + std::function onContactBegin; /* * @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, elasticity, or surface velocity values. */ - std::function onContactPreSolve; + std::function onContactPreSolve; /* * @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info */ - std::function onContactPostSolve; + std::function onContactPostSolve; /* * @brief it will called at two shapes separated, and only call it once. - * onContactBegin and onContactEnd will called in pairs. + * onContactBegin and onContactSeperate will called in pairs. */ - std::function onContactEnd; + std::function onContactSeperate; protected: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); + bool init(); + void onEvent(EventCustom* event); + +protected: + EventListenerPhysicsContact(); + virtual ~EventListenerPhysicsContact(); }; -class PhysicsContactWithBodysListener : public PhysicsContactListener +class EventListenerPhysicsContactWithBodies : public EventListenerPhysicsContact { public: - static PhysicsContactWithBodysListener* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + static EventListenerPhysicsContactWithBodies* create(PhysicsBody* bodyA, PhysicsBody* bodyB); virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); - virtual EventListener* clone(); + virtual EventListenerPhysicsContactWithBodies* clone() override; + +protected: + PhysicsBody* _a; + PhysicsBody* _b; + +protected: + EventListenerPhysicsContactWithBodies(); + virtual ~EventListenerPhysicsContactWithBodies(); +}; + +class EventListenerPhysicsContactWithShapes : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithShapes* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual EventListenerPhysicsContactWithShapes* clone() override; protected: PhysicsShape* _a; PhysicsShape* _b; protected: - PhysicsContactWithBodysListener(); - virtual ~PhysicsContactWithBodysListener(); + EventListenerPhysicsContactWithShapes(); + virtual ~EventListenerPhysicsContactWithShapes(); +}; + +class EventListenerPhysicsContactWithGroup : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithGroup* create(int group); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual EventListenerPhysicsContactWithGroup* clone() override; + +protected: + int _group; + +protected: + EventListenerPhysicsContactWithGroup(); + virtual ~EventListenerPhysicsContactWithGroup(); }; NS_CC_END diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index a8d3d962c7..58bf2ecec3 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -53,6 +53,8 @@ #include "CCArray.h" #include "CCScene.h" #include "CCDirector.h" +#include "CCEventDispatcher.h" +#include "CCEventCustom.h" #include @@ -175,7 +177,7 @@ void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distanc arr->addObject(it->second->shape); } -bool PhysicsWorld::init() +bool PhysicsWorld::init(Scene& scene) { do { @@ -184,6 +186,8 @@ bool PhysicsWorld::init() _bodies = Array::create(); CC_BREAK_IF(_bodies == nullptr); _bodies->retain(); + + _scene = &scene; cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); @@ -458,11 +462,6 @@ void PhysicsWorld::debugDraw() } } -void PhysicsWorld::setScene(Scene *scene) -{ - _scene = scene; -} - void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) { for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) @@ -571,6 +570,7 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; + PhysicsShape* shapeA = contact.getShapeA(); PhysicsShape* shapeB = contact.getShapeB(); PhysicsBody* bodyA = shapeA->getBody(); @@ -597,7 +597,6 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) } } - // bitmask check if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) @@ -617,69 +616,42 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) } } - if (contact.getNotify() && _listener && _listener->onContactBegin) - { - contact._begin = true; - contact.generateContactData(); - - // the mask has high priority than _listener->onContactBegin. - // so if the mask test is false, the two bodies won't have collision. - if (ret) - { - ret = _listener->onContactBegin(*this, contact); - }else - { - _listener->onContactBegin(*this, contact); - } - } + contact.setEventCode(PhysicsContact::EventCode::BEGIN); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); - return ret; + return ret ? contact.resetResult() : false; } int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) - { - return true; - } + contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); - if (_listener && _listener->onContactPreSolve) - { - PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); - contact._begin = false; - contact.generateContactData(); - - return _listener->onContactPreSolve(*this, contact, solve); - } - - return true; + return contact.resetResult(); } void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactPreSolve) - { - PhysicsContactPostSolve solve(contact._contactInfo); - _listener->onContactPostSolve(*this, contact, solve); - } + contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); } void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactEnd) - { - _listener->onContactEnd(*this, contact); - } + contact.setEventCode(PhysicsContact::EventCode::SEPERATE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); } void PhysicsWorld::setGravity(Point gravity) @@ -786,10 +758,10 @@ PhysicsBody* PhysicsWorld::getBodyByTag(int tag) #endif -PhysicsWorld* PhysicsWorld::create() +PhysicsWorld* PhysicsWorld::create(Scene& scene) { PhysicsWorld * world = new PhysicsWorld(); - if(world && world->init()) + if(world && world->init(scene)) { return world; } @@ -802,7 +774,6 @@ PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) , _info(nullptr) -, _listener(nullptr) , _bodies(nullptr) , _scene(nullptr) , _debugDraw(false) diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index aff9119485..6a7095da31 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -40,7 +40,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class PhysicsContactListener; class Array; class Sprite; @@ -101,10 +100,11 @@ public: PhysicsBody* getBodyByTag(int tag); /** Register a listener to receive contact callbacks*/ - inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } + //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } /** Unregister a listener. */ - inline void unregisterContactListener() { _listener = nullptr; } + //inline void unregisterContactListener() { _listener = nullptr; } + inline Scene& getScene() { return *_scene; } /** get the gravity value */ inline Point getGravity() { return _gravity; } /** set the gravity value */ @@ -120,10 +120,8 @@ public: virtual void removeAllBodies(); protected: - static PhysicsWorld* create(); - bool init(); - - void setScene(Scene* scene); + static PhysicsWorld* create(Scene& scene); + bool init(Scene& scene); virtual PhysicsBody* addBody(PhysicsBody* body); virtual PhysicsShape* addShape(PhysicsShape* shape); @@ -144,8 +142,7 @@ protected: Point _gravity; float _speed; PhysicsWorldInfo* _info; - PhysicsContactListener* _listener; - + //EventListenerPhysicsContact* _listener; Array* _bodies; std::list _joints; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f8e88891eb..f36b11e7d5 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -898,7 +898,7 @@ void PhysicsDemoPump::onEnter() // balls for (int i = 0; i < 6; ++i) { - auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.5f, 0.0f, 0.1f)); + auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.05f, 0.0f, 0.1f)); ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(ball); } @@ -908,8 +908,8 @@ void PhysicsDemoPump::onEnter() Point vec[4] = { - VisibleRect::leftTop() + Point(102, -146), - VisibleRect::leftTop() + Point(148, -159), + VisibleRect::leftTop() + Point(102, -148), + VisibleRect::leftTop() + Point(148, -161), VisibleRect::leftBottom() + Point(148, 20), VisibleRect::leftBottom() + Point(102, 20) }; @@ -918,7 +918,7 @@ void PhysicsDemoPump::onEnter() // small gear auto sgear = Node::create(); - auto sgearB = PhysicsBody::createCircle(50); + auto sgearB = PhysicsBody::createCircle(44); sgear->setPhysicsBody(sgearB); sgear->setPosition(VisibleRect::leftBottom() + Point(125, 0)); this->addChild(sgear); @@ -946,7 +946,7 @@ void PhysicsDemoPump::onEnter() this->addChild(pump); pumpB->setCategoryBitmask(0x02); pumpB->setGravityEnable(false); - _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -50))); + _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -44))); // plugger Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; @@ -964,7 +964,7 @@ void PhysicsDemoPump::onEnter() pluggerB->setCategoryBitmask(0x02); sgearB->setCollisionBitmask(0x04 | 0x01); _world->addJoint(PhysicsJointPin::create(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); - _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(50, 0))); + _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); } void PhysicsDemoPump::update(float delta) @@ -1024,7 +1024,6 @@ std::string PhysicsDemoPump::title() return "Pump"; } - void PhysicsDemoOneWayPlatform::onEnter() { PhysicsDemo::onEnter(); @@ -1044,7 +1043,17 @@ void PhysicsDemoOneWayPlatform::onEnter() platform->setPosition(VisibleRect::center()); this->addChild(platform); - this->addChild(makeBall(VisibleRect::center() + Point(0, 50), 5)); + auto ball = makeBall(VisibleRect::center() + Point(0, 50), 5); + this->addChild(ball); + + auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); + contactListener->onContactPreSolve = CC_CALLBACK_3(PhysicsDemoOneWayPlatform::onPreSolve, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); +} + +bool PhysicsDemoOneWayPlatform::onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve) +{ + return true; } std::string PhysicsDemoOneWayPlatform::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index dcf3cf4bb3..185c2a3e96 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -139,6 +139,8 @@ class PhysicsDemoOneWayPlatform : public PhysicsDemo public: void onEnter() override; std::string title() override; + + bool onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve); }; #endif From 2f67ceb495b4e35108436530deb22a7b64f199cb Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 1 Nov 2013 16:26:03 +0800 Subject: [PATCH 022/197] issue #2771: fix some code style --- cocos/2d/CCNode.cpp | 4 +- cocos/physics/CCPhysicsBody.cpp | 6 +-- cocos/physics/CCPhysicsBody.h | 32 ++++++------ cocos/physics/CCPhysicsContact.cpp | 34 +++++++------ cocos/physics/CCPhysicsContact.h | 28 +++++------ cocos/physics/CCPhysicsJoint.cpp | 30 +++++------ cocos/physics/CCPhysicsJoint.h | 20 ++++---- cocos/physics/CCPhysicsShape.cpp | 18 +++---- cocos/physics/CCPhysicsShape.h | 28 +++++------ cocos/physics/CCPhysicsWorld.cpp | 50 +++++++++++++++---- cocos/physics/CCPhysicsWorld.h | 12 ++--- .../Classes/PhysicsTest/PhysicsTest.cpp | 11 ++-- 12 files changed, 152 insertions(+), 121 deletions(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 494f267136..cb1fb62f6c 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -1389,12 +1389,12 @@ void Node::setPhysicsBody(PhysicsBody* body) { if (_physicsBody != nullptr) { - _physicsBody->_owner = nullptr; + _physicsBody->_node = nullptr; _physicsBody->release(); } _physicsBody = body; - _physicsBody->_owner = this; + _physicsBody->_node = this; _physicsBody->retain(); _physicsBody->setPosition(getPosition()); _physicsBody->setRotation(getRotation()); diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 70bfe275b8..405687a21b 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -60,7 +60,7 @@ namespace } PhysicsBody::PhysicsBody() -: _owner(nullptr) +: _node(nullptr) , _shapes(nullptr) , _world(nullptr) , _info(nullptr) @@ -570,7 +570,7 @@ void PhysicsBody::setMoment(float moment) } } -PhysicsShape* PhysicsBody::getShapeByTag(int tag) +PhysicsShape* PhysicsBody::getShapeByTag(int tag) const { for (auto child : *_shapes) { @@ -666,7 +666,7 @@ void PhysicsBody::setEnable(bool enable) } } -bool PhysicsBody::isResting() +bool PhysicsBody::isResting() const { return cpBodyIsSleeping(_info->body) == cpTrue; } diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 6073207dbd..a4bad406b8 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -122,12 +122,12 @@ public: /* * @brief get the body shapes. */ - inline Array* getShapes() { return _shapes; } + inline Array* getShapes() const { return _shapes; } /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } - PhysicsShape* getShapeByTag(int tag); + inline PhysicsShape* getShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + PhysicsShape* getShapeByTag(int tag) const; /* * @brief remove a shape from body */ @@ -152,7 +152,7 @@ public: /* * @brief get the sprite the body set to. */ - inline Node* getOwner() const { return _owner; } + inline Node* getNode() const { return _node; } void setCategoryBitmask(int bitmask); void setContactTestBitmask(int bitmask); @@ -162,7 +162,7 @@ public: inline int getCollisionBitmask() const { return _collisionBitmask; } void setGroup(int group); - inline int getGroup() { return _group; } + inline int getGroup() const { return _group; } /* * @brief get the body position. @@ -177,7 +177,7 @@ public: * @brief test the body is dynamic or not. * a dynamic body will effect with gravity. */ - inline bool isDynamic() { return _dynamic; } + inline bool isDynamic() const { return _dynamic; } /* * @brief set dynamic to body. * a dynamic body will effect with gravity. @@ -192,7 +192,7 @@ public: /* * @brief get the body mass. */ - inline float getMass() { return _mass; } + inline float getMass() const { return _mass; } /* * @brief add mass to body. * if _mass(mass of the body) == PHYSICS_INFINITY, it remains. @@ -211,7 +211,7 @@ public: /* * @brief get the body moment of inertia. */ - inline float getMoment(float moment) { return _moment; } + inline float getMoment(float moment) const { return _moment; } /* * @brief add moment of inertia to body. * if _moment(moment of the body) == PHYSICS_INFINITY, it remains. @@ -228,25 +228,25 @@ public: /* * @brief get angular damping. */ - inline float getLinearDamping() { return _linearDamping; } + inline float getLinearDamping() const { return _linearDamping; } inline void setLinearDamping(float damping) { _linearDamping = damping; } - inline float getAngularDamping() { return _angularDamping; } + inline float getAngularDamping() const { return _angularDamping; } inline void setAngularDamping(float damping) { _angularDamping = damping; } //virtual Clonable* clone() const override; - bool isResting(); - inline bool isEnable() { return _enable; } + bool isResting() const; + inline bool isEnable() const { return _enable; } void setEnable(bool enable); - inline bool isRotationEnable() { return _rotationEnable; } + inline bool isRotationEnable() const { return _rotationEnable; } void setRotationEnable(bool enable); - inline bool isGravityEnable() { return _gravityEnable; } + inline bool isGravityEnable() const { return _gravityEnable; } void setGravityEnable(bool enable); - inline int getTag() { return _tag; } + inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } Point world2Local(const Point& point); @@ -266,7 +266,7 @@ protected: virtual ~PhysicsBody(); protected: - Node* _owner; + Node* _node; std::vector _joints; Array* _shapes; PhysicsWorld* _world; diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 744302cb46..1d0cfd8bdd 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -41,6 +41,8 @@ NS_CC_BEGIN +const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; + PhysicsContact::PhysicsContact() : Event(Event::Type::CUSTOM) , _world(nullptr) @@ -100,7 +102,7 @@ void PhysicsContact::generateContactData() return; } - cpArbiter* arb = (cpArbiter*)_contactInfo; + cpArbiter* arb = static_cast(_contactInfo); _contactData = new PhysicsContactData(); _contactData->count = cpArbiterGetCount(arb); for (int i=0; i<_contactData->count; ++i) @@ -118,34 +120,34 @@ PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* c { } -float PhysicsContactPreSolve::getElasticity() +float PhysicsContactPreSolve::getElasticity() const { - return ((cpArbiter*)_contactInfo)->e; + return static_cast(_contactInfo)->e; } -float PhysicsContactPreSolve::getFriciton() +float PhysicsContactPreSolve::getFriciton() const { - return ((cpArbiter*)_contactInfo)->u; + return static_cast(_contactInfo)->u; } -Point PhysicsContactPreSolve::getSurfaceVelocity() +Point PhysicsContactPreSolve::getSurfaceVelocity() const { - return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); + return PhysicsHelper::cpv2point(static_cast(_contactInfo)->surface_vr); } void PhysicsContactPreSolve::setElasticity(float elasticity) { - ((cpArbiter*)_contactInfo)->e = elasticity; + static_cast(_contactInfo)->e = elasticity; } void PhysicsContactPreSolve::setFriction(float friction) { - ((cpArbiter*)_contactInfo)->u = friction; + static_cast(_contactInfo)->u = friction; } void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) { - ((cpArbiter*)_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); + static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); } PhysicsContactPreSolve::~PhysicsContactPreSolve() @@ -165,19 +167,19 @@ PhysicsContactPostSolve::~PhysicsContactPostSolve() } -float PhysicsContactPostSolve::getElasticity() +float PhysicsContactPostSolve::getElasticity() const { - return ((cpArbiter*)_contactInfo)->e; + return static_cast(_contactInfo)->e; } -float PhysicsContactPostSolve::getFriciton() +float PhysicsContactPostSolve::getFriciton() const { - return ((cpArbiter*)_contactInfo)->u; + return static_cast(_contactInfo)->u; } -Point PhysicsContactPostSolve::getSurfaceVelocity() +Point PhysicsContactPostSolve::getSurfaceVelocity() const { - return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); + return PhysicsHelper::cpv2point(static_cast(_contactInfo)->surface_vr); } EventListenerPhysicsContact::EventListenerPhysicsContact() diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index a4b0454e37..32127da7a5 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -81,22 +81,22 @@ public: /* * @brief get data. */ - inline void* getData() { return _data; } + inline void* getData() const { return _data; } /* * @brief set data to contact. you must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact end. */ inline void setData(void* data) { _data = data; } - EventCode getEventCode() { return _eventCode; }; + EventCode getEventCode() const { return _eventCode; }; private: static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); bool init(PhysicsShape* a, PhysicsShape* b); void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; - inline bool getNotify() { return _notify; } + inline bool getNotify() const { return _notify; } inline void setNotify(bool notify) { _notify = notify; } - inline PhysicsWorld* getWorld() { return _world; } + inline PhysicsWorld* getWorld() const { return _world; } inline void setWorld(PhysicsWorld* world) { _world = world; } inline void setResult(bool result) { _result = result; } inline bool resetResult() { bool ret = _result; _result = true; return ret; } @@ -133,9 +133,9 @@ class PhysicsContactPreSolve { public: // getter/setter - float getElasticity(); - float getFriciton(); - Point getSurfaceVelocity(); + float getElasticity() const; + float getFriciton() const; + Point getSurfaceVelocity() const; void setElasticity(float elasticity); void setFriction(float friction); void setSurfaceVelocity(Point surfaceVelocity); @@ -161,9 +161,9 @@ class PhysicsContactPostSolve { public: // getter - float getElasticity(); - float getFriciton(); - Point getSurfaceVelocity(); + float getElasticity() const; + float getFriciton() const; + Point getSurfaceVelocity() const; private: PhysicsContactPostSolve(void* contactInfo); @@ -175,8 +175,6 @@ private: friend class EventListenerPhysicsContact; }; -static const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; - /* * @brief contact listener. */ @@ -222,7 +220,7 @@ class EventListenerPhysicsContactWithBodies : public EventListenerPhysicsContact public: static EventListenerPhysicsContactWithBodies* create(PhysicsBody* bodyA, PhysicsBody* bodyB); - virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; virtual EventListenerPhysicsContactWithBodies* clone() override; protected: @@ -239,7 +237,7 @@ class EventListenerPhysicsContactWithShapes : public EventListenerPhysicsContact public: static EventListenerPhysicsContactWithShapes* create(PhysicsShape* shapeA, PhysicsShape* shapeB); - virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; virtual EventListenerPhysicsContactWithShapes* clone() override; protected: @@ -256,7 +254,7 @@ class EventListenerPhysicsContactWithGroup : public EventListenerPhysicsContact public: static EventListenerPhysicsContactWithGroup* create(int group); - virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; virtual EventListenerPhysicsContactWithGroup* clone() override; protected: diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index e35b8d241c..99fed53d8b 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -155,14 +155,14 @@ PhysicsJointDistance::~PhysicsJointDistance() } #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const +PhysicsBodyInfo* PhysicsJoint::getBodyInfo(PhysicsBody* body) const { return body->_info; } -Node* PhysicsJoint::bodyOwner(PhysicsBody* body) const +Node* PhysicsJoint::getBodyNode(PhysicsBody* body) const { - return body->_owner; + return body->_node; } @@ -198,17 +198,17 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - bodyOwner(a)->setPosition(anchr); - bodyOwner(b)->setPosition(anchr); + getBodyNode(a)->setPosition(anchr); + getBodyNode(b)->setPosition(anchr); // add a pivot joint to fixed two body together - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. - joint = cpGearJointNew(bodyInfo(a)->body, bodyInfo(b)->body, 0, 1); + joint = cpGearJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, 0, 1); CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -238,7 +238,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); @@ -258,7 +258,7 @@ void PhysicsJointPin::setMaxForce(float force) _info->joints.front()->maxForce = PhysicsHelper::float2cpfloat(force); } -float PhysicsJointPin::getMaxForce() +float PhysicsJointPin::getMaxForce() const { return PhysicsHelper::cpfloat2float(_info->joints.front()->maxForce); } @@ -282,7 +282,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpGrooveJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(grooveA), PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); @@ -317,7 +317,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpSlideJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2), 0, @@ -333,7 +333,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 return false; } -float PhysicsJointLimit::getMin() +float PhysicsJointLimit::getMin() const { return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->joints.front())); } @@ -343,7 +343,7 @@ void PhysicsJointLimit::setMin(float min) cpSlideJointSetMin(_info->joints.front(), PhysicsHelper::float2cpfloat(min)); } -float PhysicsJointLimit::getMax() +float PhysicsJointLimit::getMax() const { return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->joints.front())); } @@ -372,8 +372,8 @@ bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anc { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPinJointNew(bodyInfo(a)->body, - bodyInfo(b)->body, + cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->body, + getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); CC_BREAK_IF(joint == nullptr); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 298992c5f3..2970d992d0 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -47,13 +47,13 @@ protected: virtual ~PhysicsJoint() = 0; public: - PhysicsBody* getBodyA() { return _bodyA; } - PhysicsBody* getBodyB() { return _bodyB; } - inline int getTag() { return _tag; } + PhysicsBody* getBodyA() const { return _bodyA; } + PhysicsBody* getBodyB() const { return _bodyB; } + inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() { return _enable; } + inline bool isEnable() const { return _enable; } void setEnable(bool enable); - inline bool isCollisionEnable() { return _collisionEnable; } + inline bool isCollisionEnable() const { return _collisionEnable; } void setCollisionEnable(bool enable); protected: @@ -62,8 +62,8 @@ protected: /** * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. */ - PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; - Node* bodyOwner(PhysicsBody* body) const; + PhysicsBodyInfo* getBodyInfo(PhysicsBody* body) const; + Node* getBodyNode(PhysicsBody* body) const; protected: PhysicsBody* _bodyA; @@ -133,9 +133,9 @@ class PhysicsJointLimit : public PhysicsJoint public: PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - float getMin(); + float getMin() const; void setMin(float min); - float getMax(); + float getMax() const; void setMax(float max); protected: @@ -155,7 +155,7 @@ public: static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); void setMaxForce(float force); - float getMaxForce(); + float getMaxForce() const; protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index bb17c54501..68ef1cf351 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -353,7 +353,7 @@ float PhysicsShapeCircle::calculateDefaultMoment() cpCircleShapeGetOffset(shape))); } -float PhysicsShapeCircle::getRadius() +float PhysicsShapeCircle::getRadius() const { return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->shapes.front())); } @@ -405,12 +405,12 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* return false; } -Point PhysicsShapeEdgeSegment::getPointA() +Point PhysicsShapeEdgeSegment::getPointA() const { return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->ta); } -Point PhysicsShapeEdgeSegment::getPointB() +Point PhysicsShapeEdgeSegment::getPointB() const { return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->tb); } @@ -503,7 +503,7 @@ float PhysicsShapeBox::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapeBox::getPoints(Point* points) +Point* PhysicsShapeBox::getPoints(Point* points) const { cpShape* shape = _info->shapes.front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); @@ -511,7 +511,7 @@ Point* PhysicsShapeBox::getPoints(Point* points) return points; } -Size PhysicsShapeBox::getSize() +Size PhysicsShapeBox::getSize() const { cpShape* shape = _info->shapes.front(); return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1)), @@ -594,13 +594,13 @@ float PhysicsShapePolygon::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapePolygon::getPoints(Point* points) +Point* PhysicsShapePolygon::getPoints(Point* points) const { cpShape* shape = _info->shapes.front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } -int PhysicsShapePolygon::getPointsCount() +int PhysicsShapePolygon::getPointsCount() const { return ((cpPolyShape*)_info->shapes.front())->numVerts; } @@ -715,7 +715,7 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -int PhysicsShapeEdgePolygon::getPointsCount() +int PhysicsShapeEdgePolygon::getPointsCount() const { return _info->shapes.size() + 1; } @@ -776,7 +776,7 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -int PhysicsShapeEdgeChain::getPointsCount() +int PhysicsShapeEdgeChain::getPointsCount() const { return _info->shapes.size() + 1; } diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 8bc9224bf1..31497d14a2 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -156,8 +156,8 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; - float getRadius(); - Point getOffset(); + float getRadius() const; + Point getOffset() override; protected: bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -177,8 +177,8 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; - Point* getPoints(Point* points); - Size getSize(); + Point* getPoints(Point* points) const; + Size getSize() const; Point getOffset() override { return _offset; } protected: @@ -203,8 +203,8 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; Point getCenter() override; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -223,8 +223,8 @@ class PhysicsShapeEdgeSegment : public PhysicsShape public: static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getPointA(); - Point getPointB(); + Point getPointA() const; + Point getPointB() const; Point getCenter() override; protected: @@ -246,8 +246,8 @@ class PhysicsShapeEdgeBox : public PhysicsShape public: static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); Point getOffset() override { return _offset; } - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; protected: bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); @@ -268,8 +268,8 @@ class PhysicsShapeEdgePolygon : public PhysicsShape public: static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -290,8 +290,8 @@ class PhysicsShapeEdgeChain : public PhysicsShape public: static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 58bf2ecec3..1cd2b936c5 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -60,6 +60,8 @@ NS_CC_BEGIN +extern const char* PHYSICSCONTACT_EVENT_NAME; + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) const float PHYSICS_INFINITY = INFINITY; @@ -269,7 +271,8 @@ PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) if (cpBodyIsStatic(shape->getBody()->_info->body)) { cpSpaceAddStaticShape(_info->space, cps); - }else + } + else { cpSpaceAddShape(_info->space, cps); } @@ -473,7 +476,8 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) cpBody *body_b = constraint->b; const cpConstraintClass *klass = constraint->klass_private; - if(klass == cpPinJointGetClass()){ + if(klass == cpPinJointGetClass()) + { cpPinJoint *joint = (cpPinJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); @@ -482,7 +486,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpSlideJointGetClass()){ + } + else if(klass == cpSlideJointGetClass()) + { cpSlideJoint *joint = (cpSlideJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); @@ -491,7 +497,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpPivotJointGetClass()){ + } + else if(klass == cpPivotJointGetClass()) + { cpPivotJoint *joint = (cpPivotJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); @@ -499,7 +507,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpGrooveJointGetClass()){ + } + else if(klass == cpGrooveJointGetClass()) + { cpGrooveJoint *joint = (cpGrooveJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->grv_a, body_a->rot)); @@ -508,7 +518,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(c), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpDampedSpringGetClass()){ + } + else if(klass == cpDampedSpringGetClass()) + { } } @@ -607,7 +619,8 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) { ret = shapeA->getGroup() > 0; - }else + } + else { if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0 || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0) @@ -627,6 +640,11 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return true; + } + contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); contact.setWorld(this); EventCustom event(PHYSICSCONTACT_EVENT_NAME); @@ -638,6 +656,11 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return; + } + contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); contact.setWorld(this); EventCustom event(PHYSICSCONTACT_EVENT_NAME); @@ -647,6 +670,11 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return; + } + contact.setEventCode(PhysicsContact::EventCode::SEPERATE); contact.setWorld(this); EventCustom event(PHYSICSCONTACT_EVENT_NAME); @@ -680,7 +708,7 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point { if (callback.report != nullptr) { - RayCastCallbackInfo info = {this, &callback, point1, point2, data}; + RayCastCallbackInfo info = { this, &callback, point1, point2, data }; PhysicsWorldCallback::continues = true; cpSpaceSegmentQuery(this->_info->space, @@ -710,7 +738,7 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } -Array* PhysicsWorld::getShapesAtPoint(Point point) +Array* PhysicsWorld::getShapesAtPoint(Point point) const { Array* arr = Array::create(); cpSpaceNearestPointQuery(this->_info->space, @@ -724,7 +752,7 @@ Array* PhysicsWorld::getShapesAtPoint(Point point) return arr; } -PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) +PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) const { cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->space, PhysicsHelper::point2cpv(point), @@ -741,7 +769,7 @@ Array* PhysicsWorld::getAllBodies() const return _bodies; } -PhysicsBody* PhysicsWorld::getBodyByTag(int tag) +PhysicsBody* PhysicsWorld::getBodyByTag(int tag) const { for (auto body : *_bodies) { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 6a7095da31..e719dce2c4 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -94,24 +94,24 @@ public: void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); - Array* getShapesAtPoint(Point point); - PhysicsShape* getShapeAtPoint(Point point); + Array* getShapesAtPoint(Point point) const; + PhysicsShape* getShapeAtPoint(Point point) const; Array* getAllBodies() const; - PhysicsBody* getBodyByTag(int tag); + PhysicsBody* getBodyByTag(int tag) const; /** Register a listener to receive contact callbacks*/ //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } /** Unregister a listener. */ //inline void unregisterContactListener() { _listener = nullptr; } - inline Scene& getScene() { return *_scene; } + inline Scene& getScene() const { return *_scene; } /** get the gravity value */ - inline Point getGravity() { return _gravity; } + inline Point getGravity() const { return _gravity; } /** set the gravity value */ void setGravity(Point gravity); /** test the debug draw is enabled */ - inline bool isDebugDraw() { return _debugDraw; } + inline bool isDebugDraw() const { return _debugDraw; } /** set the debug draw */ inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f36b11e7d5..db51829b3f 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -13,6 +13,7 @@ namespace CL(PhysicsDemoJoints), CL(PhysicsDemoActions), CL(PhysicsDemoPump), + CL(PhysicsDemoOneWayPlatform), }; static int sceneIdx=-1; @@ -974,7 +975,7 @@ void PhysicsDemoPump::update(float delta) PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) { - body->getOwner()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); + body->getNode()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); body->setVelocity(Point(0, 0)); } } @@ -992,7 +993,7 @@ void PhysicsDemoPump::update(float delta) } gear->setAngularVelocity(_rotationV); - _rotationV *= 0.995; + _rotationV *= 0.995f; } } @@ -1039,11 +1040,13 @@ void PhysicsDemoOneWayPlatform::onEnter() this->addChild(ground); auto platform = Node::create(); - platform->setPhysicsBody(PhysicsBody::createEdgeBox(Size(200, 50))); + platform->setPhysicsBody(PhysicsBody::createBox(Size(200, 50))); + platform->getPhysicsBody()->setDynamic(false); platform->setPosition(VisibleRect::center()); this->addChild(platform); - auto ball = makeBall(VisibleRect::center() + Point(0, 50), 5); + auto ball = makeBall(VisibleRect::center() - Point(0, 50), 5); + ball->getPhysicsBody()->setVelocity(Point(0, 200)); this->addChild(ball); auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); From a2adbff2c8cd805e0dfae3578eb888096d75bc71 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 1 Nov 2013 16:32:27 +0800 Subject: [PATCH 023/197] issue #2771: fix some code style --- cocos/physics/CCPhysicsBody.cpp | 9 --------- cocos/physics/CCPhysicsJoint.cpp | 7 ------- 2 files changed, 16 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 405687a21b..189b9edcfa 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -730,15 +730,6 @@ Point PhysicsBody::local2World(const Point& point) return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->body, PhysicsHelper::point2cpv(point))); } -//Clonable* PhysicsBody::clone() const -//{ -// PhysicsBody* body = new PhysicsBody(); -// -// body->autorelease(); -// -// return body; -//} - #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 99fed53d8b..694559264e 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -171,11 +171,6 @@ void PhysicsJoint::setCollisionEnable(bool enable) if (_collisionEnable != enable) { _collisionEnable = enable; - -// for (auto shape : _bodyB->_shapes) -// { -// shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); -// } } } @@ -245,8 +240,6 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) _info->add(joint); - //setCollisionEnable(false); - return true; } while (false); From 5443fc0d07739743248eb431e1afb95bb1cdd23e Mon Sep 17 00:00:00 2001 From: psi Date: Sun, 3 Nov 2013 11:17:04 +0900 Subject: [PATCH 024/197] pXmlBuffer is not null terminated --- cocos/2d/CCUserDefault.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index ab30c805a0..5a85d65b41 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -66,7 +66,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle CCLOG("can not read xml file"); break; } - xmlDoc->Parse(pXmlBuffer); + xmlDoc->Parse(pXmlBuffer, nSize); delete[] pXmlBuffer; // get root node *rootNode = xmlDoc->RootElement(); From 6b8b1fb3c964a44999ce32f615edd374e577d801 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 14:01:02 +0800 Subject: [PATCH 025/197] Update android-build.py Fixing wrong capital letter, `samples/JavaScript` --> `samples/Javascript` --- build/android-build.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index be4800453a..07003e1953 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -182,15 +182,15 @@ def build_samples(target,ndk_build_param): elif target == 'testlua': app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android') elif target == 'cocosdragon': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CocosDragonJS/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/CocosDragonJS/proj.android') elif target == 'crystalcraze': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CrystalCraze/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/CrystalCraze/proj.android') elif target == 'moonwarriors': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/MoonWarriors/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/MoonWarriors/proj.android') elif target == 'testjavascript': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/TestJavascript/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/TestJavascript/proj.android') elif target == 'watermelonwithme': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/WatermelonWithMe/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/WatermelonWithMe/proj.android') else: print 'unknown target: %s' % target continue From a823e66f8e3cdb9afd56ac9f79b443108c47ddbc Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 14:36:22 +0800 Subject: [PATCH 026/197] Update run-script.sh Adding soft-link for `samples/Cpp/SimpleGame/proj.android/obj`. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index f9e5e0ff6b..5cd83ad826 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -42,7 +42,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Create a directory for temporary objects mkdir android_build_objs - PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") + PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/SimpleGame" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") for i in ${PROJECTS[*]}; do ln -s $COCOS2DX_ROOT/android_build_objs $COCOS2DX_ROOT/samples/$i/proj.android/obj done From 44bc52cf65eee6ad38a0046431c7159160cba988 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 15:36:05 +0800 Subject: [PATCH 027/197] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index c8e6b9d403..12f5963e3e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -12,6 +12,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Refactored and improved EventDispatcher. [NEW] Added Mouse Support For Desktop Platforms. [FIX] EventListeners can't be removed sometimes. + [FIX] When parsing XML using TinyXML, the data size has to be specified. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From d335769e3fccbae58ad3fa9bbb14702c95d544e8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 15:37:39 +0800 Subject: [PATCH 028/197] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 41e87fa132..0c11df97d6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -640,6 +640,7 @@ Developers: ledyba Fixed a bug that EventListeners can't be removed sometimes. + Fixed a bug that the data size has to be specified when parsing XML using TinyXML. Retired Core Developers: WenSheng Yang From 1cf0a926e19a6b8f75319f4a6acfb307a3202580 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 4 Nov 2013 02:46:22 +0000 Subject: [PATCH 029/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f399ed2207..006193d9b4 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f399ed22077b04a757a1b5613acf20bfdf7796b7 +Subproject commit 006193d9b4081c8af2b79be3cd9bcf90aedfdbae From f6d82d21d21421770bb030227e1dc4e5e970444f Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 4 Nov 2013 10:48:45 +0800 Subject: [PATCH 030/197] closed #3108: add -fsigned-char to make char to signed as default --- samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk | 3 +-- samples/Cpp/HelloCpp/proj.android/jni/Application.mk | 2 +- samples/Cpp/SimpleGame/proj.android/jni/Application.mk | 2 +- samples/Cpp/TestCpp/proj.android/jni/Application.mk | 2 +- .../Javascript/CocosDragonJS/proj.android/jni/Application.mk | 3 +-- .../Javascript/CrystalCraze/proj.android/jni/Application.mk | 3 +-- .../Javascript/MoonWarriors/proj.android/jni/Application.mk | 3 +-- .../Javascript/TestJavascript/proj.android/jni/Application.mk | 3 +-- .../WatermelonWithMe/proj.android/jni/Application.mk | 3 +-- samples/Lua/HelloLua/proj.android/jni/Application.mk | 4 ++-- samples/Lua/TestLua/proj.android/jni/Application.mk | 2 +- template/multi-platform-cpp/proj.android/jni/Application.mk | 2 +- template/multi-platform-js/proj.android/jni/Application.mk | 4 ++-- template/multi-platform-lua/proj.android/jni/Application.mk | 2 +- 14 files changed, 16 insertions(+), 22 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk index 5273ceb9dd..74af9626ab 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk +++ b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk index 0e9d025fba..74af9626ab 100644 --- a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk +++ b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk index 0e9d025fba..74af9626ab 100644 --- a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk +++ b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/TestCpp/proj.android/jni/Application.mk b/samples/Cpp/TestCpp/proj.android/jni/Application.mk index 9761d1692d..47d8add103 100644 --- a/samples/Cpp/TestCpp/proj.android/jni/Application.mk +++ b/samples/Cpp/TestCpp/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk index 24a7a8cbb3..3666985a1f 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk +++ b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk @@ -1,7 +1,6 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk index 24a7a8cbb3..3666985a1f 100644 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk +++ b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk @@ -1,7 +1,6 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk b/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk index 6608c6e10e..47d8add103 100644 --- a/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk +++ b/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT= -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk index dc8b56b0ac..47d8add103 100644 --- a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk +++ b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk index dc8b56b0ac..47d8add103 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk +++ b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Lua/HelloLua/proj.android/jni/Application.mk b/samples/Lua/HelloLua/proj.android/jni/Application.mk index a829fc0f48..540e49c358 100644 --- a/samples/Lua/HelloLua/proj.android/jni/Application.mk +++ b/samples/Lua/HelloLua/proj.android/jni/Application.mk @@ -2,7 +2,7 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char -APP_CPPFLAGS += -fexceptions +APP_CPPFLAGS += -fexceptions diff --git a/samples/Lua/TestLua/proj.android/jni/Application.mk b/samples/Lua/TestLua/proj.android/jni/Application.mk index a829fc0f48..3961feba34 100644 --- a/samples/Lua/TestLua/proj.android/jni/Application.mk +++ b/samples/Lua/TestLua/proj.android/jni/Application.mk @@ -2,7 +2,7 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char APP_CPPFLAGS += -fexceptions diff --git a/template/multi-platform-cpp/proj.android/jni/Application.mk b/template/multi-platform-cpp/proj.android/jni/Application.mk index b20df4f373..ae98b275c1 100644 --- a/template/multi-platform-cpp/proj.android/jni/Application.mk +++ b/template/multi-platform-cpp/proj.android/jni/Application.mk @@ -1,2 +1,2 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -fsigned-char diff --git a/template/multi-platform-js/proj.android/jni/Application.mk b/template/multi-platform-js/proj.android/jni/Application.mk index ee36f34b40..76c0f20fca 100644 --- a/template/multi-platform-js/proj.android/jni/Application.mk +++ b/template/multi-platform-js/proj.android/jni/Application.mk @@ -1,4 +1,4 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 +APP_CPPFLAGS := -frtti +APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char diff --git a/template/multi-platform-lua/proj.android/jni/Application.mk b/template/multi-platform-lua/proj.android/jni/Application.mk index 95acd5331a..de85c24eda 100644 --- a/template/multi-platform-lua/proj.android/jni/Application.mk +++ b/template/multi-platform-lua/proj.android/jni/Application.mk @@ -1,4 +1,4 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char APP_CPPFLAGS += -fexceptions From 6d6cbc98bbb69dba0eea999195a2284d310aa4c0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 13:46:56 +0800 Subject: [PATCH 031/197] Update travis.yml, only build master and develop branch [ci skip] --- .travis.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.travis.yml b/.travis.yml index 966f293146..1e67e468bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,3 +26,9 @@ script: - tools/travis-scripts/run-script.sh before_install: - tools/travis-scripts/before-install.sh + +# whitelist +branches: + only: + - master + - develop From 00acd67ff37595dc78fb2c9f3424afe7c3247356 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 4 Nov 2013 14:36:38 +0800 Subject: [PATCH 032/197] issue #2771: finish OneWayPlatform demo and fix some bugs --- cocos/physics/CCPhysicsBody.cpp | 15 ++++++++---- cocos/physics/CCPhysicsContact.cpp | 4 ++-- cocos/physics/CCPhysicsShape.cpp | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 24 +++++++++---------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 2 +- 5 files changed, 27 insertions(+), 20 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 1922ee59d4..152a4fc454 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -79,7 +79,7 @@ PhysicsBody::PhysicsBody() , _tag(0) , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) -, _contactTestBitmask(0) +, _contactTestBitmask(UINT_MAX) , _group(0) { } @@ -287,12 +287,19 @@ void PhysicsBody::setDynamic(bool dynamic) if (dynamic != _dynamic) { _dynamic = dynamic; - if (_world != nullptr) + if (dynamic) { - if (dynamic) + cpBodySetMass(_info->body, _mass); + + if (_world != nullptr) { cpSpaceAddBody(_world->_info->space, _info->body); - }else + } + }else + { + cpBodySetMass(_info->body, PHYSICS_INFINITY); + + if (_world != nullptr) { cpSpaceRemoveBody(_world->_info->space, _info->body); } diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 1d0cfd8bdd..b5a7c7e0a3 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -194,7 +194,7 @@ bool EventListenerPhysicsContact::init() { auto func = [this](EventCustom* event) -> void { - return onEvent(event); + onEvent(event); }; return EventListenerCustom::init(std::hash()(PHYSICSCONTACT_EVENT_NAME), func); @@ -250,7 +250,7 @@ void EventListenerPhysicsContact::onEvent(EventCustom* event) } case PhysicsContact::EventCode::POSTSOLVE: { - if (onContactPreSolve != nullptr + if (onContactPostSolve != nullptr && test(contact.getShapeA(), contact.getShapeB())) { PhysicsContactPostSolve solve(contact._contactInfo); diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 68ef1cf351..c2334ec719 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -52,7 +52,7 @@ PhysicsShape::PhysicsShape() , _tag(0) , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) -, _contactTestBitmask(0) +, _contactTestBitmask(UINT_MAX) , _group(0) { diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index db51829b3f..866cec82fd 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -204,10 +204,8 @@ void PhysicsDemoClickAdd::onEnter() #ifdef CC_USE_PHYSICS - auto touchListener = EventListenerTouchOneByOne::create(); - touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchBegan, this); - touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchMoved, this); - touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchEnded, this); + auto touchListener = EventListenerTouchAllAtOnce::create(); + touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); @@ -764,6 +762,8 @@ void PhysicsDemoJoints::onEnter() PhysicsDemo::onEnter(); auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoJoints::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoJoints::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -1039,24 +1039,24 @@ void PhysicsDemoOneWayPlatform::onEnter() ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(ground); - auto platform = Node::create(); - platform->setPhysicsBody(PhysicsBody::createBox(Size(200, 50))); + auto platform = makeBox(VisibleRect::center(), Size(200, 50)); platform->getPhysicsBody()->setDynamic(false); - platform->setPosition(VisibleRect::center()); this->addChild(platform); - auto ball = makeBall(VisibleRect::center() - Point(0, 50), 5); - ball->getPhysicsBody()->setVelocity(Point(0, 200)); + auto ball = makeBall(VisibleRect::center() - Point(0, 50), 20); + ball->getPhysicsBody()->setVelocity(Point(0, 150)); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + ball->getPhysicsBody()->setMass(1.0f); this->addChild(ball); auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); - contactListener->onContactPreSolve = CC_CALLBACK_3(PhysicsDemoOneWayPlatform::onPreSolve, this); + contactListener->onContactBegin = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); } -bool PhysicsDemoOneWayPlatform::onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve) +bool PhysicsDemoOneWayPlatform::onContactBegin(EventCustom* event, const PhysicsContact& contact) { - return true; + return contact.getContactData()->normal.y < 0; } std::string PhysicsDemoOneWayPlatform::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 185c2a3e96..4de964f2d3 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -140,7 +140,7 @@ public: void onEnter() override; std::string title() override; - bool onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve); + bool onContactBegin(EventCustom* event, const PhysicsContact& contact); }; #endif From 790be0decccb6f2d7e1071979447e3222222231e Mon Sep 17 00:00:00 2001 From: samuele3 Date: Mon, 4 Nov 2013 14:43:22 +0800 Subject: [PATCH 033/197] issue #3037:Modify vs2012 config --- extensions/assets-manager/AssetsManager.h | 2 +- .../Classes/lua_assetsmanager_test_sample.cpp | 14 ++------------ .../Lua/TestLua/proj.win32/TestLua.win32.vcxproj | 8 +++++--- .../proj.win32/TestLua.win32.vcxproj.filters | 6 ++++++ 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 80f0ae5d81..f3e413f4bd 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -145,7 +145,7 @@ public: * @js NA * @lua NA */ - AssetsManagerDelegateProtocol* getDelegate() { return _delegate ;} + AssetsManagerDelegateProtocol* getDelegate() const { return _delegate ;} /** @brief Sets connection time out in seconds */ diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp index e3d6377f0b..7f0135f06e 100644 --- a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp +++ b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp @@ -26,10 +26,7 @@ static int lua_cocos2dx_createDownloadDir(lua_State* L) return 0; int argc = lua_gettop(L); -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - + if (0 == argc) { std::string pathToSave = FileUtils::getInstance()->getWritablePath(); @@ -50,18 +47,11 @@ static int lua_cocos2dx_createDownloadDir(lua_State* L) } #endif tolua_pushstring(L, pathToSave.c_str()); - CCLOG("the path to save is %s",pathToSave.c_str()); return 1; } CCLOG("'createDownloadDir' function wrong number of arguments: %d, was expecting %d\n", argc, 0); return 0; - -#if COCOS2D_DEBUG >= 1 -tolua_lerror: - tolua_error(L,"#ferror in function 'createDownloadDir'.",&tolua_err); - return 0; -#endif } static int lua_cocos2dx_deleteDownloadDir(lua_State* L) @@ -126,7 +116,7 @@ static int lua_cocos2dx_addSearchPath(lua_State* L) goto tolua_lerror; #endif std::string pathToSave = tolua_tostring(L, 1, ""); - bool before = tolua_toboolean(L, 2, 0); + bool before = (bool)tolua_toboolean(L, 2, 0); std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); if (before) { diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj index f70904ac2f..b95a8da2f8 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj @@ -66,7 +66,7 @@ - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories) Level3 @@ -115,7 +115,7 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)" - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories) Level3 @@ -131,7 +131,7 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)"Windows MachineX86 $(OutDir);%(AdditionalLibraryDirectories) - lua51.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) true @@ -163,10 +163,12 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters index 7517b68f2b..12f4b9ee7c 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters @@ -15,6 +15,9 @@ win32 + + Classes + @@ -23,5 +26,8 @@ win32 + + Classes + \ No newline at end of file From 3289ce8fe09f63f8e36de96a6bce1c84f2f1abe4 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Mon, 4 Nov 2013 14:50:23 +0800 Subject: [PATCH 034/197] issue #3037:Modify vs2012 config --- samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp index 7f0135f06e..a254c2cbbd 100644 --- a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp +++ b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp @@ -116,7 +116,7 @@ static int lua_cocos2dx_addSearchPath(lua_State* L) goto tolua_lerror; #endif std::string pathToSave = tolua_tostring(L, 1, ""); - bool before = (bool)tolua_toboolean(L, 2, 0); + bool before = tolua_toboolean(L, 2, 0); std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); if (before) { From b5838b800d37f455b00e22a106c9aa67e9a7db5f Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 4 Nov 2013 16:48:17 +0800 Subject: [PATCH 035/197] use python script to build template android projects --- CHANGELOG | 3 +- build/android-build.py | 4 - .../proj.android/build_native.cmd | 83 -------------- .../proj.android/build_native.py | 100 +++++++++++++++++ .../proj.android/build_native.sh | 91 --------------- .../proj.android/build_native.cmd | 90 --------------- .../proj.android/build_native.py | 104 ++++++++++++++++++ .../proj.android/build_native.sh | 100 ----------------- .../proj.android/build_native.cmd | 86 --------------- .../proj.android/build_native.py | 104 ++++++++++++++++++ .../proj.android/build_native.sh | 102 ----------------- 11 files changed, 310 insertions(+), 557 deletions(-) delete mode 100644 template/multi-platform-cpp/proj.android/build_native.cmd create mode 100755 template/multi-platform-cpp/proj.android/build_native.py delete mode 100755 template/multi-platform-cpp/proj.android/build_native.sh delete mode 100644 template/multi-platform-js/proj.android/build_native.cmd create mode 100755 template/multi-platform-js/proj.android/build_native.py delete mode 100755 template/multi-platform-js/proj.android/build_native.sh delete mode 100644 template/multi-platform-lua/proj.android/build_native.cmd create mode 100755 template/multi-platform-lua/proj.android/build_native.py delete mode 100755 template/multi-platform-lua/proj.android/build_native.sh diff --git a/CHANGELOG b/CHANGELOG index 12f5963e3e..0d0efb8f2d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -19,7 +19,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [NEW] Added xlargeScreens="true" to supports-screens - [NEW] Added build/android-build.py to build all Android samples + [NEW] Added build/android-build.py to build all Android samples, and remove all build_native.sh/cmd + [NEW] Added build_native.py to build template projects, and remove build_native.sh/cmd [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] diff --git a/build/android-build.py b/build/android-build.py index 07003e1953..d1a272c2db 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -2,10 +2,6 @@ # android-build.py # Build android samples -# You can use - - -# begin import sys import os, os.path import shutil diff --git a/template/multi-platform-cpp/proj.android/build_native.cmd b/template/multi-platform-cpp/proj.android/build_native.cmd deleted file mode 100644 index 5b25ec4817..0000000000 --- a/template/multi-platform-cpp/proj.android/build_native.cmd +++ /dev/null @@ -1,83 +0,0 @@ -@echo off - -set APPNAME="HelloCpp" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-cpp/proj.android/build_native.py b/template/multi-platform-cpp/proj.android/build_native.py new file mode 100755 index 0000000000..e426c2c0ec --- /dev/null +++ b/template/multi-platform-cpp/proj.android/build_native.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-cpp/proj.android/build_native.sh b/template/multi-platform-cpp/proj.android/build_native.sh deleted file mode 100755 index 47c3c53564..0000000000 --- a/template/multi-platform-cpp/proj.android/build_native.sh +++ /dev/null @@ -1,91 +0,0 @@ -APPNAME="HelloCpp" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# run ndk-build -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi diff --git a/template/multi-platform-js/proj.android/build_native.cmd b/template/multi-platform-js/proj.android/build_native.cmd deleted file mode 100644 index 82eb0151a5..0000000000 --- a/template/multi-platform-js/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="HelloJavascript" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-js/proj.android/build_native.py b/template/multi-platform-js/proj.android/build_native.py new file mode 100755 index 0000000000..4e67dd7cfb --- /dev/null +++ b/template/multi-platform-js/proj.android/build_native.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # jsb project should copy javascript files and resources(shared with cocos2d-html5) + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/javascript/script") + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-js/proj.android/build_native.sh b/template/multi-platform-js/proj.android/build_native.sh deleted file mode 100755 index 5a008713a3..0000000000 --- a/template/multi-platform-js/proj.android/build_native.sh +++ /dev/null @@ -1,100 +0,0 @@ -APPNAME="HelloJavascript" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets -mkdir "$APP_ANDROID_ROOT"/assets/res - -# copy Resources/* into assets' root -cp -rf "$APP_ROOT"/Resources/* "$APP_ANDROID_ROOT"/assets - - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/template/multi-platform-lua/proj.android/build_native.cmd b/template/multi-platform-lua/proj.android/build_native.cmd deleted file mode 100644 index 0177685738..0000000000 --- a/template/multi-platform-lua/proj.android/build_native.cmd +++ /dev/null @@ -1,86 +0,0 @@ -@echo off - -set APPNAME="HelloLua" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy common luaScript -xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-lua/proj.android/build_native.py b/template/multi-platform-lua/proj.android/build_native.py new file mode 100755 index 0000000000..c1fe04ac28 --- /dev/null +++ b/template/multi-platform-lua/proj.android/build_native.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # lua project should copy lua script + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/lua/script") + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-lua/proj.android/build_native.sh b/template/multi-platform-lua/proj.android/build_native.sh deleted file mode 100755 index 930a9e5249..0000000000 --- a/template/multi-platform-lua/proj.android/build_native.sh +++ /dev/null @@ -1,102 +0,0 @@ -APPNAME="HelloLua" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy common luaScript -for file in "$APP_ROOT"/../../cocos/scripting/lua/script/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi \ No newline at end of file From cde79a9724bd8a0fb9dbdc47d58c3adb387e87ab Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 4 Nov 2013 18:01:42 +0800 Subject: [PATCH 036/197] use -j10 to build android samples --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 5cd83ad826..54cd858c49 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n NDK_DEBUG=0 all + ./android-build.py -n NDK_DEBUG=0 -j10 all # Build template # echo "Building template ..." From 46710c5f06d656177cdcd920cd1529291423ad46 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 4 Nov 2013 19:26:34 +0800 Subject: [PATCH 037/197] issue #2771: delay load --- cocos/physics/CCPhysicsWorld.cpp | 270 ++++++++++++------ cocos/physics/CCPhysicsWorld.h | 34 ++- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 15 + .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 8 + 4 files changed, 238 insertions(+), 89 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1cd2b936c5..913713277b 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -183,6 +183,12 @@ bool PhysicsWorld::init(Scene& scene) { do { + _delayAddBodies = Array::create(); + _delayRemoveBodies = Array::create(); + CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); + _delayAddBodies->retain(); + _delayRemoveBodies->retain(); + _info = new PhysicsWorldInfo(); CC_BREAK_IF(_info == nullptr); _bodies = Array::create(); @@ -206,20 +212,99 @@ bool PhysicsWorld::init(Scene& scene) return false; } +void PhysicsWorld::delayTestAddBody(PhysicsBody* body) +{ + if (_delayRemoveBodies->getIndexOfObject(body) != UINT_MAX) + { + _delayRemoveBodies->removeObject(body); + return; + } + + if (_info->space->locked_private) + { + if (_delayAddBodies->getIndexOfObject(body) == UINT_MAX) + { + _delayAddBodies->addObject(body); + _delayDirty = true; + } + }else + { + realAddBody(body); + } +} + +void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) +{ + if (_delayAddBodies->getIndexOfObject(body) != UINT_MAX) + { + _delayAddBodies->removeObject(body); + return; + } + + if (_info->space->locked_private) + { + if (_delayRemoveBodies->getIndexOfObject(body) == UINT_MAX) + { + _delayRemoveBodies->addObject(body); + _delayDirty = true; + } + }else + { + realRemoveBody(body); + } +} + +void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) +{ + auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); + if (it != _delayRemoveJoints.end()) + { + _delayRemoveJoints.erase(it); + return; + } + + if (_info->space->locked_private) + { + if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) + { + _delayAddJoints.push_back(joint); + _delayDirty = true; + } + }else + { + realAddJoint(joint); + } +} + +void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) +{ + auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); + if (it != _delayAddJoints.end()) + { + _delayAddJoints.erase(it); + return; + } + + if (_info->space->locked_private) + { + if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) + { + _delayRemoveJoints.push_back(joint); + _delayDirty = true; + } + }else + { + realRemoveJoint(joint); + } +} + void PhysicsWorld::addJoint(PhysicsJoint* joint) { auto it = std::find(_joints.begin(), _joints.end(), joint); if (it == _joints.end()) { - for (auto subjoint : joint->_info->joints) - { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceAddConstraint(_info->space, subjoint); - } - } - + delayTestAddJoint(joint); _joints.push_back(joint); } @@ -231,14 +316,7 @@ void PhysicsWorld::removeJoint(PhysicsJoint* joint) if (it != _joints.end()) { - for (auto subjoint : joint->_info->joints) - { - if (cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceRemoveConstraint(_info->space, subjoint); - } - } - + delayTestRemoveJoint(*it); _joints.remove(joint); } } @@ -247,13 +325,7 @@ void PhysicsWorld::removeAllJoints() { for (auto joint : _joints) { - for (auto subjoint : joint->_info->joints) - { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceRemoveConstraint(_info->space, subjoint); - } - } + delayTestRemoveJoint(joint); } _joints.clear(); @@ -263,28 +335,22 @@ PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) { for (auto cps : shape->_info->shapes) { - if (cpSpaceContainsShape(_info->space, cps)) - { - continue; - } - - if (cpBodyIsStatic(shape->getBody()->_info->body)) - { - cpSpaceAddStaticShape(_info->space, cps); - } - else - { - cpSpaceAddShape(_info->space, cps); - } + _info->addShape(cps); } return shape; } -PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) +void PhysicsWorld::realAddJoint(PhysicsJoint *joint) +{ + for (auto subjoint : joint->_info->joints) + { + _info->addJoint(subjoint); + } +} + +void PhysicsWorld::realAddBody(PhysicsBody* body) { - CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() != this && body->getWorld() != nullptr) { body->removeFromWorld(); @@ -303,7 +369,7 @@ PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) // add body to space if (body->isDynamic()) { - cpSpaceAddBody(_info->space, body->_info->body); + _info->addBody(body->_info->body); } // add shapes to space @@ -312,13 +378,38 @@ PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) addShape(dynamic_cast(shape)); } } +} + +PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) +{ + CCASSERT(body != nullptr, "the body can not be nullptr"); + delayTestAddBody(body); _bodies->addObject(body); return body; } void PhysicsWorld::removeBody(PhysicsBody* body) +{ + delayTestRemoveBody(body); + _bodies->removeObject(body); +} + +void PhysicsWorld::removeBodyByTag(int tag) +{ + for (Object* obj : *_bodies) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == tag) + { + removeBody(body); + return; + } + } +} + +void PhysicsWorld::realRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -346,25 +437,16 @@ void PhysicsWorld::removeBody(PhysicsBody* body) } // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } + _info->removeBody(body->_info->body); body->_world = nullptr; - _bodies->removeObject(body); } -void PhysicsWorld::removeBodyByTag(int tag) +void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) { - for (Object* obj : *_bodies) + for (auto subjoint : joint->_info->joints) { - PhysicsBody* body = dynamic_cast(obj); - if (body->getTag() == tag) - { - removeBody(body); - return; - } + _info->removeJoint(subjoint); } } @@ -372,33 +454,7 @@ void PhysicsWorld::removeAllBodies() { for (Object* obj : *_bodies) { - PhysicsBody* body = dynamic_cast(obj); - - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - - // remove joints - for (auto joint : body->_joints) - { - removeJoint(joint); - } - - // remove shaps - for (auto shape : *body->getShapes()) - { - removeShape(dynamic_cast(shape)); - } - - // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } - - body->_world = nullptr; + delayTestRemoveBody(dynamic_cast(obj)); } _bodies->removeAllObjects(); @@ -416,8 +472,57 @@ void PhysicsWorld::removeShape(PhysicsShape* shape) } } +void PhysicsWorld::updateBodies() +{ + if (_info->space->locked_private) + { + return; + } + + for (auto body : *_delayAddBodies) + { + realAddBody(dynamic_cast(body)); + } + + for (auto body : *_delayRemoveBodies) + { + realRemoveBody(dynamic_cast(body)); + } + + _delayAddBodies->removeAllObjects(); + _delayRemoveBodies->removeAllObjects(); +} + +void PhysicsWorld::updateJoints() +{ + if (_info->space->locked_private) + { + return; + } + + for (auto joint : _delayAddJoints) + { + realAddJoint(joint); + } + + for (auto joint : _delayRemoveJoints) + { + realRemoveJoint(joint); + } + + _delayAddJoints.clear(); + _delayRemoveJoints.clear(); +} + void PhysicsWorld::update(float delta) { + if (_delayDirty) + { + updateBodies(); + updateJoints(); + _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); + } + for (auto body : *_bodies) { body->update(delta); @@ -804,8 +909,11 @@ PhysicsWorld::PhysicsWorld() , _info(nullptr) , _bodies(nullptr) , _scene(nullptr) +, _delayDirty(false) , _debugDraw(false) , _drawNode(nullptr) +, _delayAddBodies(nullptr) +, _delayRemoveBodies(nullptr) { } @@ -814,6 +922,8 @@ PhysicsWorld::~PhysicsWorld() { removeAllBodies(); removeAllJoints(); + CC_SAFE_RELEASE(_delayRemoveBodies); + CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index e719dce2c4..2d4e7def57 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -29,6 +29,7 @@ #define __CCPHYSICS_WORLD_H__ #include +#include #include "CCObject.h" #include "CCGeometry.h" @@ -86,11 +87,15 @@ class PhysicsWorld { public: /** Adds a joint to the physics world.*/ - void addJoint(PhysicsJoint* joint); + virtual void addJoint(PhysicsJoint* joint); /** Removes a joint from the physics world.*/ - void removeJoint(PhysicsJoint* joint); + virtual void removeJoint(PhysicsJoint* joint); /** Remove all joints from the physics world.*/ - void removeAllJoints(); + virtual void removeAllJoints(); + + virtual void removeBody(PhysicsBody* body); + virtual void removeBodyByTag(int tag); + virtual void removeAllBodies(); void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); @@ -115,10 +120,6 @@ public: /** set the debug draw */ inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } - virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); - virtual void removeAllBodies(); - protected: static PhysicsWorld* create(Scene& scene); bool init(Scene& scene); @@ -132,25 +133,40 @@ protected: virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); virtual void drawWithJoint(DrawNode* node, PhysicsJoint* joint); - virtual int collisionBeginCallback(PhysicsContact& contact); virtual int collisionPreSolveCallback(PhysicsContact& contact); virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); + virtual void realAddBody(PhysicsBody* body); + virtual void realRemoveBody(PhysicsBody* body); + virtual void realAddJoint(PhysicsJoint* joint); + virtual void realRemoveJoint(PhysicsJoint* joint); + virtual void delayTestAddBody(PhysicsBody* body); + virtual void delayTestRemoveBody(PhysicsBody* body); + virtual void delayTestAddJoint(PhysicsJoint* joint); + virtual void delayTestRemoveJoint(PhysicsJoint* joint); + virtual void updateBodies(); + virtual void updateJoints(); + protected: Point _gravity; float _speed; PhysicsWorldInfo* _info; - //EventListenerPhysicsContact* _listener; Array* _bodies; std::list _joints; Scene* _scene; + bool _delayDirty; bool _debugDraw; DrawNode* _drawNode; + Array* _delayAddBodies; + Array* _delayRemoveBodies; + std::vector _delayAddJoints; + std::vector _delayRemoveJoints; + protected: PhysicsWorld(); virtual ~PhysicsWorld(); diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index f58eebadf2..fecf2009aa 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -26,6 +26,21 @@ #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN +#define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ +void PhysicsWorldInfo::add##name(cp##type* data) \ +{ \ + if (!cpSpaceContains##type(space, data)) cpSpaceAdd##type(space, data); \ +} \ +\ +void PhysicsWorldInfo::remove##name(cp##type* data) \ +{ \ + if (cpSpaceContains##type(space, data)) cpSpaceRemove##type(space, data); \ +} \ + +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Body, Body) +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) + PhysicsWorldInfo::PhysicsWorldInfo() { space = cpSpaceNew(); diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 158f074c77..5e6c78bc97 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -30,6 +30,7 @@ #include "chipmunk.h" #include "CCPlatformMacros.h" +#include NS_CC_BEGIN class PhysicsWorldInfo @@ -37,6 +38,13 @@ class PhysicsWorldInfo public: cpSpace* space; + void addShape(cpShape* shape); + void removeShape(cpShape* shape); + void addBody(cpBody* body); + void removeBody(cpBody* body); + void addJoint(cpConstraint* joint); + void removeJoint(cpConstraint* joint); + private: PhysicsWorldInfo(); ~PhysicsWorldInfo(); From add96f63a6946fca576fc5d919bbd0d3959eb39d Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 14:40:07 +0800 Subject: [PATCH 038/197] Adding top level cmakefiles.txt --- CMakeLists.txt | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..512d1e916b --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,97 @@ +cmake_minimum_required(VERSION 2.6) +project (Cocos2dxSamples) + +# The version number +set(Cocos2dxSamples_VERSION_MAJOR 3) +set(Cocos2dxSamples_VERSION_MINOR 0) + +add_definitions(-DLINUX) + +# debug +message( "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}" ) +if ( "${CMAKE_BUILD_TYPE}" STREQUAL "DEBUG" ) + add_definitions(-D_DEBUG) +endif() + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") + +include_directories( + cocos/2d + cocos/2d/platform + cocos/2d/platform/linux + cocos/base + cocos/physics + cocos/math/kazmath/include + external/jpeg/include/linux + external/tiff/include/linux + external/webp/include/linux + external/glfw3/include/linux + external/tinyxml2 + external/unzip + external/chipmunk/include/chipmunk + external/freetype2/include/linux +) + +link_directories( + /usr/local/lib + ${CMAKE_SOURCE_DIR}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR} +) + +set(COCOS_LIBRARIES + cocos2d + cocosbase + chipmunk_static + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + glfw + GLEW + GL + rt + z +) + +# kazmath +add_subdirectory(cocos/math/kazmath) + +# chipmunk library +set(BUILD_STATIC 1) + +# chipmunk library +add_subdirectory(external/chipmunk/src) + +# unzip library +add_subdirectory(external/unzip) + +# tinyxml2 library +add_subdirectory(external/tinyxml2) + +# cocos base library +add_subdirectory(cocos/base) + +# cocos physics sources +#add_subdirectory(cocos/physics) + +# cocos 2d library +add_subdirectory(cocos/2d) + +# sample HelloCpp +add_subdirectory(samples/Cpp/HelloCpp) + From 8cdd1af98278f0a9593c3bd94734cd66bb517e68 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 14:41:04 +0800 Subject: [PATCH 039/197] HelloCpp CMakeLists.txt --- samples/Cpp/HelloCpp/CMakeLists.txt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 samples/Cpp/HelloCpp/CMakeLists.txt diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt new file mode 100644 index 0000000000..f22b681d8f --- /dev/null +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -0,0 +1,14 @@ +set(SAMPLE_NAME hellocpp) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp + Classes/HelloWorldScene.cpp +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) From 8676523433a1fd9556681b73a7c3f0600b5dfce2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 14:44:54 +0800 Subject: [PATCH 040/197] Adding CMakeLists.txt --- cocos/2d/CMakeLists.txt | 125 ++++++++++++++++++++++++++++++ cocos/base/CMakeLists.txt | 20 +++++ cocos/math/kazmath/CMakeLists.txt | 17 ++++ cocos/physics/CMakeLists.txt | 17 ++++ external/tinyxml2/CMakeLists.txt | 7 ++ external/unzip/CMakeLists.txt | 8 ++ 6 files changed, 194 insertions(+) create mode 100644 cocos/2d/CMakeLists.txt create mode 100644 cocos/base/CMakeLists.txt create mode 100644 cocos/math/kazmath/CMakeLists.txt create mode 100644 cocos/physics/CMakeLists.txt create mode 100644 external/tinyxml2/CMakeLists.txt create mode 100644 external/unzip/CMakeLists.txt diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt new file mode 100644 index 0000000000..fdcd28a564 --- /dev/null +++ b/cocos/2d/CMakeLists.txt @@ -0,0 +1,125 @@ +set(COCOS2D_SRC + CCAction.cpp + CCActionCamera.cpp + CCActionEase.cpp + CCActionGrid.cpp + CCActionGrid3D.cpp + CCActionInstant.cpp + CCActionInterval.cpp + CCActionManager.cpp + CCActionPageTurn3D.cpp + CCActionProgressTimer.cpp + CCActionTiledGrid.cpp + CCActionCatmullRom.cpp + CCActionTween.cpp + CCAtlasNode.cpp + CCNode.cpp + CCEventAcceleration.cpp + CCEventListenerAcceleration.cpp + CCEvent.cpp + CCEventDispatcher.cpp + CCEventListener.cpp + CCEventKeyboard.cpp + CCEventListenerKeyboard.cpp + CCEventMouse.cpp + CCEventListenerMouse.cpp + CCTouch.cpp + CCEventTouch.cpp + CCEventListenerTouch.cpp + CCEventCustom.cpp + CCEventListenerCustom.cpp + CCDrawingPrimitives.cpp + CCDrawNode.cpp + CCGrabber.cpp + CCGrid.cpp + CCFont.cpp + CCFontAtlas.cpp + CCFontAtlasCache.cpp + CCFontAtlasFactory.cpp + CCFontDefinition.cpp + CCFontFNT.cpp + CCFontFreeType.cpp + CCLabel.cpp + CCLabelAtlas.cpp + CCLabelBMFont.cpp + CCLabelTTF.cpp + CCLabelTextFormatter.cpp + CCTextImage.cpp + CCLayer.cpp + CCScene.cpp + CCTransition.cpp + CCTransitionPageTurn.cpp + CCTransitionProgress.cpp + CCMenu.cpp + CCMenuItem.cpp + CCMotionStreak.cpp + CCProgressTimer.cpp + CCClippingNode.cpp + CCRenderTexture.cpp + CCParticleExamples.cpp + CCParticleSystem.cpp + CCParticleSystemQuad.cpp + CCParticleBatchNode.cpp + CCScriptSupport.cpp + CCAnimation.cpp + CCAnimationCache.cpp + CCSprite.cpp + CCSpriteBatchNode.cpp + CCSpriteFrame.cpp + CCSpriteFrameCache.cpp + ccUTF8.cpp + CCProfiling.cpp + CCUserDefault.cpp + TransformUtils.cpp + base64.cpp + ccUtils.cpp + CCVertex.cpp + CCNotificationCenter.cpp + TGAlib.cpp + ZipUtils.cpp + ccCArray.cpp + CCComponent.cpp + CCComponentContainer.cpp + CCIMEDispatcher.cpp + CCTextFieldTTF.cpp + CCTexture2D.cpp + CCTextureAtlas.cpp + CCTextureCache.cpp + CCParallaxNode.cpp + CCTMXLayer.cpp + CCTMXObjectGroup.cpp + CCTMXTiledMap.cpp + CCTMXXMLParser.cpp + CCTileMapAtlas.cpp + CCGLProgram.cpp + ccGLStateCache.cpp + CCShaderCache.cpp + ccShaders.cpp + CCCamera.cpp + CCConfiguration.cpp + CCDirector.cpp + CCScheduler.cpp + ccFPSImages.c + ccTypes.cpp + cocos2d.cpp + CCDeprecated.cpp + platform/CCSAXParser.cpp + platform/CCThread.cpp + platform/CCEGLViewProtocol.cpp + platform/CCFileUtils.cpp + platform/linux/CCStdC.cpp + platform/linux/CCFileUtilsLinux.cpp + platform/linux/CCCommon.cpp + platform/linux/CCApplication.cpp + platform/linux/CCEGLView.cpp + platform/linux/CCImage.cpp + platform/linux/CCDevice.cpp +) + +include(../physics/CMakeLists.txt) + +add_library(cocos2d STATIC + ${COCOS2D_SRC} + ${COCOS_PHYSICS_SRC} +) + diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt new file mode 100644 index 0000000000..c46e07c114 --- /dev/null +++ b/cocos/base/CMakeLists.txt @@ -0,0 +1,20 @@ +set(COCOS_BASE_SRC + CCAffineTransform.cpp + CCAutoreleasePool.cpp + CCGeometry.cpp + CCNS.cpp + CCObject.cpp + CCSet.cpp + CCArray.cpp + CCDictionary.cpp + CCString.cpp + CCDataVisitor.cpp + CCData.cpp + etc1.cpp + s3tc.cpp + atitc.cpp +) + +add_library(cocosbase STATIC + ${COCOS_BASE_SRC} +) diff --git a/cocos/math/kazmath/CMakeLists.txt b/cocos/math/kazmath/CMakeLists.txt new file mode 100644 index 0000000000..1dc636037d --- /dev/null +++ b/cocos/math/kazmath/CMakeLists.txt @@ -0,0 +1,17 @@ + +SET(KAZMATH_SOURCES + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/mat4.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/mat3.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/plane.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec4.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/quaternion.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec2.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec3.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/utility.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/aabb.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/ray2.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/mat4stack.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/matrix.c + ) + +ADD_SUBDIRECTORY(src) \ No newline at end of file diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt new file mode 100644 index 0000000000..2ca5a7f532 --- /dev/null +++ b/cocos/physics/CMakeLists.txt @@ -0,0 +1,17 @@ +set(COCOS_PHYSICS_SRC + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsBody.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsContact.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsShape.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsJoint.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsWorld.cpp +) diff --git a/external/tinyxml2/CMakeLists.txt b/external/tinyxml2/CMakeLists.txt new file mode 100644 index 0000000000..42822a3bc4 --- /dev/null +++ b/external/tinyxml2/CMakeLists.txt @@ -0,0 +1,7 @@ +set(TINYXML2_SRC + tinyxml2.cpp +) + +add_library(tinyxml2 STATIC + ${TINYXML2_SRC} +) diff --git a/external/unzip/CMakeLists.txt b/external/unzip/CMakeLists.txt new file mode 100644 index 0000000000..8d15111c8e --- /dev/null +++ b/external/unzip/CMakeLists.txt @@ -0,0 +1,8 @@ +set(UNZIP_SRC + ioapi.cpp + unzip.cpp +) + +add_library(unzip STATIC + ${UNZIP_SRC} +) From e560de6e4eb41e4c71afca0a94d3997cbb2e8cdf Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 16:31:52 +0800 Subject: [PATCH 041/197] HelloCpp works. --- CMakeLists.txt | 27 ++++++-------- build/BuildHelpers.CMakeLists.txt | 37 ++++++++++++++++++++ cocos/2d/platform/linux/CCFileUtilsLinux.cpp | 2 +- samples/CMakeLists.txt | 4 +++ samples/Cpp/HelloCpp/CMakeLists.txt | 10 ++++++ 5 files changed, 63 insertions(+), 17 deletions(-) create mode 100644 build/BuildHelpers.CMakeLists.txt create mode 100644 samples/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 512d1e916b..2e92c43ba0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,13 +5,16 @@ project (Cocos2dxSamples) set(Cocos2dxSamples_VERSION_MAJOR 3) set(Cocos2dxSamples_VERSION_MINOR 0) -add_definitions(-DLINUX) +include(build/BuildHelpers.CMakeLists.txt) -# debug -message( "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}" ) -if ( "${CMAKE_BUILD_TYPE}" STREQUAL "DEBUG" ) - add_definitions(-D_DEBUG) -endif() +set(CMAKE_BUILE_TYPE DEBUG) +set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") + +add_definitions(-DLINUX) # architecture if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) @@ -20,9 +23,6 @@ else() set(ARCH_DIR "32-bit") endif() -set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") -set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") - include_directories( cocos/2d cocos/2d/platform @@ -73,8 +73,6 @@ add_subdirectory(cocos/math/kazmath) # chipmunk library set(BUILD_STATIC 1) - -# chipmunk library add_subdirectory(external/chipmunk/src) # unzip library @@ -86,12 +84,9 @@ add_subdirectory(external/tinyxml2) # cocos base library add_subdirectory(cocos/base) -# cocos physics sources -#add_subdirectory(cocos/physics) - # cocos 2d library add_subdirectory(cocos/2d) -# sample HelloCpp -add_subdirectory(samples/Cpp/HelloCpp) +# build samples +add_subdirectory(samples) diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt new file mode 100644 index 0000000000..c60446bd30 --- /dev/null +++ b/build/BuildHelpers.CMakeLists.txt @@ -0,0 +1,37 @@ + +# Copies files for the given game into the target res directory +# GAME_NAME name of the game +# REL_DIR to which directory these files are relative +# SRC_FILES which files from the REL_DIR to copy (GLOB) +macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES DST) + file( GLOB_RECURSE RES_FILES RELATIVE ${REL_DIR} ${SRC_FILES} ) + + set(ALL_FILES) + foreach(SRC_FILE ${RES_FILES}) + add_custom_command( + OUTPUT "${DST}/${SRC_FILE}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${REL_DIR}/${SRC_FILE}" + "${DST}/${SRC_FILE}" + COMMENT "Copy ${SRC_FILE}" + ) + list(APPEND ALL_FILES "${DST}/${SRC_FILE}" ) + endforeach() + # create target for copying these files + add_custom_target( ${GAME_RES_TARGET} DEPENDS ${ALL_FILES} ) +endmacro() + +# convenience to call above with current directory and everything in "res" +macro(COPY_RES GAME_NAME CRG_PATTERN DST) + # a target for all addition asserts (will be done in default compile, but if you target the executable + # it won't be done -- good for testing) + add_custom_target( ${GAME_NAME}_ASSETS ALL ) + + COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_CORE_RES + ${CMAKE_CURRENT_SOURCE_DIR} + "${CRG_PATTERN}" + ${DST} + ) + add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_CORE_RES ) +endmacro() + diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp index 227c59b0ba..dc3fb5b513 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp @@ -49,7 +49,7 @@ bool FileUtilsLinux::init() fullpath[length] = '\0'; std::string appPath = fullpath; _defaultResRootPath = appPath.substr(0, appPath.find_last_of("/")); - _defaultResRootPath += "/../../../Resources/"; + _defaultResRootPath += "/Resources/"; // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. const char* xdg_config_path = getenv("XDG_CONFIG_HOME"); diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt new file mode 100644 index 0000000000..d8f27098e1 --- /dev/null +++ b/samples/CMakeLists.txt @@ -0,0 +1,4 @@ + +add_subdirectory(Cpp/HelloCpp) +add_subdirectory(Cpp/TestCpp) + diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index f22b681d8f..6ac2ed3548 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -12,3 +12,13 @@ add_executable(${SAMPLE_NAME} ) target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) + +set(SAMPLE_BIN_DIR ${CMAKE_BINARY_DIR}/bin) + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}/HelloCpp") + +message(STATUS "Hello.........." ${CMAKE_BINARY_DIR}) + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}/HelloCpp") + From 922924e1aba1cf3fee57225e1d6e27a7db2b5a1a Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 18:07:34 +0800 Subject: [PATCH 042/197] TestCpp is ok. --- CMakeLists.txt | 29 ++- cocos/audio/CMakeLists.txt | 16 ++ .../cocosbuilder/CMakeLists.txt | 33 ++++ .../editor-support/cocostudio/CMakeLists.txt | 43 +++++ cocos/editor-support/spine/CMakeLists.txt | 31 ++++ cocos/gui/CMakeLists.txt | 29 +++ cocos/network/CMakeLists.txt | 8 + extensions/CMakeLists.txt | 34 ++++ external/Box2D/CMakeLists.txt | 55 ++++++ external/json/CMakeLists.txt | 14 ++ samples/CMakeLists.txt | 3 +- samples/Cpp/HelloCpp/CMakeLists.txt | 8 +- samples/Cpp/TestCpp/CMakeLists.txt | 165 ++++++++++++++++++ 13 files changed, 461 insertions(+), 7 deletions(-) create mode 100644 cocos/audio/CMakeLists.txt create mode 100644 cocos/editor-support/cocosbuilder/CMakeLists.txt create mode 100644 cocos/editor-support/cocostudio/CMakeLists.txt create mode 100644 cocos/editor-support/spine/CMakeLists.txt create mode 100644 cocos/gui/CMakeLists.txt create mode 100644 cocos/network/CMakeLists.txt create mode 100644 extensions/CMakeLists.txt create mode 100644 external/Box2D/CMakeLists.txt create mode 100644 external/json/CMakeLists.txt create mode 100644 samples/Cpp/TestCpp/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e92c43ba0..5c20488a6b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,7 @@ set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") -add_definitions(-DLINUX) +add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) # architecture if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) @@ -24,16 +24,22 @@ set(ARCH_DIR "32-bit") endif() include_directories( + . + cocos + cocos/audio/include cocos/2d cocos/2d/platform cocos/2d/platform/linux cocos/base cocos/physics + cocos/editor-support cocos/math/kazmath/include + external external/jpeg/include/linux external/tiff/include/linux external/webp/include/linux external/glfw3/include/linux + external/curl/include/linux/${ARCH_DIR} external/tinyxml2 external/unzip external/chipmunk/include/chipmunk @@ -46,9 +52,12 @@ link_directories( ${CMAKE_SOURCE_DIR}/external/tiff/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/curl/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/cocos/audio/third-party/fmod/lib64/api/lib ) set(COCOS_LIBRARIES + audio cocos2d cocosbase chipmunk_static @@ -75,18 +84,36 @@ add_subdirectory(cocos/math/kazmath) set(BUILD_STATIC 1) add_subdirectory(external/chipmunk/src) +# box2d library +add_subdirectory(external/Box2D) + # unzip library add_subdirectory(external/unzip) # tinyxml2 library add_subdirectory(external/tinyxml2) +# audio +add_subdirectory(cocos/audio) + # cocos base library add_subdirectory(cocos/base) # cocos 2d library add_subdirectory(cocos/2d) +add_subdirectory(cocos/gui) + +add_subdirectory(cocos/network) + +add_subdirectory(cocos/editor-support/spine) +add_subdirectory(cocos/editor-support/cocosbuilder) +add_subdirectory(cocos/editor-support/cocostudio) + +add_subdirectory(extensions) + +add_subdirectory(external/json) + # build samples add_subdirectory(samples) diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt new file mode 100644 index 0000000000..79f84aa217 --- /dev/null +++ b/cocos/audio/CMakeLists.txt @@ -0,0 +1,16 @@ +set(AUDIO_SRC + linux/SimpleAudioEngineFMOD.cpp + linux/FmodAudioPlayer.cpp +) + +include_directories( + third-party/fmod/lib64/api/inc +) + +add_library(audio STATIC + ${AUDIO_SRC} +) + +target_link_libraries(audio + fmodex64 +) \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CMakeLists.txt b/cocos/editor-support/cocosbuilder/CMakeLists.txt new file mode 100644 index 0000000000..57f1113de6 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/CMakeLists.txt @@ -0,0 +1,33 @@ +set(CCB_SRC + CCBFileLoader.cpp + CCMenuItemImageLoader.cpp + CCBReader.cpp + CCMenuItemLoader.cpp + CCControlButtonLoader.cpp + CCNodeLoader.cpp + CCControlLoader.cpp + CCNodeLoaderLibrary.cpp + CCLabelBMFontLoader.cpp + CCParticleSystemQuadLoader.cpp + CCLabelTTFLoader.cpp + CCScale9SpriteLoader.cpp + CCLayerColorLoader.cpp + CCScrollViewLoader.cpp + CCLayerGradientLoader.cpp + CCSpriteLoader.cpp + CCLayerLoader.cpp + CCBAnimationManager.cpp + CCBKeyframe.cpp + CCBSequence.cpp + CCBSequenceProperty.cpp + CCBValue.cpp + CCNode+CCBRelativePositioning.cpp +) + +include_directories( + .. +) + +add_library(cocosbuilder STATIC + ${CCB_SRC} +) diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt new file mode 100644 index 0000000000..f86093b2ea --- /dev/null +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -0,0 +1,43 @@ +set(CS_SRC + CCActionFrame.cpp + CCActionFrameEasing.cpp + CCActionManagerEx.cpp + CCActionNode.cpp + CCActionObject.cpp + CCArmature.cpp + CCBone.cpp + CCArmatureAnimation.cpp + CCProcessBase.cpp + CCTween.cpp + CCDatas.cpp + CCBatchNode.cpp + CCDecorativeDisplay.cpp + CCDisplayFactory.cpp + CCDisplayManager.cpp + CCSkin.cpp + CCColliderDetector.cpp + CCArmatureDataManager.cpp + CCArmatureDefine.cpp + CCDataReaderHelper.cpp + CCSpriteFrameCacheHelper.cpp + CCTransformHelp.cpp + CCTweenFunction.cpp + CCUtilMath.cpp + CCComAttribute.cpp + CCComAudio.cpp + CCComController.cpp + CCComRender.cpp + CCInputDelegate.cpp + CSContentJsonDictionary.cpp + DictionaryHelper.cpp + CCSGUIReader.cpp + CCSSceneReader.cpp +) + +include_directories( + .. +) + +add_library(cocostudio STATIC + ${CS_SRC} +) diff --git a/cocos/editor-support/spine/CMakeLists.txt b/cocos/editor-support/spine/CMakeLists.txt new file mode 100644 index 0000000000..e76d1ea6f8 --- /dev/null +++ b/cocos/editor-support/spine/CMakeLists.txt @@ -0,0 +1,31 @@ +set(SPINE_SRC + Animation.cpp + AnimationState.cpp + AnimationStateData.cpp + Atlas.cpp + AtlasAttachmentLoader.cpp + Attachment.cpp + AttachmentLoader.cpp + Bone.cpp + BoneData.cpp + Json.cpp + RegionAttachment.cpp + Skeleton.cpp + SkeletonData.cpp + SkeletonJson.cpp + Skin.cpp + Slot.cpp + SlotData.cpp + extension.cpp + spine-cocos2dx.cpp + CCSkeleton.cpp + CCSkeletonAnimation.cpp +) + +include_directories( + .. +) + +add_library(spine STATIC + ${SPINE_SRC} +) diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt new file mode 100644 index 0000000000..069ce8a960 --- /dev/null +++ b/cocos/gui/CMakeLists.txt @@ -0,0 +1,29 @@ +set(GUI_SRC + UIRootWidget.cpp + UIWidget.cpp + Layout.cpp + LayoutParameter.cpp + UILayoutDefine.cpp + CocosGUI.cpp + UIHelper.cpp + UIInputManager.cpp + UILayer.cpp + UIDragPanel.cpp + UIListView.cpp + UIPageView.cpp + UIScrollView.cpp + UIButton.cpp + UICheckBox.cpp + UIImageView.cpp + UILabel.cpp + UILabelAtlas.cpp + UILabelBMFont.cpp + UILoadingBar.cpp + UISlider.cpp + UITextField.cpp +) + +add_library(gui STATIC + ${GUI_SRC} +) + diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt new file mode 100644 index 0000000000..8217122fa9 --- /dev/null +++ b/cocos/network/CMakeLists.txt @@ -0,0 +1,8 @@ +set(NETWORK_SRC + HttpClient.cpp + SocketIO.cpp +) + +add_library(network STATIC + ${NETWORK_SRC} +) diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt new file mode 100644 index 0000000000..5b85c4657b --- /dev/null +++ b/extensions/CMakeLists.txt @@ -0,0 +1,34 @@ +set(EXTENSIONS_SRC + assets-manager/AssetsManager.cpp + GUI/CCControlExtension/CCControl.cpp + GUI/CCControlExtension/CCControlButton.cpp + GUI/CCControlExtension/CCControlColourPicker.cpp + GUI/CCControlExtension/CCControlHuePicker.cpp + GUI/CCControlExtension/CCControlPotentiometer.cpp + GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp + GUI/CCControlExtension/CCControlSlider.cpp + GUI/CCControlExtension/CCControlStepper.cpp + GUI/CCControlExtension/CCControlSwitch.cpp + GUI/CCControlExtension/CCControlUtils.cpp + GUI/CCControlExtension/CCInvocation.cpp + GUI/CCControlExtension/CCScale9Sprite.cpp + GUI/CCEditBox/CCEditBox.cpp + GUI/CCEditBox/CCEditBoxImplAndroid.cpp + GUI/CCEditBox/CCEditBoxImplNone.cpp + GUI/CCEditBox/CCEditBoxImplTizen.cpp + GUI/CCEditBox/CCEditBoxImplWin.cpp + GUI/CCScrollView/CCScrollView.cpp + GUI/CCScrollView/CCSorting.cpp + GUI/CCScrollView/CCTableView.cpp + GUI/CCScrollView/CCTableViewCell.cpp + physics-nodes/CCPhysicsDebugNode.cpp + physics-nodes/CCPhysicsSprite.cpp +) + +include_directories( + .. +) + +add_library(extensions STATIC + ${EXTENSIONS_SRC} +) diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt new file mode 100644 index 0000000000..94a1fffb50 --- /dev/null +++ b/external/Box2D/CMakeLists.txt @@ -0,0 +1,55 @@ +set(BOX2D_SRC + Collision/Shapes/b2ChainShape.cpp + Collision/Shapes/b2CircleShape.cpp + Collision/Shapes/b2EdgeShape.cpp + Collision/Shapes/b2PolygonShape.cpp + Collision/b2BroadPhase.cpp + Collision/b2CollideCircle.cpp + Collision/b2CollideEdge.cpp + Collision/b2CollidePolygon.cpp + Collision/b2Collision.cpp + Collision/b2Distance.cpp + Collision/b2DynamicTree.cpp + Collision/b2TimeOfImpact.cpp + Common/b2BlockAllocator.cpp + Common/b2Draw.cpp + Common/b2Math.cpp + Common/b2Settings.cpp + Common/b2StackAllocator.cpp + Common/b2Timer.cpp + Dynamics/Contacts/b2ChainAndCircleContact.cpp + Dynamics/Contacts/b2ChainAndPolygonContact.cpp + Dynamics/Contacts/b2CircleContact.cpp + Dynamics/Contacts/b2Contact.cpp + Dynamics/Contacts/b2ContactSolver.cpp + Dynamics/Contacts/b2EdgeAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndPolygonContact.cpp + Dynamics/Contacts/b2PolygonAndCircleContact.cpp + Dynamics/Contacts/b2PolygonContact.cpp + Dynamics/Joints/b2DistanceJoint.cpp + Dynamics/Joints/b2FrictionJoint.cpp + Dynamics/Joints/b2GearJoint.cpp + Dynamics/Joints/b2Joint.cpp + Dynamics/Joints/b2MouseJoint.cpp + Dynamics/Joints/b2PrismaticJoint.cpp + Dynamics/Joints/b2PulleyJoint.cpp + Dynamics/Joints/b2RevoluteJoint.cpp + Dynamics/Joints/b2RopeJoint.cpp + Dynamics/Joints/b2WeldJoint.cpp + Dynamics/Joints/b2WheelJoint.cpp + Dynamics/b2Body.cpp + Dynamics/b2ContactManager.cpp + Dynamics/b2Fixture.cpp + Dynamics/b2Island.cpp + Dynamics/b2World.cpp + Dynamics/b2WorldCallbacks.cpp + Rope/b2Rope.cpp +) + +include_directories( + .. +) + +add_library(box2d STATIC + ${BOX2D_SRC} +) diff --git a/external/json/CMakeLists.txt b/external/json/CMakeLists.txt new file mode 100644 index 0000000000..257385a307 --- /dev/null +++ b/external/json/CMakeLists.txt @@ -0,0 +1,14 @@ +set(JSONCPP_SRC + json_reader.cpp + json_value.cpp + json_writer.cpp +) + +include_directories( + +) + +add_library(jsoncpp STATIC + ${JSONCPP_SRC} +) + diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index d8f27098e1..c3a9708207 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,4 +1,5 @@ -add_subdirectory(Cpp/HelloCpp) +#add_subdirectory(Cpp/HelloCpp) + add_subdirectory(Cpp/TestCpp) diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index 6ac2ed3548..22770fff8e 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -13,12 +13,10 @@ add_executable(${SAMPLE_NAME} target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) -set(SAMPLE_BIN_DIR ${CMAKE_BINARY_DIR}/bin) +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}/HelloCpp") + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") -message(STATUS "Hello.........." ${CMAKE_BINARY_DIR}) - -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}/HelloCpp") +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt new file mode 100644 index 0000000000..c567f1331a --- /dev/null +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -0,0 +1,165 @@ +set(SAMPLE_NAME testcpp) + +set(SAMPLE_SRC + Classes/AccelerometerTest/AccelerometerTest.cpp + Classes/ActionManagerTest/ActionManagerTest.cpp + Classes/ActionsEaseTest/ActionsEaseTest.cpp + Classes/ActionsProgressTest/ActionsProgressTest.cpp + Classes/ActionsTest/ActionsTest.cpp + Classes/Box2DTest/Box2dTest.cpp + Classes/Box2DTestBed/Box2dView.cpp + Classes/Box2DTestBed/GLES-Render.cpp + Classes/Box2DTestBed/Test.cpp + Classes/Box2DTestBed/TestEntries.cpp + Classes/BugsTest/Bug-1159.cpp + Classes/BugsTest/Bug-1174.cpp + Classes/BugsTest/Bug-350.cpp + Classes/BugsTest/Bug-422.cpp + Classes/BugsTest/Bug-458/Bug-458.cpp + Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp + Classes/BugsTest/Bug-624.cpp + Classes/BugsTest/Bug-886.cpp + Classes/BugsTest/Bug-899.cpp + Classes/BugsTest/Bug-914.cpp + Classes/BugsTest/BugsTest.cpp + Classes/ChipmunkTest/ChipmunkTest.cpp + Classes/ClickAndMoveTest/ClickAndMoveTest.cpp + Classes/ClippingNodeTest/ClippingNodeTest.cpp + Classes/CocosDenshionTest/CocosDenshionTest.cpp + Classes/CurlTest/CurlTest.cpp + Classes/CurrentLanguageTest/CurrentLanguageTest.cpp + Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp + Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp + Classes/EffectsTest/EffectsTest.cpp + Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp + Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp + Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp + Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp + Classes/ExtensionsTest/ExtensionsTest.cpp + Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp + Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp + Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp + Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp + Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp + Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp + Classes/FontTest/FontTest.cpp + Classes/IntervalTest/IntervalTest.cpp + Classes/KeyboardTest/KeyboardTest.cpp + Classes/InputTest/MouseTest.cpp + Classes/KeypadTest/KeypadTest.cpp + Classes/LabelTest/LabelTest.cpp + Classes/LabelTest/LabelTestNew.cpp + Classes/LayerTest/LayerTest.cpp + Classes/MenuTest/MenuTest.cpp + Classes/MotionStreakTest/MotionStreakTest.cpp + Classes/MutiTouchTest/MutiTouchTest.cpp + Classes/NodeTest/NodeTest.cpp + Classes/ParallaxTest/ParallaxTest.cpp + Classes/ParticleTest/ParticleTest.cpp + Classes/PerformanceTest/PerformanceAllocTest.cpp + Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp + Classes/PerformanceTest/PerformanceParticleTest.cpp + Classes/PerformanceTest/PerformanceSpriteTest.cpp + Classes/PerformanceTest/PerformanceTest.cpp + Classes/PerformanceTest/PerformanceTextureTest.cpp + Classes/PerformanceTest/PerformanceTouchesTest.cpp + Classes/PhysicsTest/PhysicsTest.cpp + Classes/RenderTextureTest/RenderTextureTest.cpp + Classes/RotateWorldTest/RotateWorldTest.cpp + Classes/SceneTest/SceneTest.cpp + Classes/SchedulerTest/SchedulerTest.cpp + Classes/ShaderTest/ShaderTest.cpp + Classes/ShaderTest/ShaderTest2.cpp + Classes/SpriteTest/SpriteTest.cpp + Classes/TextInputTest/TextInputTest.cpp + Classes/Texture2dTest/Texture2dTest.cpp + Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp + Classes/TextureCacheTest/TextureCacheTest.cpp + Classes/TileMapTest/TileMapTest.cpp + Classes/TouchesTest/Ball.cpp + Classes/TouchesTest/Paddle.cpp + Classes/TouchesTest/TouchesTest.cpp + Classes/TransitionsTest/TransitionsTest.cpp + Classes/UserDefaultTest/UserDefaultTest.cpp + Classes/ZwoptexTest/ZwoptexTest.cpp + Classes/FileUtilsTest/FileUtilsTest.cpp + Classes/SpineTest/SpineTest.cpp + Classes/DataVisitorTest/DataVisitorTest.cpp + Classes/ConfigurationTest/ConfigurationTest.cpp + Classes/controller.cpp + Classes/testBasic.cpp + Classes/AppDelegate.cpp + Classes/BaseTest.cpp + Classes/VisibleRect.cpp + proj.linux/main.cpp +) + +include_directories( + Classes +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} + gui + network + spine + cocostudio + cocosbuilder + extensions + ${COCOS_LIBRARIES} + box2d + jsoncpp + curl + rt +) + +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") + From c085412636cca7db4d28ecc00238d554ab831d44 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 19:14:29 +0800 Subject: [PATCH 043/197] [CMake] TestLua and HelloLua is ok. --- CMakeLists.txt | 6 +++++ cocos/scripting/CMakeLists.txt | 32 ++++++++++++++++++++++ external/lua/lua/CMakeLists.txt | 36 +++++++++++++++++++++++++ external/lua/tolua/CMakeLists.txt | 17 ++++++++++++ samples/CMakeLists.txt | 6 ++--- samples/Lua/HelloLua/CMakeLists.txt | 41 +++++++++++++++++++++++++++++ samples/Lua/TestLua/CMakeLists.txt | 41 +++++++++++++++++++++++++++++ 7 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 cocos/scripting/CMakeLists.txt create mode 100644 external/lua/lua/CMakeLists.txt create mode 100644 external/lua/tolua/CMakeLists.txt create mode 100644 samples/Lua/HelloLua/CMakeLists.txt create mode 100644 samples/Lua/TestLua/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 5c20488a6b..67dde5fa7f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,6 +34,7 @@ include_directories( cocos/physics cocos/editor-support cocos/math/kazmath/include + extensions external external/jpeg/include/linux external/tiff/include/linux @@ -114,6 +115,11 @@ add_subdirectory(extensions) add_subdirectory(external/json) +add_subdirectory(external/lua/lua) +add_subdirectory(external/lua/tolua) + +add_subdirectory(cocos/scripting) + # build samples add_subdirectory(samples) diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt new file mode 100644 index 0000000000..5212c4bbef --- /dev/null +++ b/cocos/scripting/CMakeLists.txt @@ -0,0 +1,32 @@ +set(LUABINDING_SRC + auto-generated/lua-bindings/lua_cocos2dx_auto.cpp + auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp + lua/bindings/tolua_fix.c + lua/bindings/CCLuaBridge.cpp + lua/bindings/CCLuaEngine.cpp + lua/bindings/CCLuaStack.cpp + lua/bindings/CCLuaValue.cpp + lua/bindings/Cocos2dxLuaLoader.cpp + lua/bindings/CCBProxy.cpp + lua/bindings/LuaOpengl.cpp + lua/bindings/LuaScriptHandlerMgr.cpp + lua/bindings/LuaBasicConversions.cpp + lua/bindings/lua_cocos2dx_manual.cpp + lua/bindings/lua_cocos2dx_extension_manual.cpp + lua/bindings/lua_cocos2dx_deprecated.cpp + lua/bindings/lua_xml_http_request.cpp +) + +include_directories( + auto-generated/lua-bindings + lua/bindings + ../../cocos/editor-support/cocosbuilder + ../../cocos/editor-support/cocostudio + ../../external/lua/lua + ../../external/lua/tolua +) + + +add_library(luabinding STATIC + ${LUABINDING_SRC} +) diff --git a/external/lua/lua/CMakeLists.txt b/external/lua/lua/CMakeLists.txt new file mode 100644 index 0000000000..faba14e849 --- /dev/null +++ b/external/lua/lua/CMakeLists.txt @@ -0,0 +1,36 @@ +set(LUA_SRC + lapi.c + lauxlib.c + lbaselib.c + lcode.c + ldblib.c + ldebug.c + ldo.c + ldump.c + lfunc.c + lgc.c + linit.c + liolib.c + llex.c + lmathlib.c + lmem.c + loadlib.c + lobject.c + lopcodes.c + loslib.c + lparser.c + lstate.c + lstring.c + lstrlib.c + ltable.c + ltablib.c + ltm.c + lundump.c + lvm.c + lzio.c + print.c +) + +add_library(lua STATIC + ${LUA_SRC} +) \ No newline at end of file diff --git a/external/lua/tolua/CMakeLists.txt b/external/lua/tolua/CMakeLists.txt new file mode 100644 index 0000000000..481bdd1247 --- /dev/null +++ b/external/lua/tolua/CMakeLists.txt @@ -0,0 +1,17 @@ +set(TOLUA_SRC + tolua_event.c + tolua_is.c + tolua_map.c + tolua_push.c + tolua_to.c +) + +include_directories( + ../lua +) + + +add_library(tolua STATIC + ${TOLUA_SRC} +) + diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index c3a9708207..d73334ce7e 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,5 +1,5 @@ -#add_subdirectory(Cpp/HelloCpp) - +add_subdirectory(Cpp/HelloCpp) add_subdirectory(Cpp/TestCpp) - +add_subdirectory(Lua/HelloLua) +add_subdirectory(Lua/TestLua) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt new file mode 100644 index 0000000000..9c05dea1a9 --- /dev/null +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -0,0 +1,41 @@ +set(SAMPLE_NAME hellolua) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +include_directories( + Classes + ../../../cocos/scripting/lua/bindings + ../../../external/lua/lua + ../../../external/lua/tolua +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} + luabinding + gui + network + cocostudio + cocosbuilder + extensions + ${COCOS_LIBRARIES} + jsoncpp + curl + tolua + lua + rt +) + +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") + diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt new file mode 100644 index 0000000000..88f5ea0977 --- /dev/null +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -0,0 +1,41 @@ +set(SAMPLE_NAME testlua) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +include_directories( + Classes + ../../../cocos/scripting/lua/bindings + ../../../external/lua/lua + ../../../external/lua/tolua +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} + luabinding + gui + network + cocostudio + cocosbuilder + extensions + ${COCOS_LIBRARIES} + jsoncpp + curl + tolua + lua + rt +) + +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") + From 59adba1a6d7160b0b9ae85c96e75f1e3b5b2b935 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 12:00:45 +0800 Subject: [PATCH 044/197] Updating physics/CMakeLists.txt --- cocos/physics/CMakeLists.txt | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt index 2ca5a7f532..1586db2379 100644 --- a/cocos/physics/CMakeLists.txt +++ b/cocos/physics/CMakeLists.txt @@ -1,17 +1,18 @@ set(COCOS_PHYSICS_SRC - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsBody.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsContact.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsShape.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsJoint.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsWorld.cpp ) + From daa91ad41339fe4a79ca94e91052663f593719a2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 13:10:04 +0800 Subject: [PATCH 045/197] [CMake] Update library dependency. --- CMakeLists.txt | 28 +++---------------- cocos/2d/CMakeLists.txt | 19 ++++++++++++- .../editor-support/cocostudio/CMakeLists.txt | 4 +++ cocos/network/CMakeLists.txt | 4 +++ cocos/scripting/CMakeLists.txt | 5 ++++ samples/Cpp/HelloCpp/CMakeLists.txt | 2 +- samples/Cpp/TestCpp/CMakeLists.txt | 6 ++-- samples/Lua/HelloLua/CMakeLists.txt | 8 ++---- samples/Lua/TestLua/CMakeLists.txt | 8 ++---- 9 files changed, 42 insertions(+), 42 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 67dde5fa7f..4b7d98403d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,27 +57,6 @@ link_directories( ${CMAKE_SOURCE_DIR}/cocos/audio/third-party/fmod/lib64/api/lib ) -set(COCOS_LIBRARIES - audio - cocos2d - cocosbase - chipmunk_static - tinyxml2 - kazmath - unzip - jpeg - webp - tiff - freetype - fontconfig - png - glfw - GLEW - GL - rt - z -) - # kazmath add_subdirectory(cocos/math/kazmath) @@ -94,6 +73,8 @@ add_subdirectory(external/unzip) # tinyxml2 library add_subdirectory(external/tinyxml2) +add_subdirectory(external/json) + # audio add_subdirectory(cocos/audio) @@ -107,13 +88,12 @@ add_subdirectory(cocos/gui) add_subdirectory(cocos/network) +add_subdirectory(extensions) + add_subdirectory(cocos/editor-support/spine) add_subdirectory(cocos/editor-support/cocosbuilder) add_subdirectory(cocos/editor-support/cocostudio) -add_subdirectory(extensions) - -add_subdirectory(external/json) add_subdirectory(external/lua/lua) add_subdirectory(external/lua/tolua) diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index fdcd28a564..1e66ba9cb4 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -122,4 +122,21 @@ add_library(cocos2d STATIC ${COCOS2D_SRC} ${COCOS_PHYSICS_SRC} ) - +target_link_libraries(cocos2d + cocosbase + chipmunk_static + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + glfw + GLEW + GL + rt + z +) diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt index f86093b2ea..8aa09558d9 100644 --- a/cocos/editor-support/cocostudio/CMakeLists.txt +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -41,3 +41,7 @@ include_directories( add_library(cocostudio STATIC ${CS_SRC} ) + +target_link_libraries(cocostudio + jsoncpp +) diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index 8217122fa9..1b001c6210 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -6,3 +6,7 @@ set(NETWORK_SRC add_library(network STATIC ${NETWORK_SRC} ) + +target_link_libraries(network + curl +) diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt index 5212c4bbef..bee2a84fe8 100644 --- a/cocos/scripting/CMakeLists.txt +++ b/cocos/scripting/CMakeLists.txt @@ -30,3 +30,8 @@ include_directories( add_library(luabinding STATIC ${LUABINDING_SRC} ) + +target_link_libraries(luabinding + tolua + lua +) diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index 22770fff8e..e8ee537a78 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -11,7 +11,7 @@ add_executable(${SAMPLE_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) +target_link_libraries(${SAMPLE_NAME} audio cocos2d) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index c567f1331a..d6c921f1d5 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -149,11 +149,9 @@ target_link_libraries(${SAMPLE_NAME} cocostudio cocosbuilder extensions - ${COCOS_LIBRARIES} + audio + cocos2d box2d - jsoncpp - curl - rt ) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index 9c05dea1a9..e1e41b7867 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -24,12 +24,8 @@ target_link_libraries(${SAMPLE_NAME} cocostudio cocosbuilder extensions - ${COCOS_LIBRARIES} - jsoncpp - curl - tolua - lua - rt + audio + cocos2d ) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index 88f5ea0977..fb2225945d 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -24,12 +24,8 @@ target_link_libraries(${SAMPLE_NAME} cocostudio cocosbuilder extensions - ${COCOS_LIBRARIES} - jsoncpp - curl - tolua - lua - rt + audio + cocos2d ) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") From f17aa8b4500fe96bb4b5de54f87867447b6c2639 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 13:53:30 +0800 Subject: [PATCH 046/197] Move the library of fmod to external folder. --- CMakeLists.txt | 3 +- cocos/audio/CMakeLists.txt | 4 - cocos/audio/third-party/fmod/Makefile | 81 ------------------- cocos/audio/third-party/fmod/lib64/Makefile | 65 --------------- .../include/32-bit}/fmod.h.REMOVED.git-id | 0 .../fmod/include/32-bit}/fmod.hpp | 0 .../fmod/include/32-bit}/fmod_codec.h | 0 .../fmod/include/32-bit}/fmod_dsp.h | 0 .../fmod/include/32-bit}/fmod_errors.h | 0 .../fmod/include/32-bit}/fmod_memoryinfo.h | 0 .../fmod/include/32-bit}/fmod_output.h | 0 .../fmod/include/32-bit}/fmodlinux.h | 0 .../include/64-bit}/fmod.h.REMOVED.git-id | 0 .../fmod/include/64-bit}/fmod.hpp | 0 .../fmod/include/64-bit}/fmod_codec.h | 0 .../fmod/include/64-bit}/fmod_dsp.h | 0 .../fmod/include/64-bit}/fmod_errors.h | 0 .../fmod/include/64-bit}/fmod_memoryinfo.h | 0 .../fmod/include/64-bit}/fmod_output.h | 0 .../fmod/include/64-bit}/fmodlinux.h | 0 .../libfmodex-4.36.01.so.REMOVED.git-id | 0 .../32-bit}/libfmodex.so.REMOVED.git-id | 0 .../libfmodexL-4.36.01.so.REMOVED.git-id | 0 .../32-bit}/libfmodexL.so.REMOVED.git-id | 0 .../libfmodex64-4.38.00.so.REMOVED.git-id | 0 .../64-bit}/libfmodex64.so.REMOVED.git-id | 0 .../libfmodexL64-4.38.00.so.REMOVED.git-id | 0 .../64-bit}/libfmodexL64.so.REMOVED.git-id | 0 28 files changed, 2 insertions(+), 151 deletions(-) delete mode 100644 cocos/audio/third-party/fmod/Makefile delete mode 100644 cocos/audio/third-party/fmod/lib64/Makefile rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod.h.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod.hpp (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_codec.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_dsp.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_errors.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_memoryinfo.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_output.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmodlinux.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod.h.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod.hpp (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_codec.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_dsp.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_errors.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_memoryinfo.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_output.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmodlinux.h (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodex-4.36.01.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodex.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodexL-4.36.01.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodexL.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodex64-4.38.00.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodex64.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodexL64-4.38.00.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodexL64.so.REMOVED.git-id (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b7d98403d..7f93de1683 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,6 +45,7 @@ include_directories( external/unzip external/chipmunk/include/chipmunk external/freetype2/include/linux + external/linux-specific/fmod/include/${ARCH_DIR} ) link_directories( @@ -54,7 +55,7 @@ link_directories( ${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/curl/prebuilt/linux/${ARCH_DIR} - ${CMAKE_SOURCE_DIR}/cocos/audio/third-party/fmod/lib64/api/lib + ${CMAKE_SOURCE_DIR}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} ) # kazmath diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 79f84aa217..4f56e9b44b 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -3,10 +3,6 @@ set(AUDIO_SRC linux/FmodAudioPlayer.cpp ) -include_directories( - third-party/fmod/lib64/api/inc -) - add_library(audio STATIC ${AUDIO_SRC} ) diff --git a/cocos/audio/third-party/fmod/Makefile b/cocos/audio/third-party/fmod/Makefile deleted file mode 100644 index ef3df253c6..0000000000 --- a/cocos/audio/third-party/fmod/Makefile +++ /dev/null @@ -1,81 +0,0 @@ -LBITS := $(shell getconf LONG_BIT) -ifeq ($(LBITS),64) -FMODEX = libfmodex64 -FMODEXL = libfmodexL64 -VERSION = 4.38.00 -LIBDIR = lib64/api/lib -HDRDIR = lib64/api/inc -else -FMODEX = libfmodex -FMODEXL = libfmodexL -VERSION = 4.36.01 -LIBDIR = api/lib -HDRDIR = api/inc -endif - -DESTLIBDIR = /usr/local/lib -DESTHDRDIR = /usr/local/include/fmodex - -all: - @echo "Possible targets:" - @echo "'make fmod_examples' - Build all examples" - @echo "'make install' - Install FMOD Ex libraries and headers" - @echo "'make uninstall' - Uninstall FMOD Ex libraries and headers" - -fmod_examples: - cd examples/3d && make - cd examples/cdplayer && make - cd examples/channelgroups && make - cd examples/dsp_effectperspeaker && make - cd examples/dsp_custom && make - cd examples/effects && make - cd examples/filecallbacks && make - cd examples/generatetone && make - cd examples/loadfrommemory && make - cd examples/multiplesoundcard && make - cd examples/multispeakeroutput && make - cd examples/netstream && make - cd examples/offlinedecoding && make - cd examples/pitchdetection && make - cd examples/playlist && make - cd examples/playsound && make - cd examples/playstream && make - cd examples/plugin_dev/codec_raw && make - cd examples/plugin_dev/dsp_gain && make - cd examples/readtags && make - cd examples/realtimestitching && make - cd examples/recording && make - cd examples/recordtodisk && make - cd examples/ripnetstream && make - cd examples/submixing && make - cd examples/useplugins && make - cd examples/usercreatedsound && make - cd fmoddesignerapi/examples/effects && make - cd fmoddesignerapi/examples/info_only && make - cd fmoddesignerapi/examples/load_data && make - cd fmoddesignerapi/examples/max_playbacks && make - cd fmoddesignerapi/examples/parameters && make - cd fmoddesignerapi/examples/programmer_selected && make - cd fmoddesignerapi/examples/programmer_sound && make - cd fmoddesignerapi/examples/simple_event && make - -install: - @echo "Installing FMOD Ex libraries and headers..." - cp -f ${LIBDIR}/${FMODEX}-${VERSION}.so ${DESTLIBDIR} - cp -f ${LIBDIR}/${FMODEXL}-${VERSION}.so ${DESTLIBDIR} - ln -s -f ${DESTLIBDIR}/${FMODEX}-${VERSION}.so ${DESTLIBDIR}/${FMODEX}.so - ln -s -f ${DESTLIBDIR}/${FMODEXL}-${VERSION}.so ${DESTLIBDIR}/${FMODEXL}.so - ldconfig -n ${DESTLIBDIR} - mkdir -p ${DESTHDRDIR} - cp -f ${HDRDIR}/*.h* ${DESTHDRDIR} - @echo "done." - -uninstall: - @echo "Uninstalling FMOD Ex libraries..." - rm -f ${DESTLIBDIR}/${FMODEX}.so - rm -f ${DESTLIBDIR}/${FMODEXL}.so - rm -f ${DESTLIBDIR}/${FMODEX}-${VERSION}.so - rm -f ${DESTLIBDIR}/${FMODEXL}-${VERSION}.so - ldconfig -n ${DESTLIBDIR} - rm -rf ${DESTHDRDIR} - @echo "done." diff --git a/cocos/audio/third-party/fmod/lib64/Makefile b/cocos/audio/third-party/fmod/lib64/Makefile deleted file mode 100644 index c461587728..0000000000 --- a/cocos/audio/third-party/fmod/lib64/Makefile +++ /dev/null @@ -1,65 +0,0 @@ -VERSION = 4.38.00 -LIBDIR = api/lib -HDRDIR = api/inc -DESTLIBDIR = /usr/local/lib -DESTHDRDIR = /usr/local/include/fmodex - -all: - @echo "Possible targets:" - @echo "'make fmod_examples' - Build all examples" - @echo "'make install' - Install FMOD Ex libraries and headers" - @echo "'make uninstall' - Uninstall FMOD Ex libraries and headers" - -fmod_examples: - cd examples/3d && make - cd examples/cdplayer && make - cd examples/channelgroups && make - cd examples/dsp_effectperspeaker && make - cd examples/dsp_custom && make - cd examples/effects && make - cd examples/filecallbacks && make - cd examples/generatetone && make - cd examples/loadfrommemory && make - cd examples/multiplesoundcard && make - cd examples/multispeakeroutput && make - cd examples/netstream && make - cd examples/offlinedecoding && make - cd examples/pitchdetection && make - cd examples/playlist && make - cd examples/playsound && make - cd examples/playstream && make - cd examples/plugin_dev/codec_raw && make - cd examples/plugin_dev/dsp_gain && make - cd examples/readtags && make - cd examples/realtimestitching && make - cd examples/recording && make - cd examples/recordtodisk && make - cd examples/ripnetstream && make - cd examples/submixing && make - cd examples/useplugins && make - cd examples/usercreatedsound && make - cd fmoddesignerapi/examples/effects && make - cd fmoddesignerapi/examples/info_only && make - cd fmoddesignerapi/examples/load_data && make - cd fmoddesignerapi/examples/max_playbacks && make - cd fmoddesignerapi/examples/parameters && make - cd fmoddesignerapi/examples/programmer_selected && make - cd fmoddesignerapi/examples/programmer_sound && make - cd fmoddesignerapi/examples/simple_event && make - -install: - @echo "Installing FMOD Ex libraries and headers..." - cp -f ${LIBDIR}/libfmodex64-${VERSION}.so ${DESTLIBDIR} - cp -f ${LIBDIR}/libfmodexL64-${VERSION}.so ${DESTLIBDIR} - ldconfig -n ${DESTLIBDIR} - mkdir -p ${DESTHDRDIR} - cp -f ${HDRDIR}/*.h* ${DESTHDRDIR} - @echo "done." - -uninstall: - @echo "Uninstalling FMOD Ex libraries..." - rm -f ${DESTLIBDIR}/libfmodex64-${VERSION}.so - rm -f ${DESTLIBDIR}/libfmodexL64-${VERSION}.so - ldconfig -n ${DESTLIBDIR} - rm -rf ${DESTHDRDIR} - @echo "done." diff --git a/cocos/audio/third-party/fmod/api/inc/fmod.h.REMOVED.git-id b/external/linux-specific/fmod/include/32-bit/fmod.h.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod.h.REMOVED.git-id rename to external/linux-specific/fmod/include/32-bit/fmod.h.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/inc/fmod.hpp b/external/linux-specific/fmod/include/32-bit/fmod.hpp similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod.hpp rename to external/linux-specific/fmod/include/32-bit/fmod.hpp diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_codec.h b/external/linux-specific/fmod/include/32-bit/fmod_codec.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_codec.h rename to external/linux-specific/fmod/include/32-bit/fmod_codec.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_dsp.h b/external/linux-specific/fmod/include/32-bit/fmod_dsp.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_dsp.h rename to external/linux-specific/fmod/include/32-bit/fmod_dsp.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_errors.h b/external/linux-specific/fmod/include/32-bit/fmod_errors.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_errors.h rename to external/linux-specific/fmod/include/32-bit/fmod_errors.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_memoryinfo.h b/external/linux-specific/fmod/include/32-bit/fmod_memoryinfo.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_memoryinfo.h rename to external/linux-specific/fmod/include/32-bit/fmod_memoryinfo.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_output.h b/external/linux-specific/fmod/include/32-bit/fmod_output.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_output.h rename to external/linux-specific/fmod/include/32-bit/fmod_output.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmodlinux.h b/external/linux-specific/fmod/include/32-bit/fmodlinux.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmodlinux.h rename to external/linux-specific/fmod/include/32-bit/fmodlinux.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id b/external/linux-specific/fmod/include/64-bit/fmod.h.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id rename to external/linux-specific/fmod/include/64-bit/fmod.h.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod.hpp b/external/linux-specific/fmod/include/64-bit/fmod.hpp similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod.hpp rename to external/linux-specific/fmod/include/64-bit/fmod.hpp diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_codec.h b/external/linux-specific/fmod/include/64-bit/fmod_codec.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_codec.h rename to external/linux-specific/fmod/include/64-bit/fmod_codec.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_dsp.h b/external/linux-specific/fmod/include/64-bit/fmod_dsp.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_dsp.h rename to external/linux-specific/fmod/include/64-bit/fmod_dsp.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_errors.h b/external/linux-specific/fmod/include/64-bit/fmod_errors.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_errors.h rename to external/linux-specific/fmod/include/64-bit/fmod_errors.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_memoryinfo.h b/external/linux-specific/fmod/include/64-bit/fmod_memoryinfo.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_memoryinfo.h rename to external/linux-specific/fmod/include/64-bit/fmod_memoryinfo.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_output.h b/external/linux-specific/fmod/include/64-bit/fmod_output.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_output.h rename to external/linux-specific/fmod/include/64-bit/fmod_output.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmodlinux.h b/external/linux-specific/fmod/include/64-bit/fmodlinux.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmodlinux.h rename to external/linux-specific/fmod/include/64-bit/fmodlinux.h diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodex-4.36.01.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodex-4.36.01.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodex.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodex.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodex.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodex.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodexL-4.36.01.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodexL-4.36.01.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodexL.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodexL.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodexL.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodexL.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodex64-4.38.00.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodex64-4.38.00.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodex64.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodex64.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64-4.38.00.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64-4.38.00.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64.so.REMOVED.git-id From 9be8ca371462ecfde174886c1260432c6539c139 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 14:49:42 +0800 Subject: [PATCH 047/197] [cmake] output lib to root/lib --- CMakeLists.txt | 1 - cocos/2d/CMakeLists.txt | 7 +++++++ cocos/audio/CMakeLists.txt | 9 ++++++++- cocos/base/CMakeLists.txt | 7 +++++++ cocos/editor-support/cocosbuilder/CMakeLists.txt | 7 +++++++ cocos/editor-support/cocostudio/CMakeLists.txt | 7 +++++++ cocos/editor-support/spine/CMakeLists.txt | 7 +++++++ cocos/gui/CMakeLists.txt | 5 +++++ cocos/math/kazmath/CMakeLists.txt | 8 +++++++- cocos/network/CMakeLists.txt | 7 +++++++ extensions/CMakeLists.txt | 7 +++++++ external/chipmunk/src/CMakeLists.txt | 9 +++++++++ external/json/CMakeLists.txt | 8 +++++++- external/tinyxml2/CMakeLists.txt | 7 +++++++ external/unzip/CMakeLists.txt | 7 +++++++ samples/Cpp/HelloCpp/CMakeLists.txt | 4 ++-- samples/Cpp/TestCpp/CMakeLists.txt | 4 ++-- samples/Lua/HelloLua/CMakeLists.txt | 4 ++-- samples/Lua/TestLua/CMakeLists.txt | 8 +++++--- 19 files changed, 110 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f93de1683..e07f618e27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,7 +62,6 @@ link_directories( add_subdirectory(cocos/math/kazmath) # chipmunk library -set(BUILD_STATIC 1) add_subdirectory(external/chipmunk/src) # box2d library diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 1e66ba9cb4..f147d233b6 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -140,3 +140,10 @@ target_link_libraries(cocos2d rt z ) + +set_target_properties(cocos2d + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 4f56e9b44b..9e88293ddd 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -9,4 +9,11 @@ add_library(audio STATIC target_link_libraries(audio fmodex64 -) \ No newline at end of file +) + +set_target_properties(audio + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index c46e07c114..3d37d21a2f 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -18,3 +18,10 @@ set(COCOS_BASE_SRC add_library(cocosbase STATIC ${COCOS_BASE_SRC} ) + +set_target_properties(cocosbase + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/cocosbuilder/CMakeLists.txt b/cocos/editor-support/cocosbuilder/CMakeLists.txt index 57f1113de6..00763e1fb7 100644 --- a/cocos/editor-support/cocosbuilder/CMakeLists.txt +++ b/cocos/editor-support/cocosbuilder/CMakeLists.txt @@ -31,3 +31,10 @@ include_directories( add_library(cocosbuilder STATIC ${CCB_SRC} ) + +set_target_properties(cocosbuilder + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt index 8aa09558d9..acff17a4a9 100644 --- a/cocos/editor-support/cocostudio/CMakeLists.txt +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -45,3 +45,10 @@ add_library(cocostudio STATIC target_link_libraries(cocostudio jsoncpp ) + +set_target_properties(cocostudio + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/spine/CMakeLists.txt b/cocos/editor-support/spine/CMakeLists.txt index e76d1ea6f8..0d6664b98d 100644 --- a/cocos/editor-support/spine/CMakeLists.txt +++ b/cocos/editor-support/spine/CMakeLists.txt @@ -29,3 +29,10 @@ include_directories( add_library(spine STATIC ${SPINE_SRC} ) + +set_target_properties(spine + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt index 069ce8a960..916e5cf0f2 100644 --- a/cocos/gui/CMakeLists.txt +++ b/cocos/gui/CMakeLists.txt @@ -27,3 +27,8 @@ add_library(gui STATIC ${GUI_SRC} ) +set_target_properties(gui + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/math/kazmath/CMakeLists.txt b/cocos/math/kazmath/CMakeLists.txt index 1dc636037d..208b4a97c2 100644 --- a/cocos/math/kazmath/CMakeLists.txt +++ b/cocos/math/kazmath/CMakeLists.txt @@ -14,4 +14,10 @@ SET(KAZMATH_SOURCES ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/matrix.c ) -ADD_SUBDIRECTORY(src) \ No newline at end of file +ADD_SUBDIRECTORY(src) + +set_target_properties(kazmath + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index 1b001c6210..3bd130111b 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -10,3 +10,10 @@ add_library(network STATIC target_link_libraries(network curl ) + +set_target_properties(network + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt index 5b85c4657b..176cd831ce 100644 --- a/extensions/CMakeLists.txt +++ b/extensions/CMakeLists.txt @@ -32,3 +32,10 @@ include_directories( add_library(extensions STATIC ${EXTENSIONS_SRC} ) + +set_target_properties(extensions + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/chipmunk/src/CMakeLists.txt b/external/chipmunk/src/CMakeLists.txt index 6f10d0177d..a0d15b7b8a 100644 --- a/external/chipmunk/src/CMakeLists.txt +++ b/external/chipmunk/src/CMakeLists.txt @@ -1,3 +1,5 @@ +set(BUILD_STATIC 1) + file(GLOB chipmunk_source_files "*.c" "constraints/*.c") file(GLOB chipmunk_public_header "${chipmunk_SOURCE_DIR}/include/chipmunk/*.h") file(GLOB chipmunk_constraint_header "${chipmunk_SOURCE_DIR}/include/chipmunk/constraints/*.h") @@ -39,3 +41,10 @@ if(BUILD_SHARED OR INSTALL_STATIC) install(FILES ${chipmunk_public_header} DESTINATION include/chipmunk) install(FILES ${chipmunk_constraint_header} DESTINATION include/chipmunk/constraints) endif(BUILD_SHARED OR INSTALL_STATIC) + +set_target_properties(chipmunk_static + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/json/CMakeLists.txt b/external/json/CMakeLists.txt index 257385a307..87018744ef 100644 --- a/external/json/CMakeLists.txt +++ b/external/json/CMakeLists.txt @@ -1,6 +1,6 @@ set(JSONCPP_SRC json_reader.cpp - json_value.cpp + json_value.cpp json_writer.cpp ) @@ -12,3 +12,9 @@ add_library(jsoncpp STATIC ${JSONCPP_SRC} ) +set_target_properties(jsoncpp + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/tinyxml2/CMakeLists.txt b/external/tinyxml2/CMakeLists.txt index 42822a3bc4..6877779b2c 100644 --- a/external/tinyxml2/CMakeLists.txt +++ b/external/tinyxml2/CMakeLists.txt @@ -5,3 +5,10 @@ set(TINYXML2_SRC add_library(tinyxml2 STATIC ${TINYXML2_SRC} ) + +set_target_properties(tinyxml2 + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/unzip/CMakeLists.txt b/external/unzip/CMakeLists.txt index 8d15111c8e..ae98584279 100644 --- a/external/unzip/CMakeLists.txt +++ b/external/unzip/CMakeLists.txt @@ -6,3 +6,10 @@ set(UNZIP_SRC add_library(unzip STATIC ${UNZIP_SRC} ) + +set_target_properties(unzip + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index e8ee537a78..646a1574ab 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -13,9 +13,9 @@ add_executable(${SAMPLE_NAME} target_link_libraries(${SAMPLE_NAME} audio cocos2d) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index d6c921f1d5..0547ee04b1 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -154,9 +154,9 @@ target_link_libraries(${SAMPLE_NAME} box2d ) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index e1e41b7867..81b1fa4357 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -28,9 +28,9 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index fb2225945d..cb37076c59 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -28,10 +28,12 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES(${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES_EXTRA(${SAMPLE_NAME} "${CMAKE_SOURCE_DIR}/samples/TestCpp/Resources/*") +# "${SAMPLE_BIN_DIR}") From 733197fa6518cdbd4eb7f8a818628798bcecdf3a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:48:36 +0800 Subject: [PATCH 048/197] [cmake] copy resources works. --- build/BuildHelpers.CMakeLists.txt | 44 ++++++++++++++++++++--------- samples/Cpp/HelloCpp/CMakeLists.txt | 14 ++++----- samples/Cpp/TestCpp/CMakeLists.txt | 14 ++++----- samples/Lua/HelloLua/CMakeLists.txt | 17 ++++++----- samples/Lua/TestLua/CMakeLists.txt | 22 +++++++++------ 5 files changed, 67 insertions(+), 44 deletions(-) diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt index c60446bd30..92d537dd7d 100644 --- a/build/BuildHelpers.CMakeLists.txt +++ b/build/BuildHelpers.CMakeLists.txt @@ -1,37 +1,53 @@ - +# This file was copied from GamePlay # Copies files for the given game into the target res directory # GAME_NAME name of the game # REL_DIR to which directory these files are relative # SRC_FILES which files from the REL_DIR to copy (GLOB) -macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES DST) +macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES) file( GLOB_RECURSE RES_FILES RELATIVE ${REL_DIR} ${SRC_FILES} ) - + set(ALL_FILES) foreach(SRC_FILE ${RES_FILES}) - add_custom_command( - OUTPUT "${DST}/${SRC_FILE}" - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${REL_DIR}/${SRC_FILE}" - "${DST}/${SRC_FILE}" - COMMENT "Copy ${SRC_FILE}" - ) - list(APPEND ALL_FILES "${DST}/${SRC_FILE}" ) + IF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) + add_custom_command( + OUTPUT "${APP_BIN_DIR}/${SRC_FILE}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${REL_DIR}/${SRC_FILE}" + "${APP_BIN_DIR}/Resources/${SRC_FILE}" + COMMENT "Copy ${SRC_FILE}" + ) + list(APPEND ALL_FILES "${APP_BIN_DIR}/${SRC_FILE}" ) + ENDIF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) endforeach() # create target for copying these files add_custom_target( ${GAME_RES_TARGET} DEPENDS ${ALL_FILES} ) endmacro() # convenience to call above with current directory and everything in "res" -macro(COPY_RES GAME_NAME CRG_PATTERN DST) +macro(COPY_RES GAME_NAME) # a target for all addition asserts (will be done in default compile, but if you target the executable # it won't be done -- good for testing) add_custom_target( ${GAME_NAME}_ASSETS ALL ) + # copy entire "res" directory and "game.config" if there is one + set(CRG_PATTERN "*") COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_CORE_RES - ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Resources "${CRG_PATTERN}" - ${DST} ) add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_CORE_RES ) endmacro() +# Copies resources from an additional directory +# GAME_NAME name of the game +# REL_DIR from which directory +# ARGN which patterns to copy (should include res/ in name if to be placed in the res/ output) +macro(COPY_RES_EXTRA GAME_NAME EXTRA_RES REL_DIR) + # convert src's to full paths (based on rel_dir) + set(SRC_FILES) + foreach(SRC_FILE ${ARGN} ) + list(APPEND SRC_FILES "${REL_DIR}/${SRC_FILE}") + endforeach() + COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_${EXTRA_RES} ${REL_DIR} "${SRC_FILES}" ) + add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_${EXTRA_RES} ) +endmacro() diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index 646a1574ab..b335cf89fc 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME hellocpp) +set(APP_NAME hellocpp) set(SAMPLE_SRC proj.linux/main.cpp @@ -7,16 +7,16 @@ set(SAMPLE_SRC ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} audio cocos2d) +target_link_libraries(${APP_NAME} audio cocos2d) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES( ${APP_NAME} ) diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 0547ee04b1..a4237425f9 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME testcpp) +set(APP_NAME testcpp) set(SAMPLE_SRC Classes/AccelerometerTest/AccelerometerTest.cpp @@ -138,11 +138,11 @@ include_directories( ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} +target_link_libraries(${APP_NAME} gui network spine @@ -154,10 +154,10 @@ target_link_libraries(${SAMPLE_NAME} box2d ) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES( ${APP_NAME} ) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index 81b1fa4357..c048fae5c0 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME hellolua) +set(APP_NAME hellolua) set(SAMPLE_SRC proj.linux/main.cpp @@ -13,11 +13,11 @@ include_directories( ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} +target_link_libraries(${APP_NAME} luabinding gui network @@ -28,10 +28,13 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES( ${APP_NAME} ) +COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua + script/* + ) diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index cb37076c59..dc81be8941 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME testlua) +set(APP_NAME testlua) set(SAMPLE_SRC proj.linux/main.cpp @@ -13,11 +13,11 @@ include_directories( ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} +target_link_libraries(${APP_NAME} luabinding gui network @@ -28,12 +28,16 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES(${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") -COPY_RES_EXTRA(${SAMPLE_NAME} "${CMAKE_SOURCE_DIR}/samples/TestCpp/Resources/*") -# "${SAMPLE_BIN_DIR}") +COPY_RES(${APP_NAME}) +COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua + script/* + ) +COPY_RES_EXTRA(${APP_NAME} copy_cpp_res ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources + * + ) From edb1fc7822c24ce68c916547aef09e59551749f5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:48:59 +0800 Subject: [PATCH 049/197] [cmake] Deletes .icf files. --- samples/Cpp/HelloCpp/Resources/app.icf | 17 --- .../Cpp/HelloCpp/Resources/development.icf | 107 ------------------ samples/Cpp/SimpleGame/Resources/app.icf | 20 ---- .../Cpp/SimpleGame/Resources/development.icf | 107 ------------------ samples/Cpp/SimpleGame/Resources/sd/app.icf | 26 ----- samples/Cpp/TestCpp/Resources/app.icf | 26 ----- samples/Cpp/TestCpp/Resources/development.icf | 107 ------------------ samples/Lua/HelloLua/Resources/app.icf | 23 ---- .../Lua/HelloLua/Resources/development.icf | 107 ------------------ samples/Lua/TestLua/Resources/app.icf | 26 ----- samples/Lua/TestLua/Resources/development.icf | 107 ------------------ 11 files changed, 673 deletions(-) delete mode 100644 samples/Cpp/HelloCpp/Resources/app.icf delete mode 100644 samples/Cpp/HelloCpp/Resources/development.icf delete mode 100644 samples/Cpp/SimpleGame/Resources/app.icf delete mode 100644 samples/Cpp/SimpleGame/Resources/development.icf delete mode 100644 samples/Cpp/SimpleGame/Resources/sd/app.icf delete mode 100644 samples/Cpp/TestCpp/Resources/app.icf delete mode 100644 samples/Cpp/TestCpp/Resources/development.icf delete mode 100644 samples/Lua/HelloLua/Resources/app.icf delete mode 100644 samples/Lua/HelloLua/Resources/development.icf delete mode 100644 samples/Lua/TestLua/Resources/app.icf delete mode 100644 samples/Lua/TestLua/Resources/development.icf diff --git a/samples/Cpp/HelloCpp/Resources/app.icf b/samples/Cpp/HelloCpp/Resources/app.icf deleted file mode 100644 index 74755b2099..0000000000 --- a/samples/Cpp/HelloCpp/Resources/app.icf +++ /dev/null @@ -1,17 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. diff --git a/samples/Cpp/HelloCpp/Resources/development.icf b/samples/Cpp/HelloCpp/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Cpp/HelloCpp/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/SimpleGame/Resources/app.icf b/samples/Cpp/SimpleGame/Resources/app.icf deleted file mode 100644 index 1ae216d665..0000000000 --- a/samples/Cpp/SimpleGame/Resources/app.icf +++ /dev/null @@ -1,20 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. - -[S3E] -DispFixRot=Landscape \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/Resources/development.icf b/samples/Cpp/SimpleGame/Resources/development.icf deleted file mode 100644 index c9d1b773f1..0000000000 --- a/samples/Cpp/SimpleGame/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "640" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "960" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/SimpleGame/Resources/sd/app.icf b/samples/Cpp/SimpleGame/Resources/sd/app.icf deleted file mode 100644 index dbc72b4d77..0000000000 --- a/samples/Cpp/SimpleGame/Resources/sd/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Cpp/TestCpp/Resources/app.icf b/samples/Cpp/TestCpp/Resources/app.icf deleted file mode 100644 index 7fdabcd1f2..0000000000 --- a/samples/Cpp/TestCpp/Resources/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 100000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Cpp/TestCpp/Resources/development.icf b/samples/Cpp/TestCpp/Resources/development.icf deleted file mode 100644 index 363d486f04..0000000000 --- a/samples/Cpp/TestCpp/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "Samsung Galaxy S" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "ANDROID" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "NONE:OSX:480x320" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "ANDROID" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "false" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "800" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot90" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Lua/HelloLua/Resources/app.icf b/samples/Lua/HelloLua/Resources/app.icf deleted file mode 100644 index dec7c07959..0000000000 --- a/samples/Lua/HelloLua/Resources/app.icf +++ /dev/null @@ -1,23 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Lua/HelloLua/Resources/development.icf b/samples/Lua/HelloLua/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Lua/HelloLua/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Lua/TestLua/Resources/app.icf b/samples/Lua/TestLua/Resources/app.icf deleted file mode 100644 index dbc72b4d77..0000000000 --- a/samples/Lua/TestLua/Resources/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Lua/TestLua/Resources/development.icf b/samples/Lua/TestLua/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Lua/TestLua/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" From bc251bcc9580cbf7cbf14ee6e8bcb315d86685f3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:56:03 +0800 Subject: [PATCH 050/197] [cmake] Update make-all-linux-projects.sh. --- build/make-all-linux-project.sh | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/build/make-all-linux-project.sh b/build/make-all-linux-project.sh index 4889355380..98eaeef714 100755 --- a/build/make-all-linux-project.sh +++ b/build/make-all-linux-project.sh @@ -17,10 +17,8 @@ if $COCOS2DX_USEAPT; then ./install-deps-linux.sh fi -export MAKEFLAGS=-j10 +mkdir -p linux-build +cd linux-build +cmake ../.. +make -j10 -make PLATFORM=linux DEBUG=1 clean -make PLATFORM=linux DEBUG=0 clean - -make PLATFORM=linux DEBUG=1 all -make PLATFORM=linux DEBUG=0 all From b1a9843091e575d0569f57e31814255fb79d1a68 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:59:39 +0800 Subject: [PATCH 051/197] [cmake] update run-script.sh --- tools/travis-scripts/run-script.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 54cd858c49..7fc74092fd 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -72,7 +72,10 @@ elif [ "$PLATFORM"x = "linux"x ]; then ./generate-jsbindings.sh cd $COCOS2DX_ROOT/build - make -j4 + mkdir -p linux-build + cd linux-build + cmake ../.. + make -j10 elif [ "$PLATFORM"x = "emscripten"x ]; then # Generate binding glue codes echo "Generating bindings glue codes ..." From 6a351711ae378950d058d59414ae212632c80327 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 21:05:29 +0800 Subject: [PATCH 052/197] [cmake] update run-script.sh --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 7fc74092fd..99cfba1eb1 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n NDK_DEBUG=0 -j10 all + ./android-build.py -n -j10 all # Build template # echo "Building template ..." From f968169da4b99345f1701df2d09e69fe0f5d7797 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 21:59:03 +0800 Subject: [PATCH 053/197] Update run-script.sh --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 99cfba1eb1..e8d45a1415 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n -j10 all + ./android-build.py -n "NDK_BUG=0 -j10" all # Build template # echo "Building template ..." From 0350ac7021c9ce6126716648a9330b74e035064d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 11:53:40 -0800 Subject: [PATCH 054/197] arm64 support --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/platform/CCEGLViewProtocol.cpp | 20 ++++++++-------- cocos/2d/platform/CCEGLViewProtocol.h | 10 ++++---- cocos/2d/platform/ios/EAGLView.mm | 24 +++++++++---------- cocos/math/kazmath/src/mat4.c | 2 +- cocos/math/kazmath/src/neon_matrix_impl.c | 3 ++- external/curl/include/ios/curl/curlbuild.h | 2 +- 8 files changed, 33 insertions(+), 32 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index e32180792f..0532e4c91c 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -8c640bf1e2f1cd0a489e6169c930234b809636f2 \ No newline at end of file +76a9b59d223b70e0db8ee75c10c90910f44ca943 \ 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 ba37de5f5d..7a61547a58 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b473303312be3b69891020b5fb470dd382f31284 \ No newline at end of file +339a697a5f1d1b9c06d6fa5262c9887df0f763de \ No newline at end of file diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 17eafdf0d6..9004f4c6fc 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -12,7 +12,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { NULL }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -201,9 +201,9 @@ const char* EGLViewProtocol::getViewName() return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesBegin(int num, void* ids[], float xs[], float ys[]) { - int id = 0; + void* id = nullptr; float x = 0.0f; float y = 0.0f; int nUnusedIndex = 0; @@ -251,9 +251,9 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float ys[]) { - int id = 0; + void* id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -283,7 +283,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys else { // It is error, should return. - CCLOG("Moving touches with id: %d error", id); + CCLOG("Moving touches with id: %p error", id); return; } } @@ -299,9 +299,9 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]) { - int id = 0; + void* id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -359,12 +359,12 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesEnd(int num, void* ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesCancel(int num, void* ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index b8744d0dd1..84bb1b4ee3 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -136,10 +136,10 @@ public: const char* getViewName(); /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, void* ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -156,7 +156,7 @@ public: */ float getScaleY() const; private: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]); protected: EGLTouchDelegate* _delegate; diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index 5d305d4bdc..771d32fd1f 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -399,18 +399,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (void**)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -419,18 +419,18 @@ static CCEAGLView *view = 0; { return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesMove(i, (void**)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -440,18 +440,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (void**)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -461,18 +461,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (void**)ids, xs, ys); } #pragma mark - diff --git a/cocos/math/kazmath/src/mat4.c b/cocos/math/kazmath/src/mat4.c index 77495cfdaa..9c49b56071 100644 --- a/cocos/math/kazmath/src/mat4.c +++ b/cocos/math/kazmath/src/mat4.c @@ -216,7 +216,7 @@ kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn) */ kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2) { -#if defined(__ARM_NEON__) +#if defined(__ARM_NEON__) && !defined(__arm64__) // It is possible to skip the memcpy() since "out" does not overwrite p1 or p2. // otherwise a temp must be needed. diff --git a/cocos/math/kazmath/src/neon_matrix_impl.c b/cocos/math/kazmath/src/neon_matrix_impl.c index 9790b73c92..b174ad0f87 100644 --- a/cocos/math/kazmath/src/neon_matrix_impl.c +++ b/cocos/math/kazmath/src/neon_matrix_impl.c @@ -23,7 +23,8 @@ #include "kazmath/neon_matrix_impl.h" -#if defined(__ARM_NEON__) +#if defined(__ARM_NEON__) && !defined(__arm64__) + void NEON_Matrix4Mul(const float* a, const float* b, float* output ) { diff --git a/external/curl/include/ios/curl/curlbuild.h b/external/curl/include/ios/curl/curlbuild.h index 98ede6eef7..c24099a90a 100644 --- a/external/curl/include/ios/curl/curlbuild.h +++ b/external/curl/include/ios/curl/curlbuild.h @@ -153,7 +153,7 @@ #endif /* The size of `long', as computed by sizeof. */ -#define CURL_SIZEOF_LONG 4 +#define CURL_SIZEOF_LONG sizeof(long) /* Integral data type used for curl_socklen_t. */ #define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t From ab6d620b3daf58789e0a1160dc4683f4fd445ced Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 15:11:20 -0800 Subject: [PATCH 055/197] Disables arm64 for the moment --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b016505abb..c6793fae44 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -d1d9b4192613089cb2c5ae3c1b9686903f6a4aa1 \ No newline at end of file +c49249b6c4c65ae98a4f04ee18f3546b413b53f7 \ 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 7a61547a58..d74257f49d 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -339a697a5f1d1b9c06d6fa5262c9887df0f763de \ No newline at end of file +2bc0a50d02444f846edaf00627df2df32df64f75 \ No newline at end of file From 2f0a19c7a38847bef7715c7edf918694739726e3 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 16:30:00 -0800 Subject: [PATCH 056/197] Enables more warnings in Xcode project --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index c6793fae44..098e7c8f8f 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -c49249b6c4c65ae98a4f04ee18f3546b413b53f7 \ No newline at end of file +dfbc1763de24004bc22496be8456fc4a21fda7b4 \ 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 d74257f49d..d1e4777ebf 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -2bc0a50d02444f846edaf00627df2df32df64f75 \ No newline at end of file +13f41d81e48285159fafa45159fdd1c081b4bb06 \ No newline at end of file From 24ecbc426cefc554086454233493cee3f6ce288f Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 16:30:33 -0800 Subject: [PATCH 057/197] removes Hungarian notation from CCACtionManager and fixes some 64-bit issues. --- cocos/2d/CCActionManager.cpp | 172 +++++++++++++++++------------------ cocos/2d/CCActionManager.h | 2 +- 2 files changed, 87 insertions(+), 87 deletions(-) diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 9d1fb1ee93..4a01fd7663 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -65,55 +65,55 @@ ActionManager::~ActionManager(void) // private -void ActionManager::deleteHashElement(tHashElement *pElement) +void ActionManager::deleteHashElement(tHashElement *element) { - ccArrayFree(pElement->actions); - HASH_DEL(_targets, pElement); - pElement->target->release(); - free(pElement); + ccArrayFree(element->actions); + HASH_DEL(_targets, element); + element->target->release(); + free(element); } -void ActionManager::actionAllocWithHashElement(tHashElement *pElement) +void ActionManager::actionAllocWithHashElement(tHashElement *element) { // 4 actions per Node by default - if (pElement->actions == NULL) + if (element->actions == NULL) { - pElement->actions = ccArrayNew(4); + element->actions = ccArrayNew(4); }else - if (pElement->actions->num == pElement->actions->max) + if (element->actions->num == element->actions->max) { - ccArrayDoubleCapacity(pElement->actions); + ccArrayDoubleCapacity(element->actions); } } -void ActionManager::removeActionAtIndex(int index, tHashElement *pElement) +void ActionManager::removeActionAtIndex(long index, tHashElement *element) { - Action *pAction = (Action*)pElement->actions->arr[index]; + Action *action = (Action*)element->actions->arr[index]; - if (pAction == pElement->currentAction && (! pElement->currentActionSalvaged)) + if (action == element->currentAction && (! element->currentActionSalvaged)) { - pElement->currentAction->retain(); - pElement->currentActionSalvaged = true; + element->currentAction->retain(); + element->currentActionSalvaged = true; } - ccArrayRemoveObjectAtIndex(pElement->actions, index, true); + ccArrayRemoveObjectAtIndex(element->actions, index, true); // update actionIndex in case we are in tick. looping over the actions - if (pElement->actionIndex >= index) + if (element->actionIndex >= index) { - pElement->actionIndex--; + element->actionIndex--; } - if (pElement->actions->num == 0) + if (element->actions->num == 0) { - if (_currentTarget == pElement) + if (_currentTarget == element) { _currentTargetSalvaged = true; } else { - deleteHashElement(pElement); + deleteHashElement(element); } } } @@ -122,21 +122,21 @@ void ActionManager::removeActionAtIndex(int index, tHashElement *pElement) void ActionManager::pauseTarget(Object *target) { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - pElement->paused = true; + element->paused = true; } } void ActionManager::resumeTarget(Object *target) { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - pElement->paused = false; + element->paused = false; } } @@ -168,40 +168,40 @@ void ActionManager::resumeTargets(cocos2d::Set *targetsToResume) // run -void ActionManager::addAction(Action *pAction, Node *target, bool paused) +void ActionManager::addAction(Action *action, Node *target, bool paused) { - CCASSERT(pAction != NULL, ""); + CCASSERT(action != NULL, ""); CCASSERT(target != NULL, ""); - tHashElement *pElement = NULL; + tHashElement *element = NULL; // we should convert it to Object*, because we save it as Object* Object *tmp = target; - HASH_FIND_INT(_targets, &tmp, pElement); - if (! pElement) + HASH_FIND_INT(_targets, &tmp, element); + if (! element) { - pElement = (tHashElement*)calloc(sizeof(*pElement), 1); - pElement->paused = paused; + element = (tHashElement*)calloc(sizeof(*element), 1); + element->paused = paused; target->retain(); - pElement->target = target; - HASH_ADD_INT(_targets, target, pElement); + element->target = target; + HASH_ADD_INT(_targets, target, element); } - actionAllocWithHashElement(pElement); + actionAllocWithHashElement(element); - CCASSERT(! ccArrayContainsObject(pElement->actions, pAction), ""); - ccArrayAppendObject(pElement->actions, pAction); + CCASSERT(! ccArrayContainsObject(element->actions, action), ""); + ccArrayAppendObject(element->actions, action); - pAction->startWithTarget(target); + action->startWithTarget(target); } // remove void ActionManager::removeAllActions(void) { - for (tHashElement *pElement = _targets; pElement != NULL; ) + for (tHashElement *element = _targets; element != NULL; ) { - Object *target = pElement->target; - pElement = (tHashElement*)pElement->hh.next; + Object *target = element->target; + element = (tHashElement*)element->hh.next; removeAllActionsFromTarget(target); } } @@ -214,24 +214,24 @@ void ActionManager::removeAllActionsFromTarget(Object *target) return; } - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - if (ccArrayContainsObject(pElement->actions, pElement->currentAction) && (! pElement->currentActionSalvaged)) + if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged)) { - pElement->currentAction->retain(); - pElement->currentActionSalvaged = true; + element->currentAction->retain(); + element->currentActionSalvaged = true; } - ccArrayRemoveAllObjects(pElement->actions); - if (_currentTarget == pElement) + ccArrayRemoveAllObjects(element->actions); + if (_currentTarget == element) { _currentTargetSalvaged = true; } else { - deleteHashElement(pElement); + deleteHashElement(element); } } else @@ -240,23 +240,23 @@ void ActionManager::removeAllActionsFromTarget(Object *target) } } -void ActionManager::removeAction(Action *pAction) +void ActionManager::removeAction(Action *action) { // explicit null handling - if (pAction == NULL) + if (action == NULL) { return; } - tHashElement *pElement = NULL; - Object *target = pAction->getOriginalTarget(); - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + Object *target = action->getOriginalTarget(); + HASH_FIND_INT(_targets, &target, element); + if (element) { - unsigned int i = ccArrayGetIndexOfObject(pElement->actions, pAction); - if (UINT_MAX != i) + long i = ccArrayGetIndexOfObject(element->actions, action); + if (i != CC_INVALID_INDEX) { - removeActionAtIndex(i, pElement); + removeActionAtIndex(i, element); } } else @@ -270,19 +270,19 @@ void ActionManager::removeActionByTag(int tag, Object *target) CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(target != NULL, ""); - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); - if (pElement) + if (element) { - unsigned int limit = pElement->actions->num; - for (unsigned int i = 0; i < limit; ++i) + long limit = element->actions->num; + for (long i = 0; i < limit; ++i) { - Action *pAction = (Action*)pElement->actions->arr[i]; + Action *action = (Action*)element->actions->arr[i]; - if (pAction->getTag() == (int)tag && pAction->getOriginalTarget() == target) + if (action->getTag() == (int)tag && action->getOriginalTarget() == target) { - removeActionAtIndex(i, pElement); + removeActionAtIndex(i, element); break; } } @@ -297,21 +297,21 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const { CCASSERT(tag != Action::INVALID_TAG, ""); - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); - if (pElement) + if (element) { - if (pElement->actions != NULL) + if (element->actions != NULL) { - unsigned int limit = pElement->actions->num; - for (unsigned int i = 0; i < limit; ++i) + long limit = element->actions->num; + for (long i = 0; i < limit; ++i) { - Action *pAction = (Action*)pElement->actions->arr[i]; + Action *action = (Action*)element->actions->arr[i]; - if (pAction->getTag() == (int)tag) + if (action->getTag() == (int)tag) { - return pAction; + return action; } } } @@ -329,11 +329,11 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const // and, it is not possible to get the address of a reference unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - return pElement->actions ? pElement->actions->num : 0; + return element->actions ? element->actions->num : 0; } return 0; @@ -374,10 +374,10 @@ void ActionManager::update(float dt) { _currentTarget->currentAction->stop(); - Action *pAction = _currentTarget->currentAction; + Action *action = _currentTarget->currentAction; // Make currentAction nil to prevent removeAction from salvaging it. _currentTarget->currentAction = NULL; - removeAction(pAction); + removeAction(action); } _currentTarget->currentAction = NULL; diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 72427a5648..9e21a77125 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -126,7 +126,7 @@ public: protected: // declared in ActionManager.m - void removeActionAtIndex(int index, struct _hashElement *pElement); + void removeActionAtIndex(long index, struct _hashElement *pElement); void deleteHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *pElement); void update(float dt); From ba7ed6e5787ef31e0f2de1c408fb1bc6248ea8ce Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 16:31:36 -0800 Subject: [PATCH 058/197] Fixes some compiler warnings The warnings are related to: * 64-to-32-bit conversion * shadow variables --- cocos/2d/CCFont.cpp | 2 +- cocos/2d/CCLabel.cpp | 2 +- cocos/2d/CCLabelAtlas.cpp | 4 +- cocos/2d/CCLabelBMFont.cpp | 22 ++--- cocos/2d/CCNode.cpp | 6 +- cocos/2d/CCNode.h | 4 +- cocos/2d/CCParticleSystem.cpp | 2 +- cocos/2d/CCProfiling.cpp | 2 +- cocos/2d/CCProfiling.h | 12 +-- cocos/2d/CCRenderTexture.cpp | 6 +- cocos/2d/CCSpriteBatchNode.cpp | 6 +- cocos/2d/CCSpriteBatchNode.h | 6 +- cocos/2d/CCTexture2D.cpp | 81 +++++++++-------- cocos/2d/CCTexture2D.h | 88 +++++++++---------- cocos/2d/CCTextureAtlas.cpp | 34 +++---- cocos/2d/CCTextureAtlas.h | 34 +++---- cocos/2d/ccCArray.cpp | 70 +++++++-------- cocos/2d/ccCArray.h | 34 +++---- cocos/2d/platform/CCEGLViewProtocol.cpp | 22 ++--- cocos/2d/platform/CCEGLViewProtocol.h | 10 +-- cocos/2d/platform/CCFileUtils.cpp | 2 +- cocos/2d/platform/ios/EAGLView.mm | 40 ++++----- cocos/2d/platform/mac/CCEGLView.mm | 6 +- cocos/2d/platform/mac/EAGLView.mm | 12 +-- cocos/base/CCArray.cpp | 52 +++++------ cocos/base/CCArray.h | 32 +++---- .../cocostudio/CCActionNode.cpp | 2 +- cocos/physics/CCPhysicsShape.cpp | 6 +- cocos/physics/CCPhysicsShape.h | 16 ++-- cocos/physics/CCPhysicsWorld.cpp | 8 +- 30 files changed, 313 insertions(+), 310 deletions(-) diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index cad004a906..3dc8271499 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -75,7 +75,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG default: if (customGlyphs) { - int lenght = strlen(customGlyphs); + size_t lenght = strlen(customGlyphs); _customGlyphs = new char [lenght + 2]; memcpy(_customGlyphs, customGlyphs, lenght); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 09192c0e89..68cc984636 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -158,7 +158,7 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment if (_commonLineHeight <= 0) return false; - int numLetter = 0; +// int numLetter = 0; unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); if(!utf16String) return false; diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index e96df277b5..ca28f930cb 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -113,7 +113,7 @@ bool LabelAtlas::initWithString(const char *theString, const char *fntFile) //CCLabelAtlas - Atlas generation void LabelAtlas::updateAtlasValues() { - int n = _string.length(); + size_t n = _string.length(); const unsigned char *s = (unsigned char*)_string.c_str(); @@ -188,7 +188,7 @@ void LabelAtlas::updateAtlasValues() //CCLabelAtlas - LabelProtocol void LabelAtlas::setString(const char *label) { - int len = strlen(label); + size_t len = strlen(label); if (len > _textureAtlas->getTotalQuads()) { _textureAtlas->resizeCapacity(len); diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 601187d619..a9270757c7 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -200,7 +200,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr std::string strLeft = contents->getCString(); while (strLeft.length() > 0) { - int pos = strLeft.find('\n'); + size_t pos = strLeft.find('\n'); if (pos != (int)std::string::npos) { @@ -267,8 +267,8 @@ void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fnt ////////////////////////////////////////////////////////////////////////// // page ID. Sanity check - int index = line.find('=')+1; - int index2 = line.find(' ', index); + long index = line.find('=')+1; + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); CCASSERT(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); // file @@ -288,8 +288,8 @@ void CCBMFontConfiguration::parseInfoArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // padding - int index = line.find("padding="); - int index2 = line.find(' ', index); + long index = line.find("padding="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "padding=%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left); CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom); @@ -303,8 +303,8 @@ void CCBMFontConfiguration::parseCommonArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // Height - int index = line.find("lineHeight="); - int index2 = line.find(' ', index); + long index = line.find("lineHeight="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "lineHeight=%d", &_commonHeight); // scaleW. sanity check @@ -334,8 +334,8 @@ void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontD ////////////////////////////////////////////////////////////////////////// // Character ID - int index = line.find("id="); - int index2 = line.find(' ', index); + long index = line.find("id="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "id=%u", &characterDefinition->charID); @@ -385,8 +385,8 @@ void CCBMFontConfiguration::parseKerningEntry(std::string line) // first int first; - int index = line.find("first="); - int index2 = line.find(' ', index); + long index = line.find("first="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "first=%d", &first); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index cb1fb62f6c..e329f49c3e 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -402,7 +402,7 @@ void Node::setPositionY(float y) setPosition(Point(_position.x, y)); } -unsigned int Node::getChildrenCount() const +long Node::getChildrenCount() const { return _children ? _children->count() : 0; } @@ -694,7 +694,7 @@ void Node::removeChild(Node* child, bool cleanup /* = true */) return; } - int index = _children->getIndexOfObject(child); + long index = _children->getIndexOfObject(child); if( index != CC_INVALID_INDEX ) this->detachChild( child, index, cleanup ); } @@ -754,7 +754,7 @@ void Node::removeAllChildrenWithCleanup(bool cleanup) } -void Node::detachChild(Node *child, int childIndex, bool doCleanup) +void Node::detachChild(Node *child, long childIndex, bool doCleanup) { // IMPORTANT: // -1st do onExit diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index cde05c34c3..5a363c8053 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -644,7 +644,7 @@ public: * * @return The amount of children. */ - unsigned int getChildrenCount() const; + long getChildrenCount() const; /** * Sets the parent node @@ -1421,7 +1421,7 @@ protected: void insertChild(Node* child, int z); /// Removes a child, call child->onExit(), do cleanup, remove it from children array. - void detachChild(Node *child, int index, bool doCleanup); + void detachChild(Node *child, long index, bool doCleanup); /// Convert cocos2d coordinates to UI windows coordinate. Point convertToWindowSpace(const Point& nodePoint) const; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index a42ac234cb..785251ca7a 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -388,7 +388,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn const char *textureData = dictionary->valueForKey("textureImageData")->getCString(); CCASSERT(textureData, ""); - int dataLen = strlen(textureData); + long dataLen = strlen(textureData); if(dataLen != 0) { // if it fails, try to get it from the base64-gzipped data diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 2794b3b183..3cd9878375 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName) CCASSERT(timer, "CCProfilingTimer not found"); - int duration = chrono::duration_cast(now - timer->_startTime).count(); + long duration = chrono::duration_cast(now - timer->_startTime).count(); timer->totalTime += duration; timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f; diff --git a/cocos/2d/CCProfiling.h b/cocos/2d/CCProfiling.h index d68dc6f918..b79c08c991 100644 --- a/cocos/2d/CCProfiling.h +++ b/cocos/2d/CCProfiling.h @@ -134,12 +134,12 @@ public: std::string _nameStr; std::chrono::high_resolution_clock::time_point _startTime; - int _averageTime1; - int _averageTime2; - int minTime; - int maxTime; - long long totalTime; - int numberOfCalls; + long _averageTime1; + long _averageTime2; + long minTime; + long maxTime; + long totalTime; + long numberOfCalls; }; extern void ProfilingBeginTimingBlock(const char *timerName); diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index d76c258f87..17697c9de5 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -198,8 +198,8 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); // textures must be power of two squared - unsigned int powW = 0; - unsigned int powH = 0; + long powW = 0; + long powH = 0; if (Configuration::getInstance()->supportsNPOT()) { @@ -212,7 +212,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat powH = ccNextPOT(h); } - int dataLen = (int)(powW * powH * 4); + long dataLen = (long)(powW * powH * 4); data = malloc(dataLen); CC_BREAK_IF(! data); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index d531a571dd..820a999401 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, int capacity * creation with File Image */ -SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = DEFAULT_CAPACITY*/) +SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, long capacity/* = DEFAULT_CAPACITY*/) { SpriteBatchNode *batchNode = new SpriteBatchNode(); batchNode->initWithFile(fileImage, capacity); @@ -76,7 +76,7 @@ SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = /* * init with Texture2D */ -bool SpriteBatchNode::initWithTexture(Texture2D *tex, int capacity) +bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -112,7 +112,7 @@ bool SpriteBatchNode::init() /* * init with FileImage */ -bool SpriteBatchNode::initWithFile(const char* fileImage, int capacity) +bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity) { Texture2D *texture2D = TextureCache::getInstance()->addImage(fileImage); return initWithTexture(texture2D, capacity); diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 6ba402fe57..8d1b930771 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -74,7 +74,7 @@ public: The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. */ - static SpriteBatchNode* create(const char* fileImage, int capacity = DEFAULT_CAPACITY); + static SpriteBatchNode* create(const char* fileImage, long capacity = DEFAULT_CAPACITY); /** * @js ctor */ @@ -88,14 +88,14 @@ public: /** initializes a SpriteBatchNode with a texture2d and capacity of children. The capacity will be increased in 33% in runtime if it run out of space. */ - bool initWithTexture(Texture2D *tex, int capacity); + bool initWithTexture(Texture2D *tex, long capacity); /** initializes a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children. The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. * @js init * @lua init */ - bool initWithFile(const char* fileImage, int capacity); + bool initWithFile(const char* fileImage, long capacity); bool init(); /** returns the TextureAtlas object */ diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 84a6822dda..397bdbf68a 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -119,7 +119,7 @@ static bool _PVRHaveAlphaPremultiplied = false; //conventer function // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBB -void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i=0; i < dataLen; ++i) { @@ -130,7 +130,7 @@ void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsign } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB -void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 1; i < l; i += 2) { @@ -141,7 +141,7 @@ void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsi } // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0; i < dataLen; ++i) { @@ -153,7 +153,7 @@ void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsi } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 1; i < l; i += 2) { @@ -165,7 +165,7 @@ void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, un } // IIIIIIII -> RRRRRGGGGGGBBBBB -void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -177,7 +177,7 @@ void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsign } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGGBBBBB -void Texture2D::convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 1; i < l; i += 2) @@ -189,7 +189,7 @@ void Texture2D::convertAI88ToRGB565(const unsigned char* data, int dataLen, unsi } // IIIIIIII -> RRRRGGGGBBBBAAAA -void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -202,7 +202,7 @@ void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsi } // IIIIIIIIAAAAAAAA -> RRRRGGGGBBBBAAAA -void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 1; i < l; i += 2) @@ -215,7 +215,7 @@ void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, int dataLen, un } // IIIIIIII -> RRRRRGGGGGBBBBBA -void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -228,7 +228,7 @@ void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsign } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGBBBBBA -void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 1; i < l; i += 2) @@ -241,7 +241,7 @@ void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsi } // IIIIIIII -> IIIIIIIIAAAAAAAA -void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -252,7 +252,7 @@ void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned } // IIIIIIIIAAAAAAAA -> AAAAAAAA -void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 1; i < dataLen; i += 2) { @@ -261,7 +261,7 @@ void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned } // IIIIIIIIAAAAAAAA -> IIIIIIII -void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 1; i < l; i += 2) { @@ -270,7 +270,7 @@ void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 2; i < l; i += 3) { @@ -282,7 +282,7 @@ void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB -void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 3; i < l; i += 4) { @@ -293,7 +293,7 @@ void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGGBBBBB -void Texture2D::convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 2; i < l; i += 3) @@ -305,7 +305,7 @@ void Texture2D::convertRGB888ToRGB565(const unsigned char* data, int dataLen, un } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRGGGGGGBBBBB -void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 3; i < l; i += 4) @@ -317,7 +317,7 @@ void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIII -void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 2; i < l; i += 3) { @@ -326,7 +326,7 @@ void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsign } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIII -void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 3; i < l; i += 4) { @@ -335,7 +335,7 @@ void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsi } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> AAAAAAAA -void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen -3; i < l; i += 4) { @@ -344,7 +344,7 @@ void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsi } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIIIAAAAAAAA -void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 2; i < l; i += 3) { @@ -355,7 +355,7 @@ void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsi // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIIIAAAAAAAA -void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 3; i < l; i += 4) { @@ -365,7 +365,7 @@ void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, un } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRGGGGBBBBAAAA -void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 2; i < l; i += 3) @@ -378,7 +378,7 @@ void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRGGGGBBBBAAAA -void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 3; i < l; i += 4) @@ -391,10 +391,10 @@ void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA -void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (long i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G @@ -404,10 +404,10 @@ void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, un } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA -void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 2; i < l; i += 4) + for (long i = 0, l = dataLen - 2; i < l; i += 4) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G @@ -451,12 +451,12 @@ Texture2D::PixelFormat Texture2D::getPixelFormat() const return _pixelFormat; } -unsigned int Texture2D::getPixelsWide() const +long Texture2D::getPixelsWide() const { return _pixelsWide; } -unsigned int Texture2D::getPixelsHigh() const +long Texture2D::getPixelsHigh() const { return _pixelsHigh; } @@ -529,8 +529,10 @@ bool Texture2D::hasPremultipliedAlpha() const return _hasPremultipliedAlpha; } -bool Texture2D::initWithData(const void *data, int dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize) +bool Texture2D::initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize) { + CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size"); + //if data has no mipmaps, we will consider it has only one mipmap MipmapInfo mipmap; mipmap.address = (unsigned char*)data; @@ -544,10 +546,11 @@ bool Texture2D::initWithData(const void *data, int dataLen, Texture2D::PixelForm } -bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh) +bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, long pixelsWide, long pixelsHigh) { //the pixelFormat must be a certain value - CCAssert(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); + CCASSERT(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); + CCASSERT(pixelsWide>0 && pixelsHigh>0, "Invalid size"); if (mipmapsNum <= 0) { @@ -670,7 +673,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat const char* Texture2D::description(void) const { - return String::createWithFormat("", _name, _pixelsWide, _pixelsHigh, _maxS, _maxT)->getCString(); + return String::createWithFormat("", _name, (long)_pixelsWide, (long)_pixelsHigh, _maxS, _maxT)->getCString(); } // implementation Texture2D (Image) @@ -771,7 +774,7 @@ bool Texture2D::initWithImage(Image *image, PixelFormat format) } } -Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) { @@ -820,7 +823,7 @@ Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, i return format; } -Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) { @@ -875,7 +878,7 @@ Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, return format; } -Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) { @@ -923,7 +926,7 @@ Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* dat return format; } -Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) @@ -995,7 +998,7 @@ rgb(2) -> 1235678 rgba(1) -> 12345678 */ -Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, int dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (originFormat) { diff --git a/cocos/2d/CCTexture2D.h b/cocos/2d/CCTexture2D.h index 6f15273f9c..bdb28ce582 100644 --- a/cocos/2d/CCTexture2D.h +++ b/cocos/2d/CCTexture2D.h @@ -120,13 +120,13 @@ public: struct PixelFormatInfo { - PixelFormatInfo(GLenum internalFormat, GLenum format, GLenum type, int bpp, bool compressed, bool alpha) - : internalFormat(internalFormat) - , format(format) - , type(type) - , bpp(bpp) - , compressed(compressed) - , alpha(alpha) + PixelFormatInfo(GLenum anInternalFormat, GLenum aFormat, GLenum aType, int aBpp, bool aCompressed, bool anAlpha) + : internalFormat(anInternalFormat) + , format(aFormat) + , type(aType) + , bpp(aBpp) + , compressed(aCompressed) + , alpha(anAlpha) {} GLenum internalFormat; @@ -216,10 +216,10 @@ public: * @js NA * @lua NA */ - bool initWithData(const void *data, int dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize); + bool initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize); /** Initializes with mipmaps */ - bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh); + bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh); /** Drawing extensions to make it easy to draw basic quads using a Texture2D object. @@ -326,10 +326,10 @@ public: Texture2D::PixelFormat getPixelFormat() const; /** Gets the width of the texture in pixels */ - unsigned int getPixelsWide() const; + long getPixelsWide() const; /** Gets the height of the texture in pixels */ - unsigned int getPixelsHigh() const; + long getPixelsHigh() const; /** Gets the texture name */ GLuint getName() const; @@ -360,56 +360,56 @@ private: Convert the format to the format param you specified, if the format is PixelFormat::Automatic, it will detect it automatically and convert to the closest format for you. It will return the converted format to you. if the outData != data, you must delete it manually. */ - static PixelFormat convertDataToFormat(const unsigned char* data, int dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertI8ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertAI88ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertRGB888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); //I8 to XXX - static void convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); //AI88 to XXX - static void convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToI8(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData); //RGB888 to XXX - static void convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); //RGBA8888 to XXX - static void convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); protected: /** pixel format of the texture */ Texture2D::PixelFormat _pixelFormat; /** width in pixels */ - unsigned int _pixelsWide; + long _pixelsWide; /** height in pixels */ - unsigned int _pixelsHigh; + long _pixelsHigh; /** texture name */ GLuint _name; diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index c83a042dde..3ef2a365c4 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -107,7 +107,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas * TextureAtlas::create(const char* file, int capacity) +TextureAtlas * TextureAtlas::create(const char* file, long capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if(textureAtlas && textureAtlas->initWithFile(file, capacity)) @@ -119,7 +119,7 @@ TextureAtlas * TextureAtlas::create(const char* file, int capacity) return NULL; } -TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) +TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if (textureAtlas && textureAtlas->initWithTexture(texture, capacity)) @@ -131,7 +131,7 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) return NULL; } -bool TextureAtlas::initWithFile(const char * file, int capacity) +bool TextureAtlas::initWithFile(const char * file, long capacity) { // retained in property Texture2D *texture = TextureCache::getInstance()->addImage(file); @@ -147,7 +147,7 @@ bool TextureAtlas::initWithFile(const char * file, int capacity) } } -bool TextureAtlas::initWithTexture(Texture2D *texture, int capacity) +bool TextureAtlas::initWithTexture(Texture2D *texture, long capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -310,7 +310,7 @@ void TextureAtlas::mapBuffers() // TextureAtlas - Update, Insert, Move & Remove -void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index) +void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, long index) { CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index"); @@ -323,7 +323,7 @@ void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index) } -void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index) +void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index) { CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index"); @@ -347,7 +347,7 @@ void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index) } -void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) +void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount"); @@ -378,7 +378,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) _dirty = true; } -void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) +void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) { CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -407,7 +407,7 @@ void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) _dirty = true; } -void TextureAtlas::removeQuadAtIndex(int index) +void TextureAtlas::removeQuadAtIndex(long index) { CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); @@ -426,7 +426,7 @@ void TextureAtlas::removeQuadAtIndex(int index) _dirty = true; } -void TextureAtlas::removeQuadsAtIndex(int index, int amount) +void TextureAtlas::removeQuadsAtIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); @@ -448,7 +448,7 @@ void TextureAtlas::removeAllQuads() } // TextureAtlas - Resize -bool TextureAtlas::resizeCapacity(int newCapacity) +bool TextureAtlas::resizeCapacity(long newCapacity) { CCASSERT(newCapacity>=0, "capacity >= 0"); if( newCapacity == _capacity ) @@ -522,13 +522,13 @@ bool TextureAtlas::resizeCapacity(int newCapacity) return true; } -void TextureAtlas::increaseTotalQuadsWith(int amount) +void TextureAtlas::increaseTotalQuadsWith(long amount) { CCASSERT(amount>=0, "amount >= 0"); _totalQuads += amount; } -void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) +void TextureAtlas::moveQuadsFromIndex(long oldIndex, long amount, long newIndex) { CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -560,7 +560,7 @@ void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) _dirty = true; } -void TextureAtlas::moveQuadsFromIndex(int index, int newIndex) +void TextureAtlas::moveQuadsFromIndex(long index, long newIndex) { CCASSERT(index>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds"); @@ -568,7 +568,7 @@ void TextureAtlas::moveQuadsFromIndex(int index, int newIndex) memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0])); } -void TextureAtlas::fillWithEmptyQuadsFromIndex(int index, int amount) +void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0, "values must be >= 0"); V3F_C4B_T2F_Quad quad; @@ -588,13 +588,13 @@ void TextureAtlas::drawQuads() this->drawNumberOfQuads(_totalQuads, 0); } -void TextureAtlas::drawNumberOfQuads(int numberOfQuads) +void TextureAtlas::drawNumberOfQuads(long numberOfQuads) { CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0"); this->drawNumberOfQuads(numberOfQuads, 0); } -void TextureAtlas::drawNumberOfQuads(int numberOfQuads, int start) +void TextureAtlas::drawNumberOfQuads(long numberOfQuads, long start) { CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0"); diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index 4c1bb6436a..1e5ec742d7 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -59,13 +59,13 @@ public: /** creates a TextureAtlas with an filename and with an initial capacity for Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* create(const char* file , int capacity); + static TextureAtlas* create(const char* file , long capacity); /** creates a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for n Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* createWithTexture(Texture2D *texture, int capacity); + static TextureAtlas* createWithTexture(Texture2D *texture, long capacity); /** * @js ctor */ @@ -81,7 +81,7 @@ public: * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) */ - bool initWithFile(const char* file, int capacity); + bool initWithFile(const char* file, long capacity); /** initializes a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for Quads. @@ -89,43 +89,43 @@ public: * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) */ - bool initWithTexture(Texture2D *texture, int capacity); + bool initWithTexture(Texture2D *texture, long capacity); /** updates a Quad (texture, vertex and color) at a certain index * index must be between 0 and the atlas capacity - 1 @since v0.8 */ - void updateQuad(V3F_C4B_T2F_Quad* quad, int index); + void updateQuad(V3F_C4B_T2F_Quad* quad, long index); /** Inserts a Quad (texture, vertex and color) at a certain index index must be between 0 and the atlas capacity - 1 @since v0.8 */ - void insertQuad(V3F_C4B_T2F_Quad* quad, int index); + void insertQuad(V3F_C4B_T2F_Quad* quad, long index); /** Inserts a c array of quads at a given index index must be between 0 and the atlas capacity - 1 this method doesn't enlarge the array when amount + index > totalQuads @since v1.1 */ - void insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount); + void insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount); /** Removes the quad that is located at a certain index and inserts it at a new index This operation is faster than removing and inserting in a quad in 2 different steps @since v0.7.2 */ - void insertQuadFromIndex(int fromIndex, int newIndex); + void insertQuadFromIndex(long fromIndex, long newIndex); /** removes a quad at a given index number. The capacity remains the same, but the total number of quads to be drawn is reduced in 1 @since v0.7.2 */ - void removeQuadAtIndex(int index); + void removeQuadAtIndex(long index); /** removes a amount of quads starting from index @since 1.1 */ - void removeQuadsAtIndex(int index, int amount); + void removeQuadsAtIndex(long index, long amount); /** removes all Quads. The TextureAtlas capacity remains untouched. No memory is freed. The total number of quads to be drawn will be 0 @@ -138,19 +138,19 @@ public: * It returns true if the resize was successful. * If it fails to resize the capacity it will return false with a new capacity of 0. */ - bool resizeCapacity(int capacity); + bool resizeCapacity(long capacity); /** Used internally by ParticleBatchNode don't use this unless you know what you're doing @since 1.1 */ - void increaseTotalQuadsWith(int amount); + void increaseTotalQuadsWith(long amount); /** Moves an amount of quads from oldIndex at newIndex @since v1.1 */ - void moveQuadsFromIndex(int oldIndex, int amount, int newIndex); + void moveQuadsFromIndex(long oldIndex, long amount, long newIndex); /** Moves quads from index till totalQuads to the newIndex @@ -158,26 +158,26 @@ public: This method doesn't enlarge the array if newIndex + quads to be moved > capacity @since 1.1 */ - void moveQuadsFromIndex(int index, int newIndex); + void moveQuadsFromIndex(long index, long newIndex); /** Ensures that after a realloc quads are still empty Used internally by ParticleBatchNode @since 1.1 */ - void fillWithEmptyQuadsFromIndex(int index, int amount); + void fillWithEmptyQuadsFromIndex(long index, long amount); /** draws n quads * n can't be greater than the capacity of the Atlas */ - void drawNumberOfQuads(int n); + void drawNumberOfQuads(long n); /** draws n quads from an index (offset). n + start can't be greater than the capacity of the atlas @since v1.0 */ - void drawNumberOfQuads(int numberOfQuads, int start); + void drawNumberOfQuads(long numberOfQuads, long start); /** draws all the Atlas's Quads */ diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index cd8f275311..f280bc5787 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -28,10 +28,10 @@ THE SOFTWARE. NS_CC_BEGIN -const int CC_INVALID_INDEX = -1; +const long CC_INVALID_INDEX = -1; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(int capacity) +ccArray* ccArrayNew(long capacity) { if (capacity == 0) capacity = 7; @@ -68,7 +68,7 @@ void ccArrayDoubleCapacity(ccArray *arr) arr->arr = newArr; } -void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) +void ccArrayEnsureExtraCapacity(ccArray *arr, long extra) { while (arr->max < arr->num + extra) { @@ -82,7 +82,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) void ccArrayShrink(ccArray *arr) { - int newSize = 0; + long newSize = 0; //only resize when necessary if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) @@ -104,11 +104,11 @@ void ccArrayShrink(ccArray *arr) } /** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */ -int ccArrayGetIndexOfObject(ccArray *arr, Object* object) +long ccArrayGetIndexOfObject(ccArray *arr, Object* object) { - const int arrNum = arr->num; + const long arrNum = arr->num; Object** ptr = arr->arr; - for(int i = 0; i < arrNum; ++i, ++ptr) + for(long i = 0; i < arrNum; ++i, ++ptr) { if( *ptr == object ) return i; @@ -143,7 +143,7 @@ void ccArrayAppendObjectWithResize(ccArray *arr, Object* object) enough capacity. */ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr) { - for(int i = 0; i < plusArr->num; i++) + for(long i = 0; i < plusArr->num; i++) { ccArrayAppendObject(arr, plusArr->arr[i]); } @@ -157,14 +157,14 @@ void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr) } /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index) +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index) { CCASSERT(index<=arr->num, "Invalid index. Out of bounds"); CCASSERT(object != NULL, "Invalid parameter!"); ccArrayEnsureExtraCapacity(arr, 1); - int remaining = arr->num - index; + long remaining = arr->num - index; if( remaining > 0) { memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining ); @@ -176,7 +176,7 @@ void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index) } /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2) +void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2) { CCASSERT(index1>=0 && index1 < arr->num, "(1) Invalid index. Out of bounds"); CCASSERT(index2>=0 && index2 < arr->num, "(2) Invalid index. Out of bounds"); @@ -198,7 +198,7 @@ void ccArrayRemoveAllObjects(ccArray *arr) /** Removes object at specified index and pushes back all subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = true*/) +void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj/* = true*/) { CCASSERT(arr && arr->num > 0 && index>=0 && index < arr->num, "Invalid index. Out of bounds"); if (bReleaseObj) @@ -208,7 +208,7 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr arr->num--; - int remaining = arr->num - index; + long remaining = arr->num - index; if(remaining>0) { memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*)); @@ -218,16 +218,16 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr /** Removes object at specified index and fills the gap with the last object, thereby avoiding the need to push back subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index) +void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index) { CC_SAFE_RELEASE(arr->arr[index]); - int last = --arr->num; + long last = --arr->num; arr->arr[index] = arr->arr[last]; } void ccArrayFastRemoveObject(ccArray *arr, Object* object) { - int index = ccArrayGetIndexOfObject(arr, object); + long index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayFastRemoveObjectAtIndex(arr, index); @@ -238,7 +238,7 @@ void ccArrayFastRemoveObject(ccArray *arr, Object* object) found the function has no effect. */ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/) { - int index = ccArrayGetIndexOfObject(arr, object); + long index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj); @@ -249,7 +249,7 @@ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true first matching instance in arr will be removed. */ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) { - for(int i = 0; i < minusArr->num; i++) + for(long i = 0; i < minusArr->num; i++) { ccArrayRemoveObject(arr, minusArr->arr[i]); } @@ -259,8 +259,8 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) matching instances in arr will be removed. */ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) { - int back = 0; - int i = 0; + long back = 0; + long i = 0; for( i = 0; i < arr->num; i++) { @@ -282,7 +282,7 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) // #pragma mark ccCArray for Values (c structures) /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(int capacity) +ccCArray* ccCArrayNew(long capacity) { if (capacity == 0) { @@ -317,15 +317,15 @@ void ccCArrayDoubleCapacity(ccCArray *arr) } /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra) +void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra) { ccArrayEnsureExtraCapacity((ccArray*)arr,extra); } /** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */ -int ccCArrayGetIndexOfValue(ccCArray *arr, void* value) +long ccCArrayGetIndexOfValue(ccCArray *arr, void* value) { - for( int i = 0; i < arr->num; i++) + for(long i = 0; i < arr->num; i++) { if( arr->arr[i] == value ) return i; @@ -340,11 +340,11 @@ bool ccCArrayContainsValue(ccCArray *arr, void* value) } /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index) +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index) { CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index"); - int remaining = arr->num - index; + long remaining = arr->num - index; // make sure it has enough capacity if (arr->num + 1 == arr->max) { @@ -385,7 +385,7 @@ void ccCArrayAppendValueWithResize(ccCArray *arr, void* value) enough capacity. */ void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) { - for( int i = 0; i < plusArr->num; i++) + for( long i = 0; i < plusArr->num; i++) { ccCArrayAppendValue(arr, plusArr->arr[i]); } @@ -408,9 +408,9 @@ void ccCArrayRemoveAllValues(ccCArray *arr) Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) +void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index) { - for( int last = --arr->num; index < last; index++) + for( long last = --arr->num; index < last; index++) { arr->arr[index] = arr->arr[index + 1]; } @@ -421,9 +421,9 @@ void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) +void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index) { - int last = --arr->num; + long last = --arr->num; arr->arr[index] = arr->arr[last]; } @@ -432,7 +432,7 @@ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) */ void ccCArrayRemoveValue(ccCArray *arr, void* value) { - int index = ccCArrayGetIndexOfValue(arr, value); + long index = ccCArrayGetIndexOfValue(arr, value); if (index != CC_INVALID_INDEX) { ccCArrayRemoveValueAtIndex(arr, index); @@ -444,7 +444,7 @@ void ccCArrayRemoveValue(ccCArray *arr, void* value) */ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) { - for(int i = 0; i < minusArr->num; i++) + for(long i = 0; i < minusArr->num; i++) { ccCArrayRemoveValue(arr, minusArr->arr[i]); } @@ -455,9 +455,9 @@ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) */ void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) { - int back = 0; + long back = 0; - for(int i = 0; i < arr->num; i++) + for(long i = 0; i < arr->num; i++) { if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) { diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index fff5152904..2bfff6224f 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -51,20 +51,20 @@ THE SOFTWARE. NS_CC_BEGIN -extern const int CC_INVALID_INDEX; +extern const long CC_INVALID_INDEX; // Easy integration #define CCARRAYDATA_FOREACH(__array__, __object__) \ -__object__=__array__->arr[0]; for(int i=0, num=__array__->num; iarr[i]) \ +__object__=__array__->arr[0]; for(long i=0, num=__array__->num; iarr[i]) \ typedef struct _ccArray { - int num, max; + long num, max; Object** arr; } ccArray; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(int capacity); +ccArray* ccArrayNew(long capacity); /** Frees array after removing all remaining objects. Silently ignores nil arr. */ void ccArrayFree(ccArray*& arr); @@ -73,13 +73,13 @@ void ccArrayFree(ccArray*& arr); void ccArrayDoubleCapacity(ccArray *arr); /** Increases array capacity such that max >= num + extra. */ -void ccArrayEnsureExtraCapacity(ccArray *arr, int extra); +void ccArrayEnsureExtraCapacity(ccArray *arr, long extra); /** shrinks the array so the memory footprint corresponds with the number of items */ void ccArrayShrink(ccArray *arr); /** Returns index of first occurrence of object, NSNotFound if object not found. */ -int ccArrayGetIndexOfObject(ccArray *arr, Object* object); +long ccArrayGetIndexOfObject(ccArray *arr, Object* object); /** Returns a Boolean value that indicates whether object is present in array. */ bool ccArrayContainsObject(ccArray *arr, Object* object); @@ -98,22 +98,22 @@ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr); void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr); /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index); +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index); /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2); +void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2); /** Removes all objects from arr */ void ccArrayRemoveAllObjects(ccArray *arr); /** Removes object at specified index and pushes back all subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj = true); +void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj = true); /** Removes object at specified index and fills the gap with the last object, thereby avoiding the need to push back subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index); +void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index); void ccArrayFastRemoveObject(ccArray *arr, Object* object); @@ -133,12 +133,12 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr); // #pragma mark ccCArray for Values (c structures) typedef struct _ccCArray { - int num, max; + long num, max; void** arr; } ccCArray; /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(int capacity); +ccCArray* ccCArrayNew(long capacity); /** Frees C array after removing all remaining values. Silently ignores nil arr. */ void ccCArrayFree(ccCArray *arr); @@ -147,16 +147,16 @@ void ccCArrayFree(ccCArray *arr); void ccCArrayDoubleCapacity(ccCArray *arr); /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra); +void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra); /** Returns index of first occurrence of value, NSNotFound if value not found. */ -int ccCArrayGetIndexOfValue(ccCArray *arr, void* value); +long ccCArrayGetIndexOfValue(ccCArray *arr, void* value); /** Returns a Boolean value that indicates whether value is present in the C array. */ bool ccCArrayContainsValue(ccCArray *arr, void* value); /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index); +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index); /** Appends an value. Behavior undefined if array doesn't have enough capacity. */ void ccCArrayAppendValue(ccCArray *arr, void* value); @@ -178,14 +178,14 @@ void ccCArrayRemoveAllValues(ccCArray *arr); Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index); +void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index); /** Removes value at specified index and fills the gap with the last value, thereby avoiding the need to push back subsequent values. Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index); +void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index); /** Searches for the first occurrence of value and removes it. If value is not found the function has no effect. @since v0.99.4 diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 9004f4c6fc..0296eb5a17 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -12,7 +12,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { NULL }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -201,9 +201,9 @@ const char* EGLViewProtocol::getViewName() return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesBegin(int num, long ids[], float xs[], float ys[]) { - void* id = nullptr; + long id = 0; float x = 0.0f; float y = 0.0f; int nUnusedIndex = 0; @@ -251,9 +251,9 @@ void EGLViewProtocol::handleTouchesBegin(int num, void* ids[], float xs[], float dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesMove(int num, long ids[], float xs[], float ys[]) { - void* id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -283,7 +283,7 @@ void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float else { // It is error, should return. - CCLOG("Moving touches with id: %p error", id); + CCLOG("Moving touches with id: %ld error", id); return; } } @@ -299,9 +299,9 @@ void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]) { - void* id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -336,7 +336,7 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } else { - CCLOG("Ending touches with id: %d error", id); + CCLOG("Ending touches with id: %ld error", id); return; } @@ -359,12 +359,12 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesEnd(int num, long ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesCancel(int num, long ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index 84bb1b4ee3..ed54d59712 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -136,10 +136,10 @@ public: const char* getViewName(); /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, void* ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, void* ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, void* ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, long ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -156,7 +156,7 @@ public: */ float getScaleY() const; private: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]); protected: EGLTouchDelegate* _delegate; diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index e9e01589e2..d7244ba6f0 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -451,7 +451,7 @@ NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ Dictionary* FileUtils::createDictionaryWithContentsOfFile(const std::string& filename) {return NULL;} -bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return NULL;} +bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return false;} Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename) {return NULL;} #endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */ diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index 771d32fd1f..5536a63752 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -75,7 +75,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #define IOS_MAX_TOUCHES_COUNT 10 -static CCEAGLView *view = 0; +static CCEAGLView *__view = 0; @interface CCEAGLView (Private) - (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; @@ -117,7 +117,7 @@ static CCEAGLView *view = 0; + (id) sharedEGLView { - return view; + return __view; } - (id) initWithFrame:(CGRect)frame @@ -147,14 +147,14 @@ static CCEAGLView *view = 0; } - view = self; + __view = self; originalRect_ = self.frame; self.keyboardShowNotification = nil; - if ([view respondsToSelector:@selector(setContentScaleFactor:)]) + if ([__view respondsToSelector:@selector(setContentScaleFactor:)]) { - view.contentScaleFactor = [[UIScreen mainScreen] scale]; + __view.contentScaleFactor = [[UIScreen mainScreen] scale]; } } @@ -180,7 +180,7 @@ static CCEAGLView *view = 0; } } - view = self; + __view = self; return self; } @@ -205,13 +205,13 @@ static CCEAGLView *view = 0; -(int) getWidth { CGSize bound = [self bounds].size; - return bound.width * self.contentScaleFactor; + return (int)bound.width * self.contentScaleFactor; } -(int) getHeight { CGSize bound = [self bounds].size; - return bound.height * self.contentScaleFactor; + return (int)bound.height * self.contentScaleFactor; } @@ -406,11 +406,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (long*)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -426,11 +426,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesMove(i, (long*)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -447,11 +447,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (long*)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -468,11 +468,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (long*)ids, xs, ys); } #pragma mark - diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index af3863476d..d66f1dc17c 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -202,7 +202,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -211,7 +211,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -249,7 +249,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm index ff456d0e6a..1894440ced 100644 --- a/cocos/2d/platform/mac/EAGLView.mm +++ b/cocos/2d/platform/mac/EAGLView.mm @@ -327,7 +327,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -335,7 +335,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (long*)ids, xs, ys); } - (void)mouseMoved:(NSEvent *)theEvent @@ -351,7 +351,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -359,7 +359,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (long*)ids, xs, ys); } - (void)mouseUp:(NSEvent *)theEvent @@ -370,7 +370,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -378,7 +378,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (long*)ids, xs, ys); } - (void)rightMouseDown:(NSEvent *)theEvent { diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index 3a55d6050d..90c88ebe34 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -105,7 +105,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +Array* Array::createWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -182,7 +182,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool Array::initWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -200,7 +200,7 @@ int Array::getIndexOfObject(Object* object) const { auto it = data.begin(); - for (int i = 0; it != data.end(); ++it, ++i) + for (long i = 0; it != data.end(); ++it, ++i) { if (it->get() == object) { @@ -238,7 +238,7 @@ bool Array::containsObject(Object* object) const bool Array::isEqualToArray(Array* otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -279,7 +279,7 @@ void Array::removeObject(Object* object, bool releaseObj /* ignored */) data.erase( std::remove( data.begin(), data.end(), object ) ); } -void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) +void Array::removeObjectAtIndex(long index, bool releaseObj /* ignored */) { auto obj = data[index]; data.erase( data.begin() + index ); @@ -295,7 +295,7 @@ void Array::removeAllObjects() data.erase(std::begin(data), std::end(data)); } -void Array::fastRemoveObjectAtIndex(int index) +void Array::fastRemoveObjectAtIndex(long index) { removeObjectAtIndex(index); } @@ -315,12 +315,12 @@ void Array::exchangeObject(Object* object1, Object* object2) std::swap( data[idx1], data[idx2] ); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void Array::exchangeObjectAtIndex(long index1, long index2) { std::swap( data[index1], data[index2] ); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) +void Array::replaceObjectAtIndex(long index, Object* object, bool releaseObject /* ignored */) { data[index] = object; } @@ -448,7 +448,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +Array* Array::createWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -531,7 +531,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool Array::initWithCapacity(long capacity) { CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); @@ -555,7 +555,7 @@ bool Array::initWithArray(Array* otherArray) return ret; } -int Array::getIndexOfObject(Object* object) const +long Array::getIndexOfObject(Object* object) const { return ccArrayGetIndexOfObject(data, object); } @@ -574,7 +574,7 @@ Object* Array::getRandomObject() r = 0; } - return data->arr[(int)(data->num * r)]; + return data->arr[(long)(data->num * r)]; } bool Array::containsObject(Object* object) const @@ -584,7 +584,7 @@ bool Array::containsObject(Object* object) const bool Array::isEqualToArray(Array* otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -606,13 +606,13 @@ void Array::addObjectsFromArray(Array* otherArray) ccArrayAppendArrayWithResize(data, otherArray->data); } -void Array::insertObject(Object* object, int index) +void Array::insertObject(Object* object, long index) { CCASSERT(data, "Array not initialized"); ccArrayInsertObjectAtIndex(data, object, index); } -void Array::setObject(Object* object, int index) +void Array::setObject(Object* object, long index) { CCASSERT(index>=0 && index < count(), "Invalid index"); @@ -635,7 +635,7 @@ void Array::removeObject(Object* object, bool releaseObj/* = true*/) ccArrayRemoveObject(data, object, releaseObj); } -void Array::removeObjectAtIndex(int index, bool releaseObj) +void Array::removeObjectAtIndex(long index, bool releaseObj) { ccArrayRemoveObjectAtIndex(data, index, releaseObj); } @@ -650,7 +650,7 @@ void Array::removeAllObjects() ccArrayRemoveAllObjects(data); } -void Array::fastRemoveObjectAtIndex(int index) +void Array::fastRemoveObjectAtIndex(long index) { ccArrayFastRemoveObjectAtIndex(data, index); } @@ -662,14 +662,14 @@ void Array::fastRemoveObject(Object* object) void Array::exchangeObject(Object* object1, Object* object2) { - int index1 = ccArrayGetIndexOfObject(data, object1); - if (index1 == UINT_MAX) + long index1 = ccArrayGetIndexOfObject(data, object1); + if (index1 == CC_INVALID_INDEX) { return; } - int index2 = ccArrayGetIndexOfObject(data, object2); - if (index2 == UINT_MAX) + long index2 = ccArrayGetIndexOfObject(data, object2); + if (index2 == CC_INVALID_INDEX) { return; } @@ -677,12 +677,12 @@ void Array::exchangeObject(Object* object1, Object* object2) ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void Array::exchangeObjectAtIndex(long index1, long index2) { ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) +void Array::replaceObjectAtIndex(long index, Object* object, bool releaseObject/* = true*/) { ccArrayInsertObjectAtIndex(data, object, index); ccArrayRemoveObjectAtIndex(data, index+1); @@ -693,10 +693,10 @@ void Array::reverseObjects() if (data->num > 1) { // floorf(), since in the case of an even number, the number of swaps stays the same - int count = (int) floorf(data->num/2.f); - int maxIndex = data->num - 1; + long count = (long) floorf(data->num/2.f); + long maxIndex = data->num - 1; - for (int i = 0; i < count ; i++) + for (long i = 0; i < count ; i++) { ccArraySwapObjectsAtIndexes(data, i, maxIndex); --maxIndex; diff --git a/cocos/base/CCArray.h b/cocos/base/CCArray.h index 7f67569faa..f68ee8b64d 100644 --- a/cocos/base/CCArray.h +++ b/cocos/base/CCArray.h @@ -250,7 +250,7 @@ public: /** Create an array with a default capacity * @js NA */ - static Array* createWithCapacity(int capacity); + static Array* createWithCapacity(long capacity); /** Create an array with from an existing array * @js NA */ @@ -295,7 +295,7 @@ public: * @js NA * @lua NA */ - bool initWithCapacity(int capacity); + bool initWithCapacity(long capacity); /** Initializes an array with an existing array * @js NA * @lua NA @@ -307,7 +307,7 @@ public: /** Returns element count of the array * @js NA */ - int count() const + long count() const { #if CC_USE_ARRAY_VECTOR return data.size(); @@ -318,7 +318,7 @@ public: /** Returns capacity of the array * @js NA */ - int capacity() const + long capacity() const { #if CC_USE_ARRAY_VECTOR return data.capacity(); @@ -330,17 +330,17 @@ public: * @js NA * @lua NA */ - int getIndexOfObject(Object* object) const; + long getIndexOfObject(Object* object) const; /** * @js NA */ - CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); } + CC_DEPRECATED_ATTRIBUTE long indexOfObject(Object* object) const { return getIndexOfObject(object); } /** Returns an element with a certain index * @js NA * @lua NA */ - Object* getObjectAtIndex(int index) + Object* getObjectAtIndex(long index) { CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); #if CC_USE_ARRAY_VECTOR @@ -349,7 +349,7 @@ public: return data->arr[index]; #endif } - CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); } + CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(long index) { return getObjectAtIndex(index); } /** Returns the last element of the array * @js NA */ @@ -401,17 +401,17 @@ public: /** Insert a certain object at a certain index * @js NA */ - void insertObject(Object* object, int index); + void insertObject(Object* object, long index); /** sets a certain object at a certain index * @js NA * @lua NA */ - void setObject(Object* object, int index); + void setObject(Object* object, long index); /** sets a certain object at a certain index without retaining. Use it with caution * @js NA * @lua NA */ - void fastSetObject(Object* object, int index) + void fastSetObject(Object* object, long index) { #if CC_USE_ARRAY_VECTOR setObject(object, index); @@ -424,7 +424,7 @@ public: * @js NA * @lua NA */ - void swap( int indexOne, int indexTwo ) + void swap( long indexOne, long indexTwo ) { CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices"); #if CC_USE_ARRAY_VECTOR @@ -447,7 +447,7 @@ public: /** Remove an element with a certain index * @js NA */ - void removeObjectAtIndex(int index, bool releaseObj = true); + void removeObjectAtIndex(long index, bool releaseObj = true); /** Remove all elements * @js NA */ @@ -463,7 +463,7 @@ public: /** Fast way to remove an element with a certain index * @js NA */ - void fastRemoveObjectAtIndex(int index); + void fastRemoveObjectAtIndex(long index); // Rearranging Content @@ -474,12 +474,12 @@ public: /** Swap two elements with certain indexes * @js NA */ - void exchangeObjectAtIndex(int index1, int index2); + void exchangeObjectAtIndex(long index1, long index2); /** Replace object at index with another object. * @js NA */ - void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true); + void replaceObjectAtIndex(long index, Object* object, bool releaseObject = true); /** Revers the array * @js NA diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index fceca8816c..f0f3828791 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -424,7 +424,7 @@ bool ActionNode::updateActionToTimeLine(float fTime) bool bFindFrame = false; ActionFrame* srcFrame = NULL; - ActionFrame* destFrame = NULL; +// ActionFrame* destFrame = NULL; for (int n = 0; n < _frameArrayNum; n++) { diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 68ef1cf351..b481e0c0d9 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -600,7 +600,7 @@ Point* PhysicsShapePolygon::getPoints(Point* points) const return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } -int PhysicsShapePolygon::getPointsCount() const +long PhysicsShapePolygon::getPointsCount() const { return ((cpPolyShape*)_info->shapes.front())->numVerts; } @@ -715,7 +715,7 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -int PhysicsShapeEdgePolygon::getPointsCount() const +long PhysicsShapeEdgePolygon::getPointsCount() const { return _info->shapes.size() + 1; } @@ -776,7 +776,7 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -int PhysicsShapeEdgeChain::getPointsCount() const +long PhysicsShapeEdgeChain::getPointsCount() const { return _info->shapes.size() + 1; } diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 31497d14a2..5bc1ca9dfa 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -50,10 +50,10 @@ typedef struct PhysicsMaterial , friction(0.0f) {} - PhysicsMaterial(float density, float restitution, float friction) - : density(density) - , restitution(restitution) - , friction(friction) + PhysicsMaterial(float aDensity, float aRestitution, float aFriction) + : density(aDensity) + , restitution(aRestitution) + , friction(aFriction) {} }PhysicsMaterial; @@ -204,7 +204,7 @@ public: float calculateDefaultMoment() override; Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; Point getCenter() override; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -247,7 +247,7 @@ public: static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); Point getOffset() override { return _offset; } Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; protected: bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); @@ -269,7 +269,7 @@ public: static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -291,7 +291,7 @@ public: static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1cd2b936c5..6b6e221571 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -465,9 +465,9 @@ void PhysicsWorld::debugDraw() } } -void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) +void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joints) { - for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) + for (auto it = joints->_info->joints.begin(); it != joints->_info->joints.end(); ++it) { cpConstraint *constraint = *it; @@ -526,9 +526,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) } } -void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) +void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shapes) { - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) + for (auto it = shapes->_info->shapes.begin(); it != shapes->_info->shapes.end(); ++it) { cpShape *shape = *it; From 25196072f264d6d85d46830c10708b739ded5819 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 11:57:20 +0800 Subject: [PATCH 059/197] 1. change color json format 2. fix tween easing 3. fix CCBone crate bug --- cocos/editor-support/cocostudio/CCArmature.h | 1 + .../cocostudio/CCArmatureDefine.h | 1 + cocos/editor-support/cocostudio/CCBone.cpp | 16 ++- .../cocostudio/CCDataReaderHelper.cpp | 130 ++++++++---------- .../cocostudio/CCDataReaderHelper.h | 22 +-- cocos/editor-support/cocostudio/CCDatas.h | 4 +- .../cocostudio/CCProcessBase.cpp | 2 +- .../editor-support/cocostudio/CCProcessBase.h | 2 +- cocos/editor-support/cocostudio/CCTween.cpp | 16 +-- cocos/editor-support/cocostudio/CCTween.h | 2 +- .../cocostudio/CCTweenFunction.cpp | 26 ++-- .../cocostudio/CCTweenFunction.h | 7 +- 12 files changed, 108 insertions(+), 121 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index bf11841f7e..b58591ae19 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -65,6 +65,7 @@ CC_DEPRECATED_ATTRIBUTE typedef Bone CCBone; CC_DEPRECATED_ATTRIBUTE typedef ArmatureAnimation CCArmatureAnimation; CC_DEPRECATED_ATTRIBUTE typedef Armature CCArmature; CC_DEPRECATED_ATTRIBUTE typedef ArmatureDataManager CCArmatureDataManager; +CC_DEPRECATED_ATTRIBUTE typedef TweenType CCTweenType; class Armature : public cocos2d::NodeRGBA, public cocos2d::BlendProtocol { diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index b3fca84e01..0691058417 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -30,6 +30,7 @@ THE SOFTWARE. #define VERSION_COMBINED 0.30f #define VERSION_CHANGE_ROTATION_RANGE 1.0f +#define VERSION_COLOR_READING 1.1f #ifndef AUTO_ADD_SPRITE_FRAME_NAME_PREFIX #define AUTO_ADD_SPRITE_FRAME_NAME_PREFIX 0 diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 3132acec79..faf4b0ee94 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -90,10 +90,7 @@ Bone::~Bone(void) CC_SAFE_DELETE(_displayManager); CC_SAFE_DELETE(_worldInfo); - if(_boneData) - { - _boneData->release(); - } + CC_SAFE_RELEASE_NULL(_boneData); CC_SAFE_RELEASE(_childArmature); } @@ -129,6 +126,9 @@ bool Bone::init(const char *name) CC_SAFE_DELETE(_worldInfo); _worldInfo = new BaseData(); + CC_SAFE_DELETE(_boneData); + _boneData = new CCBoneData(); + bRet = true; } while (0); @@ -140,8 +140,12 @@ void Bone::setBoneData(BoneData *boneData) { CCASSERT(NULL != boneData, "_boneData must not be NULL"); - _boneData = boneData; - _boneData->retain(); + if (_boneData != boneData) + { + CC_SAFE_RETAIN(boneData); + CC_SAFE_RELEASE(_boneData); + _boneData = boneData; + } _name = _boneData->name; _ZOrder = _boneData->zOrder; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index c64a469c71..7ff2117b41 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -140,12 +140,8 @@ namespace cocostudio { float s_PositionReadScale = 1; -float s_ContentScale = 1; -static float s_FlashToolVersion = VERSION_2_0; -static float s_CocoStudioVersion = VERSION_COMBINED; std::vector DataReaderHelper::_configFileList; -std::string DataReaderHelper::_basefilePath = ""; DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; @@ -188,6 +184,8 @@ void DataReaderHelper::loadData() // generate data info DataInfo *pDataInfo = new DataInfo(); pDataInfo->asyncStruct = pAsyncStruct; + pDataInfo->filename = pAsyncStruct->filename; + pDataInfo->baseFilePath = pAsyncStruct->baseFilePath; if (pAsyncStruct->configType == DragonBone_XML) { @@ -280,15 +278,16 @@ void DataReaderHelper::addDataFromFile(const char *filePath) //! find the base file path - _basefilePath = filePath; - size_t pos = _basefilePath.find_last_of("/"); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of("/"); + if (pos != std::string::npos) { - _basefilePath = _basefilePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); } else { - _basefilePath = ""; + basefilePath = ""; } @@ -303,6 +302,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) DataInfo dataInfo; dataInfo.filename = filePathStr; dataInfo.asyncStruct = NULL; + dataInfo.baseFilePath = basefilePath; if (str.compare(".xml") == 0) { @@ -502,7 +502,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *root = document.RootElement(); CCASSERT(root, "XML error or XML is empty."); - root->QueryFloatAttribute(VERSION, &s_FlashToolVersion); + root->QueryFloatAttribute(VERSION, &dataInfo->flashToolVersion); /* @@ -512,7 +512,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *armatureXML = armaturesXML->FirstChildElement(ARMATURE); while(armatureXML) { - ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); + ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML, dataInfo); if (dataInfo->asyncStruct) { @@ -536,7 +536,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *animationXML = animationsXML->FirstChildElement(ANIMATION); while(animationXML) { - AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); + AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML, dataInfo); if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); @@ -558,7 +558,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *textureXML = texturesXML->FirstChildElement(SUB_TEXTURE); while(textureXML) { - TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); + TextureData *textureData = DataReaderHelper::decodeTexture(textureXML, dataInfo); if (dataInfo->asyncStruct) { @@ -574,7 +574,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data } } -ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML) +ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); @@ -606,7 +606,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML } } - BoneData *boneData = decodeBone(boneXML, parentXML); + BoneData *boneData = decodeBone(boneXML, parentXML, dataInfo); armatureData->addBoneData(boneData); boneData->release(); @@ -616,7 +616,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML return armatureData; } -BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml) +BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml, DataInfo *dataInfo) { BoneData *boneData = new BoneData(); boneData->init(); @@ -634,7 +634,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: tinyxml2::XMLElement *displayXML = boneXML->FirstChildElement(DISPLAY); while(displayXML) { - DisplayData *displayData = decodeBoneDisplay(displayXML); + DisplayData *displayData = decodeBoneDisplay(displayXML, dataInfo); boneData->addDisplayData(displayData); displayData->release(); @@ -644,7 +644,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML) +DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo) { int _isArmature = 0; @@ -687,7 +687,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXM return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML) +AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo) { AnimationData *aniData = new AnimationData(); @@ -701,7 +701,7 @@ AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animation while( movementXML ) { - MovementData *movementData = decodeMovement(movementXML, armatureData); + MovementData *movementData = decodeMovement(movementXML, armatureData, dataInfo); aniData->addMovement(movementData); movementData->release(); @@ -712,7 +712,7 @@ AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animation return aniData; } -MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData) +MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData, DataInfo *dataInfo) { MovementData *movementData = new MovementData(); @@ -747,12 +747,12 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML { if( movementXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) { - movementData->tweenEasing = (CCTweenType)tweenEasing; + movementData->tweenEasing = tweenEasing == 2 ? Sine_EaseInOut : (TweenType)tweenEasing; } } else { - movementData->tweenEasing = TWEEN_EASING_MAX; + movementData->tweenEasing = Linear; } } @@ -788,7 +788,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } } - MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData); + MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData, dataInfo); movementData->addMovementBoneData(moveBoneData); moveBoneData->release(); @@ -799,7 +799,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } -MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData) +MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData, DataInfo *dataInfo) { MovementBoneData *movBoneData = new MovementBoneData(); movBoneData->init(); @@ -874,7 +874,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov } } - FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData); + FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData, dataInfo); movBoneData->addFrameData(frameData); frameData->release(); @@ -918,7 +918,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov return movBoneData; } -FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData) +FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData, DataInfo *dataInfo) { float x, y, scale_x, scale_y, skew_x, skew_y = 0; int duration, displayIndex, zOrder, tweenEasing, blendType = 0; @@ -944,7 +944,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm - if (s_FlashToolVersion >= VERSION_2_0) + if (dataInfo->flashToolVersion >= VERSION_2_0) { if(frameXML->QueryFloatAttribute(A_COCOS2DX_X, &x) == tinyxml2::XML_SUCCESS) { @@ -1037,12 +1037,12 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm { if( frameXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) { - frameData->tweenEasing = (CCTweenType)tweenEasing; + frameData->tweenEasing = tweenEasing == 2 ? Sine_EaseInOut : (TweenType)tweenEasing; } } else { - frameData->tweenEasing = TWEEN_EASING_MAX; + frameData->tweenEasing = Linear; } } @@ -1052,7 +1052,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm * recalculate frame data from parent frame data, use for translate matrix */ BaseData helpNode; - if (s_FlashToolVersion >= VERSION_2_0) + if (dataInfo->flashToolVersion >= VERSION_2_0) { parentFrameXml->QueryFloatAttribute(A_COCOS2DX_X, &helpNode.x); parentFrameXml->QueryFloatAttribute(A_COCOS2DX_Y, &helpNode.y); @@ -1076,7 +1076,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm return frameData; } -TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) +TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo) { TextureData *textureData = new TextureData(); textureData->init(); @@ -1088,7 +1088,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) float px, py, width, height = 0; - if(s_FlashToolVersion >= VERSION_2_0) + if(dataInfo->flashToolVersion >= VERSION_2_0) { textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_X, &px); textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_Y, &py); @@ -1112,7 +1112,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) while (contourXML) { - ContourData *contourData = decodeContour(contourXML); + ContourData *contourData = decodeContour(contourXML, dataInfo); textureData->addContourData(contourData); contourData->release(); @@ -1122,7 +1122,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) return textureData; } -ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML) +ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo) { ContourData *contourData = new ContourData(); contourData->init(); @@ -1153,14 +1153,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); - if (dataInfo->asyncStruct) - { - dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); - } - else - { - s_ContentScale = json.getItemFloatValue(CONTENT_SCALE, 1); - } + dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); // Decode armatures int length = json.getArrayItemCount(ARMATURE_DATA); @@ -1248,7 +1241,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string plistPath = filePath + ".plist"; std::string pngPath = filePath + ".png"; - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((_basefilePath + plistPath).c_str(), (_basefilePath + pngPath).c_str()); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile((dataInfo->baseFilePath + plistPath).c_str(), (dataInfo->baseFilePath + pngPath).c_str()); } } } @@ -1265,7 +1258,7 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *d armatureData->name = name; } - s_CocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); + dataInfo->cocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); int length = json.getArrayItemCount(BONE_DATA); for (int i = 0; i < length; i++) @@ -1344,16 +1337,8 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); - if (dataInfo->asyncStruct) - { - sdd->skinData.x *= dataInfo->contentScale; - sdd->skinData.y *= dataInfo->contentScale; - } - else - { - sdd->skinData.x *= s_ContentScale; - sdd->skinData.y *= s_ContentScale; - } + sdd->skinData.x *= dataInfo->contentScale; + sdd->skinData.y *= dataInfo->contentScale; delete dic; } @@ -1384,7 +1369,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo } else { - static_cast(displayData)->plist = _basefilePath + plist; + static_cast(displayData)->plist = dataInfo->baseFilePath + plist; } } } @@ -1435,7 +1420,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *d movementData->durationTo = json.getItemIntValue(A_DURATION_TO, 0); movementData->duration = json.getItemIntValue(A_DURATION, 0); movementData->scale = json.getItemFloatValue(A_MOVEMENT_SCALE, 1); - movementData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); + movementData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); const char *name = json.getItemStringValue(A_NAME); if(name != NULL) @@ -1479,7 +1464,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat movementBoneData->addFrameData(frameData); frameData->release(); - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { frameData->frameID = movementBoneData->duration; movementBoneData->duration += frameData->duration; @@ -1489,7 +1474,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat } - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) + if (dataInfo->cocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) { //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) FrameData **frames = (FrameData **)movementBoneData->frameList.data->arr; @@ -1513,7 +1498,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat } } - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { if (movementBoneData->frameList.count() > 0) { @@ -1535,7 +1520,7 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf decodeNode(frameData, json, dataInfo); - frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); + frameData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); @@ -1546,7 +1531,7 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf frameData->strEvent = event; } - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { frameData->duration = json.getItemIntValue(A_DURATION, 1); } @@ -1617,17 +1602,8 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; - if (dataInfo->asyncStruct) - { - node->x *= dataInfo->contentScale; - node->y *= dataInfo->contentScale; - } - else - { - node->x *= s_ContentScale; - node->y *= s_ContentScale; - } - + node->x *= dataInfo->contentScale; + node->y *= dataInfo->contentScale; node->zOrder = json.getItemIntValue(A_Z, 0); @@ -1636,7 +1612,15 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + JsonDictionary *colorDic = NULL; + if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING) + { + colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + } + else + { + colorDic = json.getSubDictionary(COLOR_INFO); + } if (colorDic) { diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index c2df44b512..82f551e52f 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -74,6 +74,9 @@ protected: std::queue configFileQueue; float contentScale; std::string filename; + std::string baseFilePath; + float flashToolVersion; + float cocoStudioVersion; } DataInfo; public: @@ -123,29 +126,29 @@ public: /** * Decode Armature Datas from xml export from Dragon Bone flash tool */ - static ArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML); - static BoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML); - static DisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML); + static ArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo); + static BoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML, DataInfo *dataInfo); + static DisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo); /** * Decode ArmatureAnimation Datas from xml export from Dragon Bone flash tool */ - static AnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML); - static MovementData *decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData); - static MovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData); - static FrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData); + static AnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo); + static MovementData *decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData, DataInfo *dataInfo); + static MovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData, DataInfo *dataInfo); + static FrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData, DataInfo *dataInfo); /** * Decode Texture Datas from xml export from Dragon Bone flash tool */ - static TextureData *decodeTexture(tinyxml2::XMLElement *textureXML); + static TextureData *decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo); /** * Decode Contour Datas from xml export from Dragon Bone flash tool */ - static ContourData *decodeContour(tinyxml2::XMLElement *contourXML); + static ContourData *decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo); public: static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); @@ -193,7 +196,6 @@ protected: std::queue *_asyncStructQueue; std::queue *_dataQueue; - static std::string _basefilePath; static std::vector _configFileList; static DataReaderHelper *_dataReaderHelper; diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 26128020cf..5f08757d13 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -341,7 +341,7 @@ public: public: int frameID; int duration; //! The frame will last duration frames - CCTweenType tweenEasing; //! Every frame's tween easing effect + TweenType tweenEasing; //! Every frame's tween easing effect bool isTween; //! Whether it's a tween key frame /** @@ -435,7 +435,7 @@ public: * Which tween easing effect the movement use * TWEEN_EASING_MAX : use the value from MovementData get from flash design panel */ - CCTweenType tweenEasing; + TweenType tweenEasing; /** * @brief save movment bone data diff --git a/cocos/editor-support/cocostudio/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp index 1c9bd8965e..62bac419b6 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -89,7 +89,7 @@ void ProcessBase::play(void *animation, int durationTo, int durationTween, int * When changing end, m_iTotalFrames will be setted to _durationTween */ _nextFrameIndex = durationTo; - _tweenEasing = (CCTweenType)tweenEasing; + _tweenEasing = (TweenType)tweenEasing; } diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index 77c5da4ebb..e59244433e 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -146,7 +146,7 @@ protected: CC_SYNTHESIZE(AnimationType, _loopType, LoopType); //! The tween easing effect - CC_SYNTHESIZE(CCTweenType, _tweenEasing, TweenEasing); + CC_SYNTHESIZE(TweenType, _tweenEasing, TweenEasing); //! The animation update speed CC_SYNTHESIZE(float, _animationInternal, AnimationInternal); diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 77f9a3b2ff..ce55cb4189 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -414,7 +414,7 @@ float Tween::updateFrameData(float currentPercent) { from = to = frames[0]; setBetween(from, to); - return currentPercent; + return _currentPercent; } if(playedTime >= frames[length - 1]->frameID) @@ -422,6 +422,8 @@ float Tween::updateFrameData(float currentPercent) // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. if (_passLastFrame) { + from = to = frames[length - 1]; + setBetween(from, to); return _currentPercent; } _passLastFrame = true; @@ -472,16 +474,10 @@ float Tween::updateFrameData(float currentPercent) /* * If frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ - - CCTweenType tweenType; - - if ( _frameTweenEasing != TWEEN_EASING_MAX) + TweenType tweenType = (_frameTweenEasing != Linear) ? _frameTweenEasing : _tweenEasing; + if (tweenType != TWEEN_EASING_MAX && tweenType != Linear) { - tweenType = (_tweenEasing == TWEEN_EASING_MAX) ? _frameTweenEasing : _tweenEasing; - if (tweenType != TWEEN_EASING_MAX && tweenType != Linear) - { - currentPercent = TweenFunction::tweenTo(0, 1, currentPercent, 1, tweenType); - } + currentPercent = TweenFunction::tweenTo(0, 1, currentPercent, 1, tweenType); } return currentPercent; diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 61213371e8..c4fc110334 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -131,7 +131,7 @@ protected: Bone *_bone; //! A weak reference to the Bone - CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use + TweenType _frameTweenEasing; //! Dedermine which tween effect current frame use int _betweenDuration; //! Current key frame will last _betweenDuration frames int _totalDuration; diff --git a/cocos/editor-support/cocostudio/CCTweenFunction.cpp b/cocos/editor-support/cocostudio/CCTweenFunction.cpp index 37b523fc79..74e4471768 100644 --- a/cocos/editor-support/cocostudio/CCTweenFunction.cpp +++ b/cocos/editor-support/cocostudio/CCTweenFunction.cpp @@ -27,7 +27,7 @@ THE SOFTWARE. namespace cocostudio { -float TweenFunction::tweenTo(float from, float change, float time, float duration, CCTweenType tweenType) +float TweenFunction::tweenTo(float from, float change, float time, float duration, TweenType tweenType) { float delta = 0; @@ -163,8 +163,8 @@ float TweenFunction::quadEaseOut(float t, float b, float c, float d) } float TweenFunction::quadEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t + b; --t; return -c / 2 * (t * (t - 2) - 1) + b; @@ -182,8 +182,8 @@ float TweenFunction::cubicEaseOut(float t, float b, float c, float d) } float TweenFunction::cubicEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t + b; t -= 2; return c / 2 * (t * t * t + 2) + b; @@ -201,8 +201,8 @@ float TweenFunction::quartEaseOut(float t, float b, float c, float d) } float TweenFunction::quartEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t * t + b; t -= 2; return -c / 2 * (t * t * t * t - 2) + b; @@ -220,8 +220,8 @@ float TweenFunction::quintEaseOut(float t, float b, float c, float d) } float TweenFunction::quintEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t * t * t + b; t -= 2; return c / 2 * (t * t * t * t * t + 2) + b; @@ -272,8 +272,8 @@ float TweenFunction::circEaseOut(float t, float b, float c, float d) } float TweenFunction::circEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b; t -= 2; return c / 2 * (sqrt(1 - t * t) + 1) + b; @@ -323,8 +323,8 @@ float TweenFunction::elasticEaseInOut(float t, float b, float c, float d, float float s = 0; if (t == 0) return b; - t /= d; - if ((t / 2) == 2) + t = t/d*2; + if ((t) == 2) return b + c; if (!p) p = d * (.3 * 1.5); diff --git a/cocos/editor-support/cocostudio/CCTweenFunction.h b/cocos/editor-support/cocostudio/CCTweenFunction.h index 255d19d58e..ff7ad6016d 100644 --- a/cocos/editor-support/cocostudio/CCTweenFunction.h +++ b/cocos/editor-support/cocostudio/CCTweenFunction.h @@ -31,16 +31,15 @@ THE SOFTWARE. namespace cocostudio { -enum CCTweenType +enum TweenType { TWEEN_EASING_MIN = -1, Linear, Sine_EaseIn, - Sine_EaseInOut, Sine_EaseOut, - + Sine_EaseInOut, Quad_EaseIn, Quad_EaseOut, @@ -85,7 +84,7 @@ class TweenFunction { public: - static float tweenTo(float from, float change, float time, float duration, CCTweenType tweenType); + static float tweenTo(float from, float change, float time, float duration, TweenType tweenType); static float linear(float t, float b, float c, float d); From b076711b699b3b37ec44f014e017a3af440e670e Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 13:42:27 +0800 Subject: [PATCH 060/197] fix compile error --- cocos/editor-support/cocostudio/CCColliderDetector.cpp | 2 +- cocos/editor-support/cocostudio/CCColliderDetector.h | 7 +++---- .../CocoStudioArmatureTest/ArmatureScene.cpp | 3 ++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index cceb1a9b72..21cf39e486 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -56,7 +56,7 @@ void ColliderFilter::updateShape(b2Fixture *fixture) } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT -ColliderFilter::ColliderFilter(cpCollisionType collisionType, cpGroup group) +ColliderFilter::ColliderFilter(uintptr_t collisionType, uintptr_t group) : _collisionType(collisionType) , _group(group) { diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index e2da724c80..0b9c058aa8 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -34,7 +34,6 @@ THE SOFTWARE. #if ENABLE_PHYSICS_CHIPMUNK_DETECT -#include "chipmunk.h" struct cpBody; struct cpShape; #elif ENABLE_PHYSICS_BOX2D_DETECT @@ -62,11 +61,11 @@ protected: CC_SYNTHESIZE(signed short, _groupIndex, GroupIndex); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT public: - ColliderFilter(cpCollisionType collisionType = 0, cpGroup group = 0); + ColliderFilter(uintptr_t collisionType = 0, uintptr_t group = 0); void updateShape(cpShape *shape); protected: - CC_SYNTHESIZE(cpCollisionType, _collisionType, CollisionType); - CC_SYNTHESIZE(cpGroup, _group, Group); + CC_SYNTHESIZE(uintptr_t, _collisionType, CollisionType); + CC_SYNTHESIZE(uintptr_t, _group, Group); #endif }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index a6dfd04092..0b662d9c15 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1008,7 +1008,8 @@ void TestColliderDetector::initWorld() cpSpaceAddBody(space, body); armature2->setBody(body); - armature2->setColliderFilter(&ColliderFilter(eEnemyTag)); + ColliderFilter filter = ColliderFilter(eEnemyTag); + armature2->setColliderFilter(&filter); cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); } From a3a2b0274ea24b89e0672d608ca24549578f6575 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 5 Nov 2013 14:23:48 +0800 Subject: [PATCH 061/197] Updating submodule of bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index b6f97d9fc2..eb2dbfef01 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit b6f97d9fc2d3450426423583c7a6aaf4a366a99d +Subproject commit eb2dbfef01a1d43691f31386069b65c319e41e2c From 5cecc93c3ef0cf9ae5909700a4556dc76f11f29b Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 5 Nov 2013 06:31:26 +0000 Subject: [PATCH 062/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 006193d9b4..56a3820b26 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 006193d9b4081c8af2b79be3cd9bcf90aedfdbae +Subproject commit 56a3820b2660d69ebd958838f515cd75f08eaf18 From b445f0824add0abfcc9a760ca1b029cc0275f249 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 5 Nov 2013 15:09:51 +0800 Subject: [PATCH 063/197] issue #2868:Bind UI and Scene parser to lua by bindings-generator and add releated test samples --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/gui/UIHelper.h | 2 +- cocos/scripting/lua/bindings/CCLuaStack.cpp | 2 + .../luaScript/ExtensionTest/ArmatureTest.lua | 147 +++++------------- tools/bindings-generator | 2 +- tools/tolua/cocos2dx_extension.ini | 17 +- tools/tolua/cocos2dx_studio.ini | 67 ++++++++ tools/tolua/genbindings.sh | 8 +- 8 files changed, 117 insertions(+), 130 deletions(-) create mode 100644 tools/tolua/cocos2dx_studio.ini diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index ac519a56c8..b99b211450 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -5a0361664f33af4303065c98da4b8d8e4efe48b4 \ No newline at end of file +ab3cbe9f9358e0c472a7775bb7087507f50892e9 \ No newline at end of file diff --git a/cocos/gui/UIHelper.h b/cocos/gui/UIHelper.h index cab106d26a..2c477ea266 100644 --- a/cocos/gui/UIHelper.h +++ b/cocos/gui/UIHelper.h @@ -44,7 +44,7 @@ public: /** * Default destructor */ - ~UIHelper(); + virtual ~UIHelper(); //initializes state of UIHelper. void init(); diff --git a/cocos/scripting/lua/bindings/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp index bad774b677..a0269bf318 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.cpp +++ b/cocos/scripting/lua/bindings/CCLuaStack.cpp @@ -54,6 +54,7 @@ extern "C" { #include "lua_cocos2dx_extension_manual.h" #include "lua_cocos2dx_deprecated.h" #include "lua_xml_http_request.h" +#include "lua_cocos2dx_studio_auto.hpp" namespace { int lua_print(lua_State * luastate) @@ -135,6 +136,7 @@ bool LuaStack::init(void) register_all_cocos2dx_deprecated(_state); register_cocos2dx_extension_CCBProxy(_state); tolua_opengl_open(_state); + register_all_cocos2dx_studio(_state); register_all_cocos2dx_manual(_state); register_all_cocos2dx_extension_manual(_state); register_all_cocos2dx_manual_deprecated(_state); diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua index 66a224d9e2..446854de11 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua @@ -4,16 +4,15 @@ local scheduler = cc.Director:getInstance():getScheduler() local ArmatureTestIndex = { TEST_COCOSTUDIO_WITH_SKELETON = 1, - TEST_COCOSTUDIO_WITHOUT_SKELETON = 2, - TEST_DRAGON_BONES_2_0 = 3, - TEST_PERFORMANCE = 4, - TEST_CHANGE_ZORDER = 5, - TEST_ANIMATION_EVENT = 6, - TEST_PARTICLE_DISPLAY = 7, - TEST_USE_DIFFERENT_PICTURE = 8, - TEST_BOUDINGBOX = 9, - TEST_ANCHORPOINT = 10, - TEST_ARMATURE_NESTING = 11, + TEST_DRAGON_BONES_2_0 = 2, + TEST_PERFORMANCE = 3, + TEST_CHANGE_ZORDER = 4, + TEST_ANIMATION_EVENT = 5, + TEST_PARTICLE_DISPLAY = 6, + TEST_USE_DIFFERENT_PICTURE = 7, + TEST_BOUDINGBOX = 8, + TEST_ANCHORPOINT = 9, + TEST_ARMATURE_NESTING = 10, } local armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON @@ -31,13 +30,13 @@ function ArmatureTestScene.extend(target) end function ArmatureTestScene:runThisTest() - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON self:addChild(restartArmatureTest()) @@ -59,7 +58,7 @@ function ArmatureTestScene.create() end function ArmatureTestScene.toMainMenuCallback() - cc.ArmatureDataManager:purgeArmatureSystem() + ccs.ArmatureDataManager:purgeArmatureSystem() end local ArmatureTestLayer = class("ArmatureTestLayer") @@ -72,8 +71,6 @@ end function ArmatureTestLayer.title(idx) if ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON == idx then return "Test Export From CocoStudio With Skeleton Effect" - elseif ArmatureTestIndex.TEST_COCOSTUDIO_WITHOUT_SKELETON == idx then - return "Test Export From CocoStudio Without Skeleton Effect" elseif ArmatureTestIndex.TEST_DRAGON_BONES_2_0 == idx then return "Test Export From DragonBones version 2.0" elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then @@ -209,7 +206,7 @@ function TestCSWithSkeleton.extend(target) end function TestCSWithSkeleton:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setScale(0.2) armature:setAnchorPoint(cc.p(0.5, 0.5)) @@ -230,40 +227,6 @@ function TestCSWithSkeleton.create() return layer end -local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) -TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton - -function TestCSWithoutSkeleton.extend(target) - local t = tolua.getpeer(target) - if not t then - t = {} - tolua.setpeer(target, t) - end - setmetatable(t, TestCSWithoutSkeleton) - return target -end - -function TestCSWithoutSkeleton:onEnter() - local armature = cc.Armature:create("TestBone") - armature:getAnimation():playByIndex(0) - armature:setScale(0.2) - armature:setAnchorPoint(cc.p(0.5, 0.5)) - armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) - self:addChild(armature) -end - -function TestCSWithoutSkeleton.create() - local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) - - if nil ~= layer then - layer:createMenu() - layer:createToExtensionMenu() - layer:onEnter() - layer:creatTitleAndSubTitle(armatureSceneIdx) - end - return layer -end - local TestDragonBones20 = class("TestDragonBones20",ArmatureTestLayer) TestDragonBones20.__index = TestDragonBones20 @@ -278,7 +241,7 @@ function TestDragonBones20.extend(target) end function TestDragonBones20:onEnter() - local armature = cc.Armature:create("Dragon") + local armature = ccs.Armature:create("Dragon") armature:getAnimation():playByIndex(1) armature:getAnimation():setAnimationScale(0.4) armature:setScale(0.6) @@ -320,7 +283,7 @@ function TestPerformance.update(delta) TestPerformance.times = TestPerformance.times + delta if TestPerformance.times > 0.25 then TestPerformance.time = 0 - local armature = cc.Armature:create("Knight_f/Knight") + local armature = ccs.Armature:create("Knight_f/Knight") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(50 + TestPerformance.armatureCount * 5, winSize.height / 2)) armature:setScale(0.6) @@ -363,40 +326,6 @@ function TestPerformance.create() return layer end -local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) -TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton - -function TestCSWithoutSkeleton.extend(target) - local t = tolua.getpeer(target) - if not t then - t = {} - tolua.setpeer(target, t) - end - setmetatable(t, TestCSWithoutSkeleton) - return target -end - -function TestCSWithoutSkeleton:onEnter() - local armature = cc.Armature:create("TestBone") - armature:getAnimation():playByIndex(0) - armature:setScale(0.2) - armature:setAnchorPoint(cc.p(0.5, 0.5)) - armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) - self:addChild(armature) -end - -function TestCSWithoutSkeleton.create() - local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) - - if nil ~= layer then - layer:createMenu() - layer:createToExtensionMenu() - layer:onEnter() - layer:creatTitleAndSubTitle(armatureSceneIdx) - end - return layer -end - local TestChangeZorder = class("TestChangeZorder",ArmatureTestLayer) TestChangeZorder.__index = TestChangeZorder TestChangeZorder.currentTag = -1 @@ -414,21 +343,21 @@ end function TestChangeZorder:onEnter() self.currentTag = -1 - local armature = cc.Armature:create("Knight_f/Knight") + local armature = ccs.Armature:create("Knight_f/Knight") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100 )) armature:setScale(0.6) self.currentTag = self.currentTag + 1 self:addChild(armature, self.currentTag, self.currentTag) - armature = cc.Armature:create("TestBone") + armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setScale(0.24) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) self.currentTag = self.currentTag + 1 self:addChild(armature, self.currentTag, self.currentTag) - armature = cc.Armature:create("Dragon") + armature = ccs.Armature:create("Dragon") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) armature:setScale(0.6) @@ -471,7 +400,7 @@ function TestAnimationEvent.extend(target) end function TestAnimationEvent:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():play("Fire") armature:setScaleX(-0.24) armature:setScaleY(0.24) @@ -511,25 +440,25 @@ function TestParticleDisplay:onEnter() self:setTouchEnabled(true) self.animationID = 0 - self.armature = cc.Armature:create("robot") + self.armature = ccs.Armature:create("robot") self.armature:getAnimation():playByIndex(0) self.armature:setPosition(VisibleRect:center()) self.armature:setScale(0.48) self:addChild(self.armature) - local displayData = cc.ParticleDisplayData:create() - displayData:setParam("Particles/SmallSun.plist") + local p1 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist") + local p2 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist") - local bone = cc.Bone:create("p1") - bone:addDisplay(displayData, 0) + local bone = ccs.Bone:create("p1") + bone:addDisplay(p1, 0) bone:changeDisplayByIndex(0, true) bone:setIgnoreMovementBoneData(true) bone:setZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a3") - bone = cc.Bone:create("p2") - bone:addDisplay(displayData, 0) + bone = ccs.Bone:create("p2") + bone:addDisplay(p2, 0) bone:changeDisplayByIndex(0, true) bone:setIgnoreMovementBoneData(true) bone:setZOrder(100) @@ -583,7 +512,7 @@ function TestUseMutiplePicture:onEnter() self:setTouchEnabled(true) self.displayIndex = 1 - self.armature = cc.Armature:create("Knight_f/Knight") + self.armature = ccs.Armature:create("Knight_f/Knight") self.armature:getAnimation():playByIndex(0) self.armature:setPosition(cc.p(VisibleRect:left().x + 70, VisibleRect:left().y)) self.armature:setScale(1.2) @@ -600,11 +529,10 @@ function TestUseMutiplePicture:onEnter() "weapon_f-hammer.png", }; - local spriteDisplayData = cc.SpriteDisplayData:create() local i = 1 for i = 1,table.getn(weapon) do - spriteDisplayData:setParam(weapon[i]) - self.armature:getBone("weapon"):addDisplay(spriteDisplayData, i - 1) + local skin = ccs.Skin:createWithSpriteFrameName(weapon[i]) + self.armature:getBone("weapon"):addDisplay(skin, i - 1) end local function onTouchBegan(x, y) @@ -649,7 +577,7 @@ function TestBoundingBox.extend(target) end function TestBoundingBox:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setPosition(VisibleRect:center()) armature:setScale(0.2) @@ -685,7 +613,7 @@ end function TestAnchorPoint:onEnter() local i = 1 for i = 1 , 5 do - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0); armature:setPosition(VisibleRect:center()) armature:setScale(0.2) @@ -731,7 +659,7 @@ function TestArmatureNesting:onEnter() self:setTouchEnabled(true) self.weaponIndex = 0 - self.armature = cc.Armature:create("cyborg") + self.armature = ccs.Armature:create("cyborg") self.armature:getAnimation():playByIndex(1) self.armature:setPosition(VisibleRect:center()) self.armature:setScale(1.2) @@ -770,7 +698,6 @@ end local armatureSceneArr = { TestCSWithSkeleton.create, - TestCSWithoutSkeleton.create, TestDragonBones20.create, TestPerformance.create, TestChangeZorder.create, diff --git a/tools/bindings-generator b/tools/bindings-generator index b6f97d9fc2..d41959ab0b 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit b6f97d9fc2d3450426423583c7a6aaf4a366a99d +Subproject commit d41959ab0b15c20aa0802ab5c9ef92be7b742bd4 diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index dd5aa433aa..5940e44111 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -13,7 +13,8 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT cxxgenerator_headers = @@ -22,11 +23,11 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h +headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -47,16 +48,10 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*], - ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], - Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], - Skin::[getSkinData setSkinData], - ArmatureAnimation::[updateHandler updateFrameData frameEvent], - Bone::[(s|g)etIgnoreMovementBoneData] + ControlSwitchSprite::[*] -rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager], - ArmatureDataManager::[sharedArmatureDataManager=getInstance] +rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager] rename_classes = CCBReader::_Reader, CCBAnimationManager::AnimationManager diff --git a/tools/tolua/cocos2dx_studio.ini b/tools/tolua/cocos2dx_studio.ini new file mode 100644 index 0000000000..c30134f97d --- /dev/null +++ b/tools/tolua/cocos2dx_studio.ini @@ -0,0 +1,67 @@ +[cocos2dx_studio] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_studio + +# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`) +# all classes will be embedded in that namespace +target_namespace = ccs + +android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include +android_flags = -D_SIZE_T_DEFINED_ + +clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include +clang_flags = -nostdinc -x c++ -std=c++11 + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + +cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT + +cxxgenerator_headers = + +# extra arguments for clang +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# what headers to parse +headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h %(cocosdir)s/cocos/gui/CocosGUI.h + +# what classes to produce code for. You can use regular expressions here. When testing the regular +# expression, it will be enclosed in "^$", like this: "^Menu*$". +classes =Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ UIWidget GUIRenderer Layout RectClippingNode UIRootWidget UIButton UICheckBox UIImageView UILabel UICCLabelAtlas UILabelAtlas UILoadingBar UIScrollView UISlider UICCTextField UITextField UIListView UIDragPanel UILabelBMFont UIPageView UIHelper UILayer + +# what should we skip? in the format ClassName::[function function] +# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also +# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just +# add a single "*" as functions. See bellow for several examples. A special class name is "*", which +# will apply to all class names. This is a convenience wildcard to be able to skip similar named +# functions from all classes. + +skip = .*Delegate::[*], + .*Loader.*::[*], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener addEventListener], + ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], + Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], + Skin::[(s|g)etSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent], + Bone::[(s|g)etIgnoreMovementBoneData] + +rename_functions = ArmatureDataManager::[sharedArmatureDataManager=getInstance] + +rename_classes = + +# for all class names, should we remove something when registering in the target VM? +remove_prefix = + +# classes for which there will be no "parent" lookup +classes_have_no_parents = + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Object ProcessBase + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = ArmatureDataManager + +# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. +script_control_cpp = no + diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index b236c43ae8..e6997542bf 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -78,9 +78,5 @@ echo -e "$_CONTENTS" > "$_CONF_INI_FILE" echo --- # Generate bindings for cocos2dx -echo "Generating bindings for cocos2dx..." -set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto - -echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto +echo "Generating bindings for cocos2dx_studio..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto From 3eef64c3b8d44adc58688c8a86921a2440983bd1 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 15:32:13 +0800 Subject: [PATCH 064/197] 1. Change NULL to null 2. Remove CocoStudio/Armature files --- .../editor-support/cocostudio/CCArmature.cpp | 88 +- cocos/editor-support/cocostudio/CCArmature.h | 2 +- .../cocostudio/CCArmatureAnimation.cpp | 36 +- .../cocostudio/CCArmatureAnimation.h | 4 +- .../cocostudio/CCArmatureDataManager.cpp | 16 +- .../cocostudio/CCArmatureDefine.h | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 24 +- cocos/editor-support/cocostudio/CCBone.cpp | 60 +- cocos/editor-support/cocostudio/CCBone.h | 2 +- .../cocostudio/CCColliderDetector.cpp | 54 +- .../cocostudio/CCDataReaderHelper.cpp | 76 +- .../cocostudio/CCDataReaderHelper.h | 4 +- cocos/editor-support/cocostudio/CCDatas.h | 4 +- .../cocostudio/CCDecorativeDisplay.cpp | 8 +- .../cocostudio/CCDisplayFactory.cpp | 4 +- .../cocostudio/CCDisplayManager.cpp | 28 +- cocos/editor-support/cocostudio/CCSkin.cpp | 16 +- .../cocostudio/CCSpriteFrameCacheHelper.cpp | 4 +- cocos/editor-support/cocostudio/CCTween.cpp | 26 +- cocos/editor-support/cocostudio/CCTween.h | 2 +- extensions/CocoStudio/Armature/CCArmature.cpp | 785 -------- extensions/CocoStudio/Armature/CCBone.cpp | 401 ----- extensions/CocoStudio/Armature/CCBone.h | 199 --- .../Armature/display/CCDisplayManager.cpp | 396 ----- .../CocoStudio/Armature/display/CCSkin.cpp | 205 --- .../Armature/utils/CCArmatureDefine.cpp | 34 - .../Armature/utils/CCDataReaderHelper.cpp | 1582 ----------------- .../CocoStudioArmatureTest/ArmatureScene.cpp | 50 +- 28 files changed, 255 insertions(+), 3857 deletions(-) delete mode 100644 extensions/CocoStudio/Armature/CCArmature.cpp delete mode 100644 extensions/CocoStudio/Armature/CCBone.cpp delete mode 100644 extensions/CocoStudio/Armature/CCBone.h delete mode 100644 extensions/CocoStudio/Armature/display/CCDisplayManager.cpp delete mode 100644 extensions/CocoStudio/Armature/display/CCSkin.cpp delete mode 100644 extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp delete mode 100644 extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index baa56ddfb7..be5c9d0c33 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -49,7 +49,7 @@ Armature *Armature::create() return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } @@ -62,7 +62,7 @@ Armature *Armature::create(const char *name) return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } Armature *Armature::create(const char *name, Bone *parentBone) @@ -74,31 +74,31 @@ Armature *Armature::create(const char *name, Bone *parentBone) return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } Armature::Armature() - : _armatureData(NULL) - , _batchNode(NULL) - , _atlas(NULL) - , _parentBone(NULL) + : _armatureData(nullptr) + , _batchNode(nullptr) + , _atlas(nullptr) + , _parentBone(nullptr) , _armatureTransformDirty(true) - , _boneDic(NULL) - , _topBoneList(NULL) - , _animation(NULL) - , _textureAtlasDic(NULL) + , _boneDic(nullptr) + , _topBoneList(nullptr) + , _animation(nullptr) + , _textureAtlasDic(nullptr) { } Armature::~Armature(void) { - if(NULL != _boneDic) + if(nullptr != _boneDic) { _boneDic->removeAllObjects(); CC_SAFE_DELETE(_boneDic); } - if (NULL != _topBoneList) + if (nullptr != _topBoneList) { _topBoneList->removeAllObjects(); CC_SAFE_DELETE(_topBoneList); @@ -110,7 +110,7 @@ Armature::~Armature(void) bool Armature::init() { - return init(NULL); + return init(nullptr); } @@ -139,7 +139,7 @@ bool Armature::init(const char *name) _blendFunc.dst = CC_BLEND_DST; - _name = name == NULL ? "" : name; + _name = name == nullptr ? "" : name; ArmatureDataManager *armatureDataManager = ArmatureDataManager::getInstance(); @@ -159,7 +159,7 @@ bool Armature::init(const char *name) _armatureData = armatureData; - DictElement *_element = NULL; + DictElement *_element = nullptr; Dictionary *boneDataDic = &armatureData->boneDataDic; CCDICT_FOREACH(boneDataDic, _element) { @@ -228,13 +228,13 @@ bool Armature::init(const char *name, Bone *parentBone) Bone *Armature::createBone(const char *boneName) { Bone *existedBone = getBone(boneName); - if(existedBone != NULL) + if(existedBone != nullptr) return existedBone; BoneData *boneData = (BoneData *)_armatureData->getBoneData(boneName); std::string parentName = boneData->parentName; - Bone *bone = NULL; + Bone *bone = nullptr; if( parentName.length() != 0 ) { @@ -257,10 +257,10 @@ Bone *Armature::createBone(const char *boneName) void Armature::addBone(Bone *bone, const char *parentName) { - CCASSERT( bone != NULL, "Argument must be non-nil"); - CCASSERT(_boneDic->objectForKey(bone->getName()) == NULL, "bone already added. It can't be added again"); + CCASSERT( bone != nullptr, "Argument must be non-nil"); + CCASSERT(_boneDic->objectForKey(bone->getName()) == nullptr, "bone already added. It can't be added again"); - if (NULL != parentName) + if (nullptr != parentName) { Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); if (boneParent) @@ -286,9 +286,9 @@ void Armature::addBone(Bone *bone, const char *parentName) void Armature::removeBone(Bone *bone, bool recursion) { - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); + CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); - bone->setArmature(NULL); + bone->setArmature(nullptr); bone->removeFromParent(recursion); if (_topBoneList->containsObject(bone)) @@ -308,15 +308,15 @@ Bone *Armature::getBone(const char *name) const void Armature::changeBoneParent(Bone *bone, const char *parentName) { - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); + CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); if(bone->getParentBone()) { bone->getParentBone()->getChildren()->removeObject(bone); - bone->setParentBone(NULL); + bone->setParentBone(nullptr); } - if (parentName != NULL) + if (parentName != nullptr) { Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); @@ -451,7 +451,7 @@ void Armature::update(float dt) { _animation->update(dt); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_topBoneList, object) { static_cast(object)->update(dt); @@ -462,20 +462,20 @@ void Armature::update(float dt) void Armature::draw() { - if (_parentBone == NULL && _batchNode == NULL) + if (_parentBone == nullptr && _batchNode == nullptr) { CC_NODE_DRAW_SETUP(); GL::blendFunc(_blendFunc.src, _blendFunc.dst); } - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) { Node *node = bone->getDisplayRenderNode(); - if (NULL == node) + if (nullptr == node) continue; switch (bone->getDisplayRenderNodeType()) @@ -556,7 +556,7 @@ void Armature::draw() } } - if(_atlas && !_batchNode && _parentBone == NULL) + if(_atlas && !_batchNode && _parentBone == nullptr) { _atlas->drawQuads(); _atlas->removeAllQuads(); @@ -642,7 +642,7 @@ Rect Armature::getBoundingBox() const Rect boundingBox = Rect(0, 0, 0, 0); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) @@ -686,7 +686,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) return bs; } } - return NULL; + return nullptr; } TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) @@ -703,7 +703,7 @@ TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) } TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); - if (atlas == NULL) + if (atlas == nullptr) { atlas = TextureAtlas::createWithTexture(texture, 4); _textureAtlasDic->setObject(atlas, key); @@ -715,7 +715,7 @@ void Armature::setParentBone(Bone *parentBone) { _parentBone = parentBone; - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(_boneDic, element) { Bone *bone = static_cast(element->getObject()); @@ -730,7 +730,7 @@ Bone *Armature::getParentBone() void CCArmature::setColliderFilter(ColliderFilter *filter) { - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(_boneDic, element) { Bone *bone = static_cast(element->getObject()); @@ -754,18 +754,18 @@ void Armature::setBody(b2Body *body) _body = body; _body->SetUserData(this); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = NULL; + Object *displayObject = nullptr; CCARRAY_FOREACH(displayList, displayObject) { ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) + if (detector != nullptr) { detector->setBody(_body); } @@ -782,7 +782,7 @@ b2Fixture *Armature::getShapeList() } else { - return NULL; + return nullptr; } } @@ -802,18 +802,18 @@ void Armature::setBody(cpBody *body) _body = body; _body->data = this; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = NULL; + Object *displayObject = nullptr; CCARRAY_FOREACH(displayList, displayObject) { ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) + if (detector != nullptr) { detector->setBody(_body); } @@ -830,7 +830,7 @@ cpShape *Armature::getShapeList() } else { - return NULL; + return nullptr; } } #endif diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index b58591ae19..9f6fc3331b 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -112,7 +112,7 @@ public: * Add a Bone to this Armature, * * @param bone The Bone you want to add to Armature - * @param parentName The parent Bone's name you want to add to . If it's NULL, then set Armature to its parent + * @param parentName The parent Bone's name you want to add to . If it's nullptr, then set Armature to its parent */ virtual void addBone(Bone *bone, const char *parentName); /** diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index ed6e383751..8f9c9252bd 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -43,24 +43,24 @@ ArmatureAnimation *ArmatureAnimation::create(Armature *armature) return pArmatureAnimation; } CC_SAFE_DELETE(pArmatureAnimation); - return NULL; + return nullptr; } ArmatureAnimation::ArmatureAnimation() - : _animationData(NULL) + : _animationData(nullptr) , _speedScale(1) - , _movementData(NULL) - , _armature(NULL) + , _movementData(nullptr) + , _armature(nullptr) , _movementID("") , _toIndex(0) - , _tweenList(NULL) + , _tweenList(nullptr) , _ignoreFrameEvent(false) - , _movementEventCallFunc(NULL) - , _frameEventCallFunc(NULL) - , _movementEventTarget(NULL) - , _frameEventTarget(NULL) + , _movementEventCallFunc(nullptr) + , _frameEventCallFunc(nullptr) + , _movementEventTarget(nullptr) + , _frameEventTarget(nullptr) { } @@ -94,7 +94,7 @@ bool ArmatureAnimation::init(Armature *armature) void ArmatureAnimation:: pause() { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->pause(); @@ -104,7 +104,7 @@ void ArmatureAnimation:: pause() void ArmatureAnimation::resume() { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->resume(); @@ -114,7 +114,7 @@ void ArmatureAnimation::resume() void ArmatureAnimation::stop() { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->stop(); @@ -145,7 +145,7 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; - DictElement *element = NULL; + DictElement *element = nullptr; Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -173,7 +173,7 @@ void ArmatureAnimation::setAnimationInternal(float animationInternal) _animationInternal = animationInternal; - DictElement *element = NULL; + DictElement *element = nullptr; Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -232,10 +232,10 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura _durationTween = durationTween; } - MovementBoneData *movementBoneData = NULL; + MovementBoneData *movementBoneData = nullptr; _tweenList->removeAllObjects(); - DictElement *element = NULL; + DictElement *element = nullptr; Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) @@ -302,7 +302,7 @@ void ArmatureAnimation::gotoAndPlay(int frameIndex) _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; _currentFrame = _nextFrameIndex * _currentPercent; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->gotoAndPlay(frameIndex); @@ -327,7 +327,7 @@ int ArmatureAnimation::getMovementCount() void ArmatureAnimation::update(float dt) { ProcessBase::update(dt); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->update(dt); diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 5fe23543bf..3c6e7e5a2c 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -182,13 +182,13 @@ public: /** * Set armature's movement event callback function - * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + * To disconnect this event, just setMovementEventCallFunc(nullptr, nullptr); */ void setMovementEventCallFunc(cocos2d::Object *target, SEL_MovementEventCallFunc callFunc); /** * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ void setFrameEventCallFunc(cocos2d::Object *target, SEL_FrameEventCallFunc callFunc); diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index ca1945b418..c8278387ce 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -32,11 +32,11 @@ using namespace cocos2d; namespace cocostudio { -static ArmatureDataManager *s_sharedArmatureDataManager = NULL; +static ArmatureDataManager *s_sharedArmatureDataManager = nullptr; ArmatureDataManager *ArmatureDataManager::getInstance() { - if (s_sharedArmatureDataManager == NULL) + if (s_sharedArmatureDataManager == nullptr) { s_sharedArmatureDataManager = new ArmatureDataManager(); if (!s_sharedArmatureDataManager || !s_sharedArmatureDataManager->init()) @@ -56,9 +56,9 @@ void ArmatureDataManager::destoryInstance() ArmatureDataManager::ArmatureDataManager(void) { - _armarureDatas = NULL; - _animationDatas = NULL; - _textureDatas = NULL; + _armarureDatas = nullptr; + _animationDatas = nullptr; + _textureDatas = nullptr; _autoLoadSpriteFile = false; } @@ -156,7 +156,7 @@ void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armature ArmatureData *ArmatureDataManager::getArmatureData(const char *id) { - ArmatureData *armatureData = NULL; + ArmatureData *armatureData = nullptr; if (_armarureDatas) { armatureData = (ArmatureData *)_armarureDatas->objectForKey(id); @@ -187,7 +187,7 @@ void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animat AnimationData *ArmatureDataManager::getAnimationData(const char *id) { - AnimationData *animationData = NULL; + AnimationData *animationData = nullptr; if (_animationDatas) { animationData = (AnimationData *)_animationDatas->objectForKey(id); @@ -219,7 +219,7 @@ void ArmatureDataManager::addTextureData(const char *id, TextureData *textureDat TextureData *ArmatureDataManager::getTextureData(const char *id) { - TextureData *textureData = NULL; + TextureData *textureData = nullptr; if (_textureDatas) { textureData = (TextureData *)_textureDatas->objectForKey(id); diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 0691058417..c79b58ff81 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -50,7 +50,7 @@ THE SOFTWARE. #endif #define CS_RETURN_IF(cond) if (cond) return -#define CS_RETURN_NULL_IF(cond) if (cond) return NULL; +#define CS_RETURN_NULL_IF(cond) if (cond) return nullptr; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index bb84576d66..d674d8487b 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -40,12 +40,12 @@ BatchNode *BatchNode::create() return batchNode; } CC_SAFE_DELETE(batchNode); - return NULL; + return nullptr; } BatchNode::BatchNode() - : _atlas(NULL) - , _textureAtlasDic(NULL) + : _atlas(nullptr) + , _textureAtlasDic(nullptr) { } @@ -79,18 +79,18 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) { Node::addChild(child, zOrder, tag); Armature *armature = dynamic_cast(child); - if (armature != NULL) + if (armature != nullptr) { armature->setBatchNode(this); Dictionary *dict = armature->getBoneDic(); - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(displayList, object) { DecorativeDisplay *display = static_cast(object); @@ -107,18 +107,18 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) void BatchNode::removeChild(Node* child, bool cleanup) { Armature *armature = dynamic_cast(child); - if (armature != NULL) + if (armature != nullptr) { - armature->setBatchNode(NULL); + armature->setBatchNode(nullptr); Dictionary *dict = armature->getBoneDic(); - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(displayList, object) { DecorativeDisplay *display = static_cast(object); @@ -166,7 +166,7 @@ void BatchNode::visit() void BatchNode::draw() { CC_NODE_DRAW_SETUP(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { Armature *armature = dynamic_cast(object); @@ -193,7 +193,7 @@ TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) int key = texture->getName(); TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); - if (atlas == NULL) + if (atlas == nullptr) { atlas = CCTextureAtlas::createWithTexture(texture, 4); _textureAtlasDic->setObject(atlas, key); diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index faf4b0ee94..45562f898e 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -43,7 +43,7 @@ Bone *Bone::create() return pBone; } CC_SAFE_DELETE(pBone); - return NULL; + return nullptr; } @@ -57,27 +57,27 @@ Bone *Bone::create(const char *name) return pBone; } CC_SAFE_DELETE(pBone); - return NULL; + return nullptr; } Bone::Bone() { - _tweenData = NULL; - _parentBone = NULL; - _armature = NULL; - _childArmature = NULL; - _boneData = NULL; - _tween = NULL; - _tween = NULL; - _children = NULL; - _displayManager = NULL; + _tweenData = nullptr; + _parentBone = nullptr; + _armature = nullptr; + _childArmature = nullptr; + _boneData = nullptr; + _tween = nullptr; + _tween = nullptr; + _children = nullptr; + _displayManager = nullptr; _ignoreMovementBoneData = false; _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); _boneTransformDirty = true; _blendType = BLEND_NORMAL; - _worldInfo = NULL; + _worldInfo = nullptr; - _armatureParentBone = NULL; + _armatureParentBone = nullptr; _dataVersion = 0; } @@ -97,7 +97,7 @@ Bone::~Bone(void) bool Bone::init() { - return Bone::init(NULL); + return Bone::init(nullptr); } @@ -107,7 +107,7 @@ bool Bone::init(const char *name) do { - if(NULL != name) + if(nullptr != name) { _name = name; } @@ -138,7 +138,7 @@ bool Bone::init(const char *name) void Bone::setBoneData(BoneData *boneData) { - CCASSERT(NULL != boneData, "_boneData must not be NULL"); + CCASSERT(nullptr != boneData, "_boneData must not be nullptr"); if (_boneData != boneData) { @@ -169,7 +169,7 @@ void Bone::setArmature(Armature *armature) } else { - _armatureParentBone = NULL; + _armatureParentBone = nullptr; } } @@ -229,7 +229,7 @@ void Bone::update(float delta) DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { Bone *childBone = (Bone *)object; @@ -282,7 +282,7 @@ void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); RGBAProtocol *protocol = dynamic_cast(display); - if(protocol != NULL) + if(protocol != nullptr) { protocol->setColor(Color3B(_displayedColor.r * _tweenData->r / 255, _displayedColor.g * _tweenData->g / 255, _displayedColor.b * _tweenData->b / 255)); protocol->setOpacity(_displayedOpacity * _tweenData->a / 255); @@ -304,8 +304,8 @@ void Bone::updateZOrder() void Bone::addChildBone(Bone *child) { - CCASSERT( NULL != child, "Argument must be non-nil"); - CCASSERT( NULL == child->_parentBone, "child already added. It can't be added again"); + CCASSERT( nullptr != child, "Argument must be non-nil"); + CCASSERT( nullptr == child->_parentBone, "child already added. It can't be added again"); if(!_children) { @@ -327,7 +327,7 @@ void Bone::removeChildBone(Bone *bone, bool recursion) if(recursion) { Array *_ccbones = bone->_children; - Object *_object = NULL; + Object *_object = nullptr; CCARRAY_FOREACH(_ccbones, _object) { Bone *_ccBone = (Bone *)_object; @@ -335,9 +335,9 @@ void Bone::removeChildBone(Bone *bone, bool recursion) } } - bone->setParentBone(NULL); + bone->setParentBone(nullptr); - bone->getDisplayManager()->setCurrentDecorativeDisplay(NULL); + bone->getDisplayManager()->setCurrentDecorativeDisplay(nullptr); _children->removeObject(bone); } @@ -345,7 +345,7 @@ void Bone::removeChildBone(Bone *bone, bool recursion) void Bone::removeFromParent(bool recursion) { - if (NULL != _parentBone) + if (nullptr != _parentBone) { _parentBone->removeChildBone(this, recursion); } @@ -365,9 +365,9 @@ void Bone::setChildArmature(Armature *armature) { if (_childArmature != armature) { - if (armature == NULL && _childArmature) + if (armature == nullptr && _childArmature) { - _childArmature->setParentBone(NULL); + _childArmature->setParentBone(nullptr); } CC_SAFE_RETAIN(armature); @@ -441,7 +441,7 @@ Array *Bone::getColliderBodyList() return detector->getColliderBodyList(); } } - return NULL; + return nullptr; } @@ -449,7 +449,7 @@ Array *Bone::getColliderBodyList() void Bone::setColliderFilter(ColliderFilter *filter) { Array *array = _displayManager->getDecorativeDisplayList(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(array, object) { DecorativeDisplay *decoDisplay = static_cast(object); @@ -468,7 +468,7 @@ ColliderFilter *Bone::getColliderFilter() return detector->getColliderFilter(); } } - return NULL; + return nullptr; } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 6edd3fe8cb..58a15c3987 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -102,7 +102,7 @@ public: * It will not set the Armature, if you want to add the bone to a Armature, you should use Armature::addBone(Bone *bone, const char* parentName). * * @param parent the parent bone. - * NULL : remove this bone from armature + * nullptr : remove this bone from armature */ void setParentBone(Bone *parent); diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 21cf39e486..be587ecefb 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -70,7 +70,7 @@ void ColliderFilter::updateShape(cpShape *shape) #if ENABLE_PHYSICS_BOX2D_DETECT ColliderBody::ColliderBody(ContourData *contourData) - : _fixture(NULL) + : _fixture(nullptr) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); @@ -84,7 +84,7 @@ ColliderBody::ColliderBody(ContourData *contourData) #elif ENABLE_PHYSICS_CHIPMUNK_DETECT ColliderBody::ColliderBody(ContourData *contourData) - : _shape(NULL) + : _shape(nullptr) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); @@ -127,7 +127,7 @@ ColliderDetector *ColliderDetector::create() return pColliderDetector; } CC_SAFE_DELETE(pColliderDetector); - return NULL; + return nullptr; } ColliderDetector *ColliderDetector::create(Bone *bone) @@ -139,15 +139,15 @@ ColliderDetector *ColliderDetector::create(Bone *bone) return pColliderDetector; } CC_SAFE_DELETE(pColliderDetector); - return NULL; + return nullptr; } ColliderDetector::ColliderDetector() - : _colliderBodyList(NULL) - , _filter(NULL) + : _colliderBodyList(nullptr) + , _filter(nullptr) , _active(false) { - _body = NULL; + _body = nullptr; } ColliderDetector::~ColliderDetector() @@ -198,7 +198,7 @@ void ColliderDetector::addContourData(ContourData *contourData) void ColliderDetector::addContourDataList(Array *contourDataList) { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(contourDataList, object) { addContourData((ContourData *)object); @@ -207,7 +207,7 @@ void ColliderDetector::addContourDataList(Array *contourDataList) void ColliderDetector::removeContourData(ContourData *contourData) { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *body = (ColliderBody*)object; @@ -242,28 +242,28 @@ void ColliderDetector::setActive(bool active) } else { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); _body->DestroyFixture(fixture); - colliderBody->setB2Fixture(NULL); + colliderBody->setB2Fixture(nullptr); } } } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT if (_body) { - Object *object = NULL; + Object *object = nullptr; if (_active) { CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - if(shape->space_private == NULL) + if(shape->space_private == nullptr) { cpSpaceAddShape(_body->space_private, shape); } @@ -275,7 +275,7 @@ void ColliderDetector::setActive(bool active) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - if (shape->space_private != NULL) + if (shape->space_private != nullptr) { cpSpaceRemoveShape(_body->space_private, shape); } @@ -299,7 +299,7 @@ void ColliderDetector::setColliderFilter(ColliderFilter *filter) { *_filter = *filter; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; @@ -333,21 +333,21 @@ void ColliderDetector::updateTransform(AffineTransform &t) return; } - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); #if ENABLE_PHYSICS_BOX2D_DETECT - b2PolygonShape *shape = NULL; - if (_body != NULL) + b2PolygonShape *shape = nullptr; + if (_body != nullptr) { shape = (b2PolygonShape *)colliderBody->getB2Fixture()->GetShape(); } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - cpPolyShape *shape = NULL; - if (_body != NULL) + cpPolyShape *shape = nullptr; + if (_body != nullptr) { shape = (cpPolyShape *)colliderBody->getShape(); } @@ -372,13 +372,13 @@ void ColliderDetector::updateTransform(AffineTransform &t) #endif #if ENABLE_PHYSICS_BOX2D_DETECT - if (shape != NULL) + if (shape != nullptr) { b2Vec2 &bv = shape->m_vertices[i]; bv.Set(helpPoint.x / PT_RATIO, helpPoint.y / PT_RATIO); } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - if (shape != NULL) + if (shape != nullptr) { cpVect v ; v.x = helpPoint.x; @@ -389,7 +389,7 @@ void ColliderDetector::updateTransform(AffineTransform &t) } #if ENABLE_PHYSICS_CHIPMUNK_DETECT - cpConvexHull(num, shape->verts, NULL, NULL, 0); + cpConvexHull(num, shape->verts, nullptr, nullptr, 0); for (int i = 0; i < num; i++) { cpVect b = shape->verts[(i + 1) % shape->numVerts]; @@ -408,14 +408,14 @@ void ColliderDetector::setBody(b2Body *pBody) { _body = pBody; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); const Array *array = &contourData->vertexList; - Object *object = NULL; + Object *object = nullptr; b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.count()]; @@ -439,7 +439,7 @@ void ColliderDetector::setBody(b2Body *pBody) b2Fixture *fixture = _body->CreateFixture(&fixtureDef); fixture->SetUserData(_bone); - if (colliderBody->getB2Fixture() != NULL) + if (colliderBody->getB2Fixture() != nullptr) { _body->DestroyFixture(colliderBody->getB2Fixture()); } @@ -459,7 +459,7 @@ void ColliderDetector::setBody(cpBody *pBody) { _body = pBody; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 7ff2117b41..50b59715c7 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -143,14 +143,14 @@ float s_PositionReadScale = 1; std::vector DataReaderHelper::_configFileList; -DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; +DataReaderHelper *DataReaderHelper::_dataReaderHelper = nullptr; //! Async load void DataReaderHelper::loadData() { - AsyncStruct *pAsyncStruct = NULL; + AsyncStruct *pAsyncStruct = nullptr; while (true) { @@ -202,12 +202,12 @@ void DataReaderHelper::loadData() _dataInfoMutex.unlock(); } - if( _asyncStructQueue != NULL ) + if( _asyncStructQueue != nullptr ) { delete _asyncStructQueue; - _asyncStructQueue = NULL; + _asyncStructQueue = nullptr; delete _dataQueue; - _dataQueue = NULL; + _dataQueue = nullptr; } } @@ -259,7 +259,7 @@ DataReaderHelper::~DataReaderHelper() if (_loadingThread) _loadingThread->join(); CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; + _dataReaderHelper = nullptr; } void DataReaderHelper::addDataFromFile(const char *filePath) @@ -301,7 +301,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) DataInfo dataInfo; dataInfo.filename = filePathStr; - dataInfo.asyncStruct = NULL; + dataInfo.asyncStruct = nullptr; dataInfo.baseFilePath = basefilePath; if (str.compare(".xml") == 0) @@ -354,7 +354,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p // lazy init - if (_asyncStructQueue == NULL) + if (_asyncStructQueue == nullptr) { _asyncStructQueue = new std::queue(); _dataQueue = new std::queue(); @@ -591,7 +591,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML * If this bone have parent, then get the parent bone xml */ const char *parentName = boneXML->Attribute(A_PARENT); - tinyxml2::XMLElement *parentXML = NULL; + tinyxml2::XMLElement *parentXML = nullptr; if (parentName) { parentXML = armatureXML->FirstChildElement(BONE); @@ -624,7 +624,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: std::string name = boneXML->Attribute(A_NAME); boneData->name = name; - if( boneXML->Attribute(A_PARENT) != NULL ) + if( boneXML->Attribute(A_PARENT) != nullptr ) { boneData->parentName = boneXML->Attribute(A_PARENT); } @@ -671,7 +671,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXM } - if(displayXML->Attribute(A_NAME) != NULL ) + if(displayXML->Attribute(A_NAME) != nullptr ) { if(!_isArmature) { @@ -740,7 +740,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } const char *_easing = movementXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) + if(_easing != nullptr) { std::string str = _easing; if(str.compare(FL_NAN) != 0) @@ -773,7 +773,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML std::string parentName = boneData->parentName; - tinyxml2::XMLElement *parentXml = NULL; + tinyxml2::XMLElement *parentXml = nullptr; if (parentName.length() != 0) { parentXml = movementXML->FirstChildElement(BONE); @@ -827,14 +827,14 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov int parentTotalDuration = 0; int currentDuration = 0; - tinyxml2::XMLElement *parentFrameXML = NULL; + tinyxml2::XMLElement *parentFrameXML = nullptr; std::vector parentXmlList; /* * get the parent frame xml list, we need get the origin data */ - if( parentXml != NULL ) + if( parentXml != nullptr ) { parentFrameXML = parentXml->FirstChildElement(FRAME); while (parentFrameXML) @@ -843,7 +843,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov parentFrameXML = parentFrameXML->NextSiblingElement(FRAME); } - parentFrameXML = NULL; + parentFrameXML = nullptr; length = parentXmlList.size(); } @@ -925,19 +925,19 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm FrameData *frameData = new FrameData(); - if(frameXML->Attribute(A_MOVEMENT) != NULL) + if(frameXML->Attribute(A_MOVEMENT) != nullptr) { frameData->strMovement = frameXML->Attribute(A_MOVEMENT); } - if(frameXML->Attribute(A_EVENT) != NULL) + if(frameXML->Attribute(A_EVENT) != nullptr) { frameData->strEvent = frameXML->Attribute(A_EVENT); } - if(frameXML->Attribute(A_SOUND) != NULL) + if(frameXML->Attribute(A_SOUND) != nullptr) { frameData->strSound = frameXML->Attribute(A_SOUND); } - if(frameXML->Attribute(A_SOUND_EFFECT) != NULL) + if(frameXML->Attribute(A_SOUND_EFFECT) != nullptr) { frameData->strSoundEffect = frameXML->Attribute(A_SOUND_EFFECT); } @@ -1030,7 +1030,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm const char *_easing = frameXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) + if(_easing != nullptr) { std::string str = _easing; if(str.compare(FL_NAN) != 0) @@ -1081,7 +1081,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML, D TextureData *textureData = new TextureData(); textureData->init(); - if( textureXML->Attribute(A_NAME) != NULL) + if( textureXML->Attribute(A_NAME) != nullptr) { textureData->name = textureXML->Attribute(A_NAME); } @@ -1216,14 +1216,14 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } // Auto load sprite file - bool autoLoad = dataInfo->asyncStruct == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; + bool autoLoad = dataInfo->asyncStruct == nullptr ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; if (autoLoad) { length = json.getArrayItemCount(CONFIG_FILE_PATH); for (int i = 0; i < length; i++) { const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i); - if (path == NULL) + if (path == nullptr) { CCLOG("load CONFIG_FILE_PATH error."); return; @@ -1253,7 +1253,7 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *d armatureData->init(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { armatureData->name = name; } @@ -1282,13 +1282,13 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json, DataInfo *dataInfo) decodeNode(boneData, json, dataInfo); const char *str = json.getItemStringValue(A_NAME); - if(str != NULL) + if(str != nullptr) { boneData->name = str; } str = json.getItemStringValue(A_PARENT); - if(str != NULL) + if(str != nullptr) { boneData->parentName = str; } @@ -1312,7 +1312,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo { DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); - DisplayData *displayData = NULL; + DisplayData *displayData = nullptr; switch (displayType) { @@ -1321,13 +1321,13 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo displayData = new SpriteDisplayData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { ((SpriteDisplayData *)displayData)->displayName = name; } JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); - if (dic != NULL) + if (dic != nullptr) { SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; sdd->skinData.x = dic->getItemFloatValue(A_X, 0) * s_PositionReadScale; @@ -1350,7 +1350,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo displayData = new ArmatureDisplayData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { ((ArmatureDisplayData *)displayData)->displayName = name; } @@ -1361,7 +1361,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo displayData = new ParticleDisplayData(); const char *plist = json.getItemStringValue(A_PLIST); - if(plist != NULL) + if(plist != nullptr) { if (dataInfo->asyncStruct) { @@ -1391,7 +1391,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json, DataInfo AnimationData *aniData = new AnimationData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { aniData->name = name; } @@ -1423,7 +1423,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *d movementData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { movementData->name = name; } @@ -1450,7 +1450,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat movementBoneData->delay = json.getItemFloatValue(A_MOVEMENT_DELAY, 0); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { movementBoneData->name = name; } @@ -1526,7 +1526,7 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); const char *event = json.getItemStringValue(A_EVENT); - if (event != NULL) + if (event != nullptr) { frameData->strEvent = event; } @@ -1549,7 +1549,7 @@ TextureData *DataReaderHelper::decodeTexture(JsonDictionary &json) textureData->init(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { textureData->name = name; } @@ -1612,7 +1612,7 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - JsonDictionary *colorDic = NULL; + JsonDictionary *colorDic = nullptr; if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING) { colorDic = json.getSubItemFromArray(COLOR_INFO, 0); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index 82f551e52f..33088e0043 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -119,7 +119,7 @@ public: * * @param xmlPath The cache of the xml */ - static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = NULL); + static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = nullptr); @@ -151,7 +151,7 @@ public: static ContourData *decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo); public: - static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); + static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = nullptr); static ArmatureData *decodeArmature(JsonDictionary &json, DataInfo *dataInfo); static BoneData *decodeBone(JsonDictionary &json, DataInfo *dataInfo); diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 5f08757d13..4b9c2feca6 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -39,7 +39,7 @@ public: \ return var;\ }\ CC_SAFE_DELETE(var);\ - return NULL;\ + return nullptr;\ } #define CC_CREATE_NO_PARAM(varType)\ @@ -52,7 +52,7 @@ public: \ return var;\ }\ CC_SAFE_DELETE(var);\ - return NULL;\ + return nullptr;\ } namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp index e595ecbe0c..81cc4bc751 100644 --- a/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp @@ -37,16 +37,16 @@ DecorativeDisplay *DecorativeDisplay::create() return pDisplay; } CC_SAFE_DELETE(pDisplay); - return NULL; + return nullptr; } DecorativeDisplay::DecorativeDisplay() - : _display(NULL) - , _displayData(NULL) + : _display(nullptr) + , _displayData(nullptr) { #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - _colliderDetector = NULL; + _colliderDetector = nullptr; #endif } diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index b130428ab1..7f329ff3cc 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -133,7 +133,7 @@ void DisplayFactory::addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay) { - Skin *skin = NULL; + Skin *skin = nullptr; SpriteDisplayData *displayData = (SpriteDisplayData *)decoDisplay->getDisplayData(); @@ -157,7 +157,7 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp decoDisplay->setDisplay(skin); - if (skin == NULL) + if (skin == nullptr) { return; } diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index bffcf80c64..5efa5510c7 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -41,19 +41,19 @@ DisplayManager *DisplayManager::create(Bone *bone) return pDisplayManager; } CC_SAFE_DELETE(pDisplayManager); - return NULL; + return nullptr; } DisplayManager::DisplayManager() - : _decoDisplayList(NULL) - , _displayRenderNode(NULL) + : _decoDisplayList(nullptr) + , _displayRenderNode(nullptr) , _displayType(CS_DISPLAY_MAX) - , _currentDecoDisplay(NULL) + , _currentDecoDisplay(nullptr) , _displayIndex(-1) , _forceChangeDisplay(false) , _visible(true) - , _bone(NULL) + , _bone(nullptr) { } @@ -91,7 +91,7 @@ bool DisplayManager::init(Bone *bone) void DisplayManager::addDisplay(DisplayData *displayData, int index) { - DecorativeDisplay *decoDisplay = NULL; + DecorativeDisplay *decoDisplay = nullptr; if( (index >= 0) && (index < _decoDisplayList->count()) ) { @@ -115,7 +115,7 @@ void DisplayManager::addDisplay(DisplayData *displayData, int index) void DisplayManager::addDisplay(Node *display, int index) { - DecorativeDisplay *decoDisplay = NULL; + DecorativeDisplay *decoDisplay = nullptr; if( (index >= 0) && (index < _decoDisplayList->count()) ) { @@ -127,7 +127,7 @@ void DisplayManager::addDisplay(Node *display, int index) _decoDisplayList->addObject(decoDisplay); } - DisplayData *displayData = NULL; + DisplayData *displayData = nullptr; if (Skin *skin = dynamic_cast(display)) { skin->setBone(_bone); @@ -175,7 +175,7 @@ void DisplayManager::removeDisplay(int index) { if(index == _displayIndex) { - setCurrentDecorativeDisplay(NULL); + setCurrentDecorativeDisplay(nullptr); _displayIndex = -1; } @@ -206,7 +206,7 @@ void DisplayManager::changeDisplayByIndex(int index, bool force) if(_displayRenderNode) { _displayRenderNode->removeFromParentAndCleanup(true); - setCurrentDecorativeDisplay(NULL); + setCurrentDecorativeDisplay(nullptr); } return; } @@ -235,12 +235,12 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) } #endif - Node *displayRenderNode = _currentDecoDisplay == NULL ? NULL : _currentDecoDisplay->getDisplay(); + Node *displayRenderNode = _currentDecoDisplay == nullptr ? nullptr : _currentDecoDisplay->getDisplay(); if (_displayRenderNode) { - if (dynamic_cast(_displayRenderNode) != NULL) + if (dynamic_cast(_displayRenderNode) != nullptr) { - _bone->setChildArmature(NULL); + _bone->setChildArmature(nullptr); } _displayRenderNode->removeFromParentAndCleanup(true); _displayRenderNode->release(); @@ -310,7 +310,7 @@ void DisplayManager::initDisplayList(BoneData *boneData) CS_RETURN_IF(!boneData); - Object *object = NULL; + Object *object = nullptr; Array *displayDataList = &boneData->displayDataList; CCARRAY_FOREACH(displayDataList, object) { diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 5cb8483a95..b0496729f4 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -48,7 +48,7 @@ Skin *Skin::create() return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) @@ -60,7 +60,7 @@ Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin *Skin::create(const char *pszFileName) @@ -72,12 +72,12 @@ Skin *Skin::create(const char *pszFileName) return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin::Skin() - : _bone(NULL) - , _armature(NULL) + : _bone(nullptr) + , _armature(nullptr) , _displayName("") { _skinTransform = AffineTransformIdentity; @@ -85,12 +85,12 @@ Skin::Skin() bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) { - CCAssert(pszSpriteFrameName != NULL, ""); + CCAssert(pszSpriteFrameName != nullptr, ""); SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pszSpriteFrameName); bool ret = true; - if (pFrame != NULL) + if (pFrame != nullptr) { ret = initWithSpriteFrame(pFrame); } @@ -188,7 +188,7 @@ void Skin::updateTransform() SET_VERTEX3F( _quad.tr.vertices, RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); } - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS + // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS if (_textureAtlas) { _textureAtlas->updateQuad(&_quad, _textureAtlas->getTotalQuads()); diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index 68fa7ebfb5..d3e2b620fd 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -29,7 +29,7 @@ using namespace cocos2d; namespace cocostudio { -SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = NULL; +SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = nullptr; SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() { @@ -44,7 +44,7 @@ SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() void SpriteFrameCacheHelper::purge() { delete _spriteFrameCacheHelper; - _spriteFrameCacheHelper = NULL; + _spriteFrameCacheHelper = nullptr; } void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *plistPath, const char *imagePath) diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index ce55cb4189..75ff8bbb7e 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -43,24 +43,24 @@ Tween *Tween::create(Bone *bone) return pTween; } CC_SAFE_DELETE(pTween); - return NULL; + return nullptr; } Tween::Tween() - : _movementBoneData(NULL) - , _tweenData(NULL) - , _from(NULL) - , _to(NULL) - , _between(NULL) - , _bone(NULL) + : _movementBoneData(nullptr) + , _tweenData(nullptr) + , _from(nullptr) + , _to(nullptr) + , _between(nullptr) + , _bone(nullptr) , _frameTweenEasing(Linear) , _fromIndex(0) , _toIndex(0) - , _animation(NULL) + , _animation(nullptr) , _passLastFrame(false) { @@ -86,7 +86,7 @@ bool Tween::init(Bone *bone) _tweenData = _bone->getTweenData(); _tweenData->displayIndex = -1; - _animation = _bone->getArmature() != NULL ? _bone->getArmature()->getAnimation() : NULL; + _animation = _bone->getArmature() != nullptr ? _bone->getArmature()->getAnimation() : nullptr; bRet = true; } @@ -98,7 +98,7 @@ bool Tween::init(Bone *bone) void Tween::play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing) { - ProcessBase::play(NULL, durationTo, durationTween, loop, tweenEasing); + ProcessBase::play(nullptr, durationTo, durationTween, loop, tweenEasing); if (loop) { @@ -354,7 +354,7 @@ void Tween::arriveKeyFrame(FrameData *keyFrameData) FrameData *Tween::tweenNodeTo(float percent, FrameData *node) { - node = node == NULL ? _tweenData : node; + node = node == nullptr ? _tweenData : node; if (!_from->isTween) { @@ -407,8 +407,8 @@ float Tween::updateFrameData(float currentPercent) int length = _movementBoneData->frameList.count(); FrameData **frames = (FrameData **)_movementBoneData->frameList.data->arr; - FrameData *from = NULL; - FrameData *to = NULL; + FrameData *from = nullptr; + FrameData *to = nullptr; if (playedTime < frames[0]->frameID) { diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index c4fc110334..ce08f2264e 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -108,7 +108,7 @@ protected: /** * According to the percent to calculate current FrameData with tween effect */ - virtual FrameData *tweenNodeTo(float percent, FrameData *node = NULL); + virtual FrameData *tweenNodeTo(float percent, FrameData *node = nullptr); /** * According to the percent to calculate current color with tween effect diff --git a/extensions/CocoStudio/Armature/CCArmature.cpp b/extensions/CocoStudio/Armature/CCArmature.cpp deleted file mode 100644 index c5709b0418..0000000000 --- a/extensions/CocoStudio/Armature/CCArmature.cpp +++ /dev/null @@ -1,785 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCArmature.h" -#include "utils/CCArmatureDataManager.h" -#include "utils/CCArmatureDefine.h" -#include "utils/CCDataReaderHelper.h" -#include "datas/CCDatas.h" -#include "display/CCSkin.h" - -#if ENABLE_PHYSICS_BOX2D_DETECT -#include "Box2D/Box2D.h" -#elif ENABLE_PHYSICS_CHIPMUNK_DETECT -#include "chipmunk.h" -#endif - - -NS_CC_EXT_ARMATURE_BEGIN - -Armature *Armature::create() -{ - Armature *armature = new Armature(); - if (armature && armature->init()) - { - armature->autorelease(); - return armature; - } - CC_SAFE_DELETE(armature); - return NULL; -} - - -Armature *Armature::create(const char *name) -{ - Armature *armature = new Armature(); - if (armature && armature->init(name)) - { - armature->autorelease(); - return armature; - } - CC_SAFE_DELETE(armature); - return NULL; -} - -Armature *Armature::create(const char *name, Bone *parentBone) -{ - Armature *armature = new Armature(); - if (armature && armature->init(name, parentBone)) - { - armature->autorelease(); - return armature; - } - CC_SAFE_DELETE(armature); - return NULL; -} - -Armature::Armature() - : _armatureData(NULL) - , _batchNode(NULL) - , _atlas(NULL) - , _parentBone(NULL) - , _armatureTransformDirty(true) - , _boneDic(NULL) - , _topBoneList(NULL) - , _animation(NULL) -{ -} - - -Armature::~Armature(void) -{ - if(NULL != _boneDic) - { - _boneDic->removeAllObjects(); - CC_SAFE_DELETE(_boneDic); - } - if (NULL != _topBoneList) - { - _topBoneList->removeAllObjects(); - CC_SAFE_DELETE(_topBoneList); - } - CC_SAFE_DELETE(_animation); -} - - -bool Armature::init() -{ - return init(NULL); -} - - -bool Armature::init(const char *name) -{ - bool bRet = false; - do - { - removeAllChildren(); - - CC_SAFE_DELETE(_animation); - _animation = new ArmatureAnimation(); - _animation->init(this); - - CC_SAFE_DELETE(_boneDic); - _boneDic = new Dictionary(); - - CC_SAFE_DELETE(_topBoneList); - _topBoneList = new Array(); - _topBoneList->init(); - - _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; - - - _name = name == NULL ? "" : name; - - ArmatureDataManager *armatureDataManager = ArmatureDataManager::getInstance(); - - if(_name.length() != 0) - { - _name = name; - - AnimationData *animationData = armatureDataManager->getAnimationData(name); - CCASSERT(animationData, "AnimationData not exist! "); - - _animation->setAnimationData(animationData); - - - ArmatureData *armatureData = armatureDataManager->getArmatureData(name); - CCASSERT(armatureData, ""); - - _armatureData = armatureData; - - - DictElement *_element = NULL; - Dictionary *boneDataDic = &armatureData->boneDataDic; - CCDICT_FOREACH(boneDataDic, _element) - { - Bone *bone = createBone(_element->getStrKey()); - - //! init bone's Tween to 1st movement's 1st frame - do - { - - MovementData *movData = animationData->getMovement(animationData->movementNames.at(0).c_str()); - CC_BREAK_IF(!movData); - - MovementBoneData *movBoneData = movData->getMovementBoneData(bone->getName().c_str()); - CC_BREAK_IF(!movBoneData || movBoneData->frameList.count() <= 0); - - FrameData *frameData = movBoneData->getFrameData(0); - CC_BREAK_IF(!frameData); - - bone->getTweenData()->copy(frameData); - bone->changeDisplayByIndex(frameData->displayIndex, false); - } - while (0); - } - - update(0); - updateOffsetPoint(); - } - else - { - _name = "new_armature"; - _armatureData = ArmatureData::create(); - _armatureData->name = _name; - - AnimationData *animationData = AnimationData::create(); - animationData->name = _name; - - armatureDataManager->addArmatureData(_name.c_str(), _armatureData); - armatureDataManager->addAnimationData(_name.c_str(), animationData); - - _animation->setAnimationData(animationData); - - } - - setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); - - unscheduleUpdate(); - scheduleUpdate(); - - setCascadeOpacityEnabled(true); - setCascadeColorEnabled(true); - - bRet = true; - } - while (0); - - return bRet; -} - -bool Armature::init(const char *name, Bone *parentBone) -{ - _parentBone = parentBone; - return init(name); -} - - -Bone *Armature::createBone(const char *boneName) -{ - Bone *existedBone = getBone(boneName); - if(existedBone != NULL) - return existedBone; - - BoneData *boneData = (BoneData *)_armatureData->getBoneData(boneName); - std::string parentName = boneData->parentName; - - Bone *bone = NULL; - - if( parentName.length() != 0 ) - { - createBone(parentName.c_str()); - bone = Bone::create(boneName); - addBone(bone, parentName.c_str()); - } - else - { - bone = Bone::create(boneName); - addBone(bone, ""); - } - - bone->setBoneData(boneData); - bone->getDisplayManager()->changeDisplayByIndex(-1, false); - - return bone; -} - - -void Armature::addBone(Bone *bone, const char *parentName) -{ - CCASSERT( bone != NULL, "Argument must be non-nil"); - CCASSERT(_boneDic->objectForKey(bone->getName()) == NULL, "bone already added. It can't be added again"); - - if (NULL != parentName) - { - Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); - if (boneParent) - { - boneParent->addChildBone(bone); - } - else - { - _topBoneList->addObject(bone); - } - } - else - { - _topBoneList->addObject(bone); - } - - bone->setArmature(this); - - _boneDic->setObject(bone, bone->getName()); - addChild(bone); -} - - -void Armature::removeBone(Bone *bone, bool recursion) -{ - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); - - bone->setArmature(NULL); - bone->removeFromParent(recursion); - - if (_topBoneList->containsObject(bone)) - { - _topBoneList->removeObject(bone); - } - _boneDic->removeObjectForKey(bone->getName()); - removeChild(bone, true); -} - - -Bone *Armature::getBone(const char *name) const -{ - return (Bone *)_boneDic->objectForKey(name); -} - - -void Armature::changeBoneParent(Bone *bone, const char *parentName) -{ - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); - - if(bone->getParentBone()) - { - bone->getParentBone()->getChildren()->removeObject(bone); - bone->setParentBone(NULL); - } - - if (parentName != NULL) - { - Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); - - if (boneParent) - { - boneParent->addChildBone(bone); - if (_topBoneList->containsObject(bone)) - { - _topBoneList->removeObject(bone); - } - } - else - { - _topBoneList->addObject(bone); - } - } -} - -Dictionary *Armature::getBoneDic() -{ - return _boneDic; -} - -const AffineTransform &Armature::getNodeToParentTransform() const -{ - if (_transformDirty) - { - _armatureTransformDirty = true; - - // Translate values - float x = _position.x; - float y = _position.y; - - if (_ignoreAnchorPointForPosition) - { - x += _anchorPointInPoints.x; - y += _anchorPointInPoints.y; - } - - // Rotation values - // Change rotation code to handle X and Y - // If we skew with the exact same value for both x and y then we're simply just rotating - float cx = 1, sx = 0, cy = 1, sy = 0; - if (_rotationX || _rotationY) - { - float radiansX = -CC_DEGREES_TO_RADIANS(_rotationX); - float radiansY = -CC_DEGREES_TO_RADIANS(_rotationY); - cx = cosf(radiansX); - sx = sinf(radiansX); - cy = cosf(radiansY); - sy = sinf(radiansY); - } - - // Add offset point - x += cy * _offsetPoint.x * _scaleX + -sx * _offsetPoint.y * _scaleY; - y += sy * _offsetPoint.x * _scaleX + cx * _offsetPoint.y * _scaleY; - - bool needsSkewMatrix = ( _skewX || _skewY ); - - // optimization: - // inline anchor point calculation if skew is not needed - // Adjusted transform calculation for rotational skew - if (! needsSkewMatrix && !_anchorPointInPoints.equals(Point::ZERO)) - { - x += cy * -_anchorPointInPoints.x * _scaleX + -sx * -_anchorPointInPoints.y * _scaleY; - y += sy * -_anchorPointInPoints.x * _scaleX + cx * -_anchorPointInPoints.y * _scaleY; - } - - - // Build Transform Matrix - // Adjusted transform calculation for rotational skew - _transform = AffineTransformMake( cy * _scaleX, sy * _scaleX, - -sx * _scaleY, cx * _scaleY, - x, y ); - - // XXX: Try to inline skew - // If skew is needed, apply skew and then anchor point - if (needsSkewMatrix) - { - AffineTransform skewMatrix = AffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(_skewY)), - tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, - 0.0f, 0.0f ); - _transform = AffineTransformConcat(skewMatrix, _transform); - - // adjust anchor point - if (!_anchorPointInPoints.equals(Point::ZERO)) - { - _transform = AffineTransformTranslate(_transform, -_anchorPointInPoints.x, -_anchorPointInPoints.y); - } - } - - if (_additionalTransformDirty) - { - _transform = AffineTransformConcat(_transform, _additionalTransform); - _additionalTransformDirty = false; - } - - _transformDirty = false; - } - - return _transform; -} - -void Armature::updateOffsetPoint() -{ - // Set contentsize and Calculate anchor point. - Rect rect = getBoundingBox(); - setContentSize(rect.size); - _offsetPoint = Point(-rect.origin.x, -rect.origin.y); - if (rect.size.width != 0 && rect.size.height != 0) - { - setAnchorPoint(Point(_offsetPoint.x / rect.size.width, _offsetPoint.y / rect.size.height)); - } -} - -void Armature::setAnimation(ArmatureAnimation *animation) -{ - _animation = animation; -} - -ArmatureAnimation *Armature::getAnimation() -{ - return _animation; -} - -bool Armature::getArmatureTransformDirty() -{ - return _armatureTransformDirty; -} - -void Armature::update(float dt) -{ - _animation->update(dt); - - Object *object = NULL; - CCARRAY_FOREACH(_topBoneList, object) - { - static_cast(object)->update(dt); - } - - _armatureTransformDirty = false; -} - -void Armature::draw() -{ - if (_parentBone == NULL) - { - CC_NODE_DRAW_SETUP(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - DisplayManager *displayManager = bone->getDisplayManager(); - Node *node = displayManager->getDisplayRenderNode(); - - if (NULL == node) - continue; - - switch (displayManager->getCurrentDecorativeDisplay()->getDisplayData()->displayType) - { - case CS_DISPLAY_SPRITE: - { - Skin *skin = static_cast(node); - - TextureAtlas *textureAtlas = skin->getTextureAtlas(); - BlendType blendType = bone->getBlendType(); - if(_atlas != textureAtlas || blendType != BLEND_NORMAL) - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - } - - _atlas = textureAtlas; - if (_atlas->getCapacity() == _atlas->getTotalQuads() && !_atlas->resizeCapacity(_atlas->getCapacity() * 2)) - return; - - skin->updateTransform(); - - if (blendType != BLEND_NORMAL) - { - updateBlendType(blendType); - _atlas->drawQuads(); - _atlas->removeAllQuads(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - } - break; - case CS_DISPLAY_ARMATURE: - { - Armature *armature = static_cast(node); - - TextureAtlas *textureAtlas = armature->getTextureAtlas(); - if(_atlas != textureAtlas) - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - } - armature->draw(); - - _atlas = armature->getTextureAtlas(); - } - break; - default: - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - node->visit(); - - CC_NODE_DRAW_SETUP(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - break; - } - } - else if(Node *node = dynamic_cast(object)) - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - node->visit(); - - CC_NODE_DRAW_SETUP(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - } - - if(_atlas && !_batchNode && _parentBone == NULL) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } -} - - -void Armature::updateBlendType(BlendType blendType) -{ - BlendFunc blendFunc; - switch (blendType) - { - case BLEND_NORMAL: - { - blendFunc.src = CC_BLEND_SRC; - blendFunc.dst = CC_BLEND_DST; - } - break; - case BLEND_ADD: - { - blendFunc.src = GL_SRC_ALPHA; - blendFunc.dst = GL_ONE; - } - break; - case BLEND_MULTIPLY: - { - blendFunc.src = GL_DST_COLOR; - blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA; - } - break; - case BLEND_SCREEN: - { - blendFunc.src = GL_ONE; - blendFunc.dst = GL_ONE_MINUS_SRC_COLOR; - } - break; - default: - { - blendFunc.src = CC_BLEND_SRC; - blendFunc.dst = CC_BLEND_DST; - } - break; - } - GL::blendFunc(blendFunc.src, blendFunc.dst); -} - - - -void Armature::visit() -{ - // quick return if not visible. children won't be drawn. - if (!_visible) - { - return; - } - kmGLPushMatrix(); - - if (_grid && _grid->isActive()) - { - _grid->beforeDraw(); - } - - transform(); - sortAllChildren(); - draw(); - updateEventPriorityIndex(); - - // reset for next frame - _orderOfArrival = 0; - - if (_grid && _grid->isActive()) - { - _grid->afterDraw(this); - } - - kmGLPopMatrix(); -} - -Rect Armature::getBoundingBox() const -{ - float minx, miny, maxx, maxy = 0; - - bool first = true; - - Rect boundingBox = Rect(0, 0, 0, 0); - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - Rect r = bone->getDisplayManager()->getBoundingBox(); - - if(first) - { - minx = r.getMinX(); - miny = r.getMinY(); - maxx = r.getMaxX(); - maxy = r.getMaxY(); - - first = false; - } - else - { - minx = r.getMinX() < boundingBox.getMinX() ? r.getMinX() : boundingBox.getMinX(); - miny = r.getMinY() < boundingBox.getMinY() ? r.getMinY() : boundingBox.getMinY(); - maxx = r.getMaxX() > boundingBox.getMaxX() ? r.getMaxX() : boundingBox.getMaxX(); - maxy = r.getMaxY() > boundingBox.getMaxY() ? r.getMaxY() : boundingBox.getMaxY(); - } - - boundingBox.setRect(minx, miny, maxx - minx, maxy - miny); - } - } - - return boundingBox; -} - -Bone *Armature::getBoneAtPoint(float x, float y) -{ - int length = _children->count(); - Bone *bs; - - for(int i = length - 1; i >= 0; i--) - { - bs = static_cast( _children->getObjectAtIndex(i) ); - if(bs->getDisplayManager()->containPoint(x, y)) - { - return bs; - } - } - return NULL; -} - -#if ENABLE_PHYSICS_BOX2D_DETECT -b2Body *Armature::getBody() -{ - return _body; -} - -void Armature::setBody(b2Body *body) -{ - if (_body == body) - { - return; - } - - _body = body; - _body->SetUserData(this); - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - - Object *displayObject = NULL; - CCARRAY_FOREACH(displayList, displayObject) - { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) - { - detector->setBody(_body); - } - } - } - } -} - -b2Fixture *Armature::getShapeList() -{ - if (_body) - { - return _body->GetFixtureList(); - } - else - { - return NULL; - } -} - -#elif ENABLE_PHYSICS_CHIPMUNK_DETECT -cpBody *Armature::getBody() -{ - return _body; -} - -void Armature::setBody(cpBody *body) -{ - if (_body == body) - { - return; - } - - _body = body; - _body->data = this; - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - - Object *displayObject = NULL; - CCARRAY_FOREACH(displayList, displayObject) - { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) - { - detector->setBody(_body); - } - } - } - } -} - -cpShape *Armature::getShapeList() -{ - if (_body) - { - return _body->shapeList_private; - } - else - { - return NULL; - } -} -#endif - - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/CCBone.cpp b/extensions/CocoStudio/Armature/CCBone.cpp deleted file mode 100644 index d9ad2bfdc7..0000000000 --- a/extensions/CocoStudio/Armature/CCBone.cpp +++ /dev/null @@ -1,401 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCBone.h" -#include "CCArmature.h" -#include "utils/CCUtilMath.h" -#include "utils/CCArmatureDataManager.h" -#include "utils/CCTransformHelp.h" -#include "display/CCDisplayManager.h" - -NS_CC_EXT_ARMATURE_BEGIN - -Bone *Bone::create() -{ - - Bone *pBone = new Bone(); - if (pBone && pBone->init()) - { - pBone->autorelease(); - return pBone; - } - CC_SAFE_DELETE(pBone); - return NULL; - -} - -Bone *Bone::create(const char *name) -{ - - Bone *pBone = new Bone(); - if (pBone && pBone->init(name)) - { - pBone->autorelease(); - return pBone; - } - CC_SAFE_DELETE(pBone); - return NULL; -} - -Bone::Bone() -{ - _tweenData = NULL; - _parentBone = NULL; - _armature = NULL; - _childArmature = NULL; - _boneData = NULL; - _tween = NULL; - _tween = NULL; - _children = NULL; - _displayManager = NULL; - _ignoreMovementBoneData = false; - _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); - _boneTransformDirty = true; - _blendType = BLEND_NORMAL; -} - - -Bone::~Bone(void) -{ - CC_SAFE_DELETE(_tweenData); - CC_SAFE_DELETE(_children); - CC_SAFE_DELETE(_tween); - CC_SAFE_DELETE(_displayManager); - - if(_boneData) - { - _boneData->release(); - } - - CC_SAFE_RELEASE(_childArmature); -} - -bool Bone::init() -{ - return Bone::init(NULL); -} - - -bool Bone::init(const char *name) -{ - bool bRet = false; - do - { - - if(NULL != name) - { - _name = name; - } - - CC_SAFE_DELETE(_tweenData); - _tweenData = new FrameData(); - - CC_SAFE_DELETE(_tween); - _tween = new Tween(); - _tween->init(this); - - CC_SAFE_DELETE(_displayManager); - _displayManager = new DisplayManager(); - _displayManager->init(this); - - - bRet = true; - } - while (0); - - return bRet; -} - -void Bone::setBoneData(BoneData *boneData) -{ - CCASSERT(NULL != boneData, "_boneData must not be NULL"); - - _boneData = boneData; - _boneData->retain(); - - _name = _boneData->name; - _ZOrder = _boneData->zOrder; - - _displayManager->initDisplayList(boneData); -} - -BoneData *Bone::getBoneData() -{ - return _boneData; -} - -void Bone::setArmature(Armature *armature) -{ - _armature = armature; - if (_armature) - { - _tween->setAnimation(_armature->getAnimation()); - } -} - - -Armature *Bone::getArmature() -{ - return _armature; -} - -void Bone::update(float delta) -{ - if (_parentBone) - _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); - - CCBone *armatureParentBone = _armature->getParentBone(); - if (armatureParentBone && !_boneTransformDirty) - { - _boneTransformDirty = armatureParentBone->isTransformDirty(); - } - - - if (_boneTransformDirty) - { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) - { - TransformHelp::nodeConcat(*_tweenData, *_boneData); - _tweenData->scaleX -= 1; - _tweenData->scaleY -= 1; - } - - TransformHelp::nodeToMatrix(*_tweenData, _worldTransform); - - _worldTransform = AffineTransformConcat(getNodeToParentTransform(), _worldTransform); - - if(_parentBone) - { - _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); - } - else - { - if (armatureParentBone) - { - _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); - } - } - } - - DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - Bone *childBone = (Bone *)object; - childBone->update(delta); - } - - _boneTransformDirty = false; -} - - -void Bone::updateDisplayedColor(const Color3B &parentColor) -{ - _realColor = Color3B(255, 255, 255); - NodeRGBA::updateDisplayedColor(parentColor); - updateColor(); -} - -void Bone::updateDisplayedOpacity(GLubyte parentOpacity) -{ - _realOpacity = 255; - NodeRGBA::updateDisplayedOpacity(parentOpacity); - updateColor(); -} - -void Bone::setColor(const Color3B &color) -{ - CCNodeRGBA::setColor(color); - updateColor(); -} -void Bone::setOpacity(GLubyte opacity) -{ - CCNodeRGBA::setOpacity(opacity); - updateColor(); -} - -void Bone::updateColor() -{ - Node *display = _displayManager->getDisplayRenderNode(); - RGBAProtocol *protocol = dynamic_cast(display); - if(protocol != NULL) - { - protocol->setColor(Color3B(_displayedColor.r * _tweenData->r / 255, _displayedColor.g * _tweenData->g / 255, _displayedColor.b * _tweenData->b / 255)); - protocol->setOpacity(_displayedOpacity * _tweenData->a / 255); - } -} - -void Bone::updateZOrder() -{ - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) - { - int zorder = _tweenData->zOrder + _boneData->zOrder; - setZOrder(zorder); - } - else - { - setZOrder(_tweenData->zOrder); - } -} - -void Bone::addChildBone(Bone *child) -{ - CCASSERT( NULL != child, "Argument must be non-nil"); - CCASSERT( NULL == child->_parentBone, "child already added. It can't be added again"); - - if(!_children) - { - _children = Array::createWithCapacity(4); - _children->retain(); - } - - if (_children->getIndexOfObject(child) == UINT_MAX) - { - _children->addObject(child); - child->setParentBone(this); - } -} - -void Bone::removeChildBone(Bone *bone, bool recursion) -{ - if ( _children->getIndexOfObject(bone) != UINT_MAX ) - { - if(recursion) - { - Array *_ccbones = bone->_children; - Object *_object = NULL; - CCARRAY_FOREACH(_ccbones, _object) - { - Bone *_ccBone = (Bone *)_object; - bone->removeChildBone(_ccBone, recursion); - } - } - - bone->setParentBone(NULL); - - bone->getDisplayManager()->setCurrentDecorativeDisplay(NULL); - - _children->removeObject(bone); - } -} - -void Bone::removeFromParent(bool recursion) -{ - if (NULL != _parentBone) - { - _parentBone->removeChildBone(this, recursion); - } -} - -void Bone::setParentBone(Bone *parent) -{ - _parentBone = parent; -} - -Bone *Bone::getParentBone() -{ - return _parentBone; -} - -void Bone::setChildArmature(Armature *armature) -{ - if (_childArmature != armature) - { - CC_SAFE_RETAIN(armature); - CC_SAFE_RELEASE(_childArmature); - _childArmature = armature; - } -} - -Armature *Bone::getChildArmature() -{ - return _childArmature; -} - -Tween *Bone::getTween() -{ - return _tween; -} - -void Bone::setZOrder(int zOrder) -{ - if (_ZOrder != zOrder) - Node::setZOrder(zOrder); -} - -void Bone::setTransformDirty(bool dirty) -{ - _boneTransformDirty = dirty; -} - -bool Bone::isTransformDirty() -{ - return _boneTransformDirty; -} - -AffineTransform Bone::getNodeToArmatureTransform() const -{ - return _worldTransform; -} - -AffineTransform Bone::getNodeToWorldTransform() const -{ - return AffineTransformConcat(_worldTransform, _armature->getNodeToWorldTransform()); -} - -Node *Bone::getDisplayRenderNode() -{ - return _displayManager->getDisplayRenderNode(); -} - -void Bone::addDisplay(DisplayData *displayData, int index) -{ - _displayManager->addDisplay(displayData, index); -} - -void Bone::addDisplay(Node *display, int index) -{ - _displayManager->addDisplay(display, index); -} - -void Bone::changeDisplayByIndex(int index, bool force) -{ - _displayManager->changeDisplayByIndex(index, force); -} - -Array *Bone::getColliderBodyList() -{ - if (DecorativeDisplay *decoDisplay = _displayManager->getCurrentDecorativeDisplay()) - { - if (ColliderDetector *detector = decoDisplay->getColliderDetector()) - { - return detector->getColliderBodyList(); - } - } - return NULL; -} - - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/CCBone.h b/extensions/CocoStudio/Armature/CCBone.h deleted file mode 100644 index 1aecfcb099..0000000000 --- a/extensions/CocoStudio/Armature/CCBone.h +++ /dev/null @@ -1,199 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CCBONE_H__ -#define __CCBONE_H__ - -#include "utils/CCArmatureDefine.h" -#include "datas/CCDatas.h" -#include "animation/CCTween.h" -#include "display/CCDecorativeDisplay.h" -#include "display/CCDisplayManager.h" - -NS_CC_EXT_ARMATURE_BEGIN - - -class Armature; - -class Bone : public NodeRGBA -{ -public: - /** - * Allocates and initializes a bone. - * @return A initialized bone which is marked as "autorelease". - */ - static Bone *create(); - /** - * Allocates and initializes a bone. - * - * @param name If name is not null, then set name to the bone's name - * @return A initialized bone which is marked as "autorelease". - */ - static Bone *create(const char *name); - -public: - Bone(); - /** - * @js NA - * @lua NA - */ - virtual ~Bone(void); - - /** - * Initializes an empty Bone with nothing init. - */ - virtual bool init(); - - /** - * Initializes a Bone with the specified name - * @param name Bone's name. - */ - virtual bool init(const char *name); - - /** - * Add display and use displayData to init the display. - * If index already have a display, then replace it. - * If index is current display index, then also change display to _index - * - * @param displayData it include the display information, like DisplayType. - * If you want to create a sprite display, then create a SpriteDisplayData param - * - * @param index the index of the display you want to replace or add to - * -1 : append display from back - */ - void addDisplay(DisplayData *displayData, int index); - - void addDisplay(Node *display, int index); - - void changeDisplayByIndex(int index, bool force); - - /** - * Add a child to this bone, and it will let this child call setParent(Bone *parent) function to set self to it's parent - * @param child the child you want to add - */ - void addChildBone(Bone *child); - - /** - * Set parent bone. - * If parent is NUll, then also remove this bone from armature. - * It will not set the Armature, if you want to add the bone to a Armature, you should use Armature::addBone(Bone *bone, const char* parentName). - * - * @param parent the parent bone. - * NULL : remove this bone from armature - */ - void setParentBone(Bone *parent); - - /** - * Get parent bone - * @return parent bone - */ - Bone *getParentBone(); - - /** - * Remove itself from its parent. - * @param recursion whether or not to remove childBone's display - */ - void removeFromParent(bool recursion); - - /** - * Removes a child Bone - * @param bone the bone you want to remove - */ - void removeChildBone(Bone *bone, bool recursion); - - void update(float delta) override; - - virtual void updateDisplayedColor(const Color3B &parentColor) override; - virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; - - virtual void setColor(const Color3B& color) override; - virtual void setOpacity(GLubyte opacity) override; - - //! Update color to render display - virtual void updateColor(); - - //! Update zorder - virtual void updateZOrder(); - - virtual void setZOrder(int zOrder) override; - - Tween *getTween(); - - /* - * Whether or not the bone's transform property changed. if true, the bone will update the transform. - */ - virtual void setTransformDirty(bool dirty); - - virtual bool isTransformDirty(); - - virtual AffineTransform getNodeToArmatureTransform() const; - virtual AffineTransform getNodeToWorldTransform() const override; - - Node *getDisplayRenderNode(); - - /* - * Get the ColliderBody list in this bone. The object in the Array is ColliderBody. - */ - virtual Array *getColliderBodyList(); - -public: - /* - * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData - * when call setData function, it will copy from the BoneData. - */ - CC_PROPERTY(BoneData *, _boneData, BoneData); - - //! A weak reference to the Armature - CC_PROPERTY(Armature *, _armature, Armature); - - //! A weak reference to the child Armature - CC_PROPERTY(Armature *, _childArmature, ChildArmature); - - CC_SYNTHESIZE(DisplayManager *, _displayManager, DisplayManager) - - /* - * When Armature play an animation, if there is not a MovementBoneData of this bone in this MovementData, this bone will be hidden. - * Set IgnoreMovementBoneData to true, then this bone will also be shown. - */ - CC_SYNTHESIZE(bool, _ignoreMovementBoneData, IgnoreMovementBoneData) - - CC_SYNTHESIZE(BlendType, _blendType, BlendType) -protected: - Tween *_tween; //! Calculate tween effect - - //! Used for making tween effect in every frame - CC_SYNTHESIZE_READONLY(FrameData *, _tweenData, TweenData); - - CC_SYNTHESIZE(std::string, _name, Name); - - Bone *_parentBone; //! A weak reference to its parent - bool _boneTransformDirty; //! Whether or not transform dirty - - //! self Transform, use this to change display's state - AffineTransform _worldTransform; -}; - -NS_CC_EXT_ARMATURE_END - -#endif /*__CCBONE_H__*/ diff --git a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp b/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp deleted file mode 100644 index ae69ea8230..0000000000 --- a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp +++ /dev/null @@ -1,396 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCDisplayManager.h" -#include "../CCBone.h" -#include "../CCArmature.h" -#include "../utils/CCUtilMath.h" -#include "../display/CCSkin.h" - -NS_CC_EXT_ARMATURE_BEGIN - -DisplayManager *DisplayManager::create(Bone *bone) -{ - DisplayManager *pDisplayManager = new DisplayManager(); - if (pDisplayManager && pDisplayManager->init(bone)) - { - pDisplayManager->autorelease(); - return pDisplayManager; - } - CC_SAFE_DELETE(pDisplayManager); - return NULL; -} - - -DisplayManager::DisplayManager() - : _decoDisplayList(NULL) - , _displayRenderNode(NULL) - , _currentDecoDisplay(NULL) - , _displayIndex(-1) - , _forceChangeDisplay(false) - , _visible(true) - , _bone(NULL) -{ -} - -DisplayManager::~DisplayManager() -{ - CC_SAFE_DELETE(_decoDisplayList); - - if( _displayRenderNode ) - { - _displayRenderNode->removeFromParentAndCleanup(true); - if(_displayRenderNode->retainCount() > 0) - CC_SAFE_RELEASE_NULL(_displayRenderNode); - } - -} - -bool DisplayManager::init(Bone *bone) -{ - bool ret = false; - - do - { - - _bone = bone; - - initDisplayList(bone->getBoneData()); - - ret = true; - } - while (0); - - return ret; -} - - -void DisplayManager::addDisplay(DisplayData *displayData, int index) -{ - DecorativeDisplay *decoDisplay = NULL; - - if(index >= 0 && (unsigned int)index < _decoDisplayList->count()) - { - decoDisplay = (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); - } - else - { - decoDisplay = DecorativeDisplay::create(); - _decoDisplayList->addObject(decoDisplay); - } - - DisplayFactory::addDisplay(_bone, decoDisplay, displayData); - - //! if changed display index is current display index, then change current display to the new display - if(index == _displayIndex) - { - _displayIndex = -1; - changeDisplayByIndex(index, false); - } -} - -void DisplayManager::addDisplay(Node *display, int index) -{ - DecorativeDisplay *decoDisplay = NULL; - - if(index >= 0 && (unsigned int)index < _decoDisplayList->count()) - { - decoDisplay = (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); - } - else - { - decoDisplay = DecorativeDisplay::create(); - _decoDisplayList->addObject(decoDisplay); - } - - DisplayData *displayData = NULL; - if (Skin *skin = dynamic_cast(display)) - { - skin->setBone(_bone); - displayData = SpriteDisplayData::create(); - - DisplayFactory::initSpriteDisplay(_bone, decoDisplay, skin->getDisplayName().c_str(), skin); - - if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) - { - skin->setSkinData(spriteDisplayData->skinData); - ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; - } - else - { - BaseData baseData; - skin->setSkinData(baseData); - } - } - else if (dynamic_cast(display)) - { - displayData = ParticleDisplayData::create(); - } - else if(Armature *armature = dynamic_cast(display)) - { - displayData = ArmatureDisplayData::create(); - armature->setParentBone(_bone); - } - else - { - displayData = DisplayData::create(); - } - - decoDisplay->setDisplay(display); - decoDisplay->setDisplayData(displayData); - - //! if changed display index is current display index, then change current display to the new display - if(index == _displayIndex) - { - _displayIndex = -1; - changeDisplayByIndex(index, false); - } -} - -void DisplayManager::removeDisplay(int index) -{ - _decoDisplayList->removeObjectAtIndex(index); - - if(index == _displayIndex) - { - setCurrentDecorativeDisplay(NULL); - } -} - -Array *DisplayManager::getDecorativeDisplayList() -{ - return _decoDisplayList; -} - -void DisplayManager::changeDisplayByIndex(int index, bool force) -{ - CCASSERT( (_decoDisplayList ? index < (int)_decoDisplayList->count() : true), "the _index value is out of range"); - - _forceChangeDisplay = force; - - //! If index is equal to current display index,then do nothing - if ( _displayIndex == index) - return; - - - _displayIndex = index; - - //! If displayIndex < 0, it means you want to hide you display - if (_displayIndex < 0) - { - if(_displayRenderNode) - { - _displayRenderNode->removeFromParentAndCleanup(true); - setCurrentDecorativeDisplay(NULL); - } - return; - } - - - DecorativeDisplay *decoDisplay = (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(_displayIndex); - - setCurrentDecorativeDisplay(decoDisplay); -} - -void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) -{ -#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - if (_currentDecoDisplay && _currentDecoDisplay->getColliderDetector()) - { - _currentDecoDisplay->getColliderDetector()->setActive(false); - } -#endif - - _currentDecoDisplay = decoDisplay; - -#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - if (_currentDecoDisplay && _currentDecoDisplay->getColliderDetector()) - { - _currentDecoDisplay->getColliderDetector()->setActive(true); - } -#endif - - Node *displayRenderNode = _currentDecoDisplay == NULL ? NULL : _currentDecoDisplay->getDisplay(); - if (_displayRenderNode) - { - if (dynamic_cast(_displayRenderNode) != NULL) - { - _bone->setChildArmature(NULL); - } - _displayRenderNode->removeFromParentAndCleanup(true); - _displayRenderNode->release(); - } - - _displayRenderNode = displayRenderNode; - - if(_displayRenderNode) - { - if (Armature *armature = dynamic_cast(_displayRenderNode)) - { - _bone->setChildArmature(armature); - } - else if (ParticleSystemQuad *particle = dynamic_cast(_displayRenderNode)) - { - particle->resetSystem(); - } - - if (RGBAProtocol *rgbaProtocaol = dynamic_cast(_displayRenderNode)) - { - rgbaProtocaol->setColor(_bone->getDisplayedColor()); - rgbaProtocaol->setOpacity(_bone->getDisplayedOpacity()); - } - - _displayRenderNode->retain(); - _displayRenderNode->setVisible(_visible); - } -} - -Node *DisplayManager::getDisplayRenderNode() -{ - return _displayRenderNode; -} - -int DisplayManager::getCurrentDisplayIndex() -{ - return _displayIndex; -} - -DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() -{ - return _currentDecoDisplay; -} - -DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) -{ - return (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); -} - -void DisplayManager::initDisplayList(BoneData *boneData) -{ - CC_SAFE_DELETE(_decoDisplayList); - _decoDisplayList = Array::create(); - _decoDisplayList->retain(); - - CS_RETURN_IF(!boneData); - - Object *object = NULL; - Array *displayDataList = &boneData->displayDataList; - CCARRAY_FOREACH(displayDataList, object) - { - DisplayData *displayData = (DisplayData *)object; - - DecorativeDisplay *decoDisplay = DecorativeDisplay::create(); - decoDisplay->setDisplayData(displayData); - - DisplayFactory::createDisplay(_bone, decoDisplay); - - _decoDisplayList->addObject(decoDisplay); - } -} - - -bool DisplayManager::containPoint(Point &point) -{ - if(!_visible || _displayIndex < 0) - { - return false; - } - - bool ret = false; - - switch (_currentDecoDisplay->getDisplayData()->displayType) - { - case CS_DISPLAY_SPRITE: - { - /* - * First we first check if the point is in the sprite content rect. If false, then we continue to check - * the contour point. If this step is also false, then we can say the bone not contain this point. - * - */ - - Point outPoint = Point(0, 0); - - Sprite *sprite = (Sprite *)_currentDecoDisplay->getDisplay(); - sprite = (Sprite *)sprite->getChildByTag(0); - - ret = CC_SPRITE_CONTAIN_POINT_WITH_RETURN(sprite, point, outPoint); - - } - break; - - default: - break; - } - return ret; -} - -bool DisplayManager::containPoint(float x, float y) -{ - Point p = Point(x, y); - return containPoint(p); -} - - -void DisplayManager::setVisible(bool visible) -{ - if(!_displayRenderNode) - return; - - _visible = visible; - _displayRenderNode->setVisible(visible); -} - -bool DisplayManager::isVisible() -{ - return _visible; -} - - -Size DisplayManager::getContentSize() -{ - CS_RETURN_IF(!_displayRenderNode) Size(0, 0); - return _displayRenderNode->getContentSize(); -} - -Rect DisplayManager::getBoundingBox() -{ - CS_RETURN_IF(!_displayRenderNode) Rect(0, 0, 0, 0); - return _displayRenderNode->getBoundingBox(); -} - - -Point DisplayManager::getAnchorPoint() -{ - CS_RETURN_IF(!_displayRenderNode) Point(0, 0); - return _displayRenderNode->getAnchorPoint(); -} - -Point DisplayManager::getAnchorPointInPoints() -{ - CS_RETURN_IF(!_displayRenderNode) Point(0, 0); - return _displayRenderNode->getAnchorPointInPoints(); -} - - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/display/CCSkin.cpp b/extensions/CocoStudio/Armature/display/CCSkin.cpp deleted file mode 100644 index a35bbffcbe..0000000000 --- a/extensions/CocoStudio/Armature/display/CCSkin.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCSkin.h" -#include "../utils/CCTransformHelp.h" -#include "../utils/CCSpriteFrameCacheHelper.h" -#include "../CCArmature.h" - -NS_CC_EXT_ARMATURE_BEGIN - -#if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) -#endif - -Skin *Skin::create() -{ - Skin *skin = new Skin(); - if(skin && skin->init()) - { - skin->autorelease(); - return skin; - } - CC_SAFE_DELETE(skin); - return NULL; -} - -Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) -{ - Skin *skin = new Skin(); - if(skin && skin->initWithSpriteFrameName(pszSpriteFrameName)) - { - skin->autorelease(); - return skin; - } - CC_SAFE_DELETE(skin); - return NULL; -} - -Skin *Skin::create(const char *pszFileName) -{ - Skin *skin = new Skin(); - if(skin && skin->initWithFile(pszFileName)) - { - skin->autorelease(); - return skin; - } - CC_SAFE_DELETE(skin); - return NULL; -} - -Skin::Skin() - : _bone(NULL) - , _displayName("") -{ - _skinTransform = AffineTransformIdentity; -} - -bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) -{ - bool ret = Sprite::initWithSpriteFrameName(pszSpriteFrameName); - - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszSpriteFrameName; - } - - return ret; -} - -bool Skin::initWithFile(const char *pszFilename) -{ - bool ret = Sprite::initWithFile(pszFilename); - - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszFilename; - } - - return ret; -} - -void Skin::setSkinData(const BaseData &var) -{ - _skinData = var; - - setScaleX(_skinData.scaleX); - setScaleY(_skinData.scaleY); - setRotation(CC_RADIANS_TO_DEGREES(_skinData.skewX)); - setPosition(Point(_skinData.x, _skinData.y)); - - _skinTransform = getNodeToParentTransform(); - updateArmatureTransform(); -} - -const BaseData &Skin::getSkinData() const -{ - return _skinData; -} - -void Skin::updateArmatureTransform() -{ - _transform = AffineTransformConcat(_skinTransform, _bone->getNodeToArmatureTransform()); -} - -void Skin::updateTransform() -{ - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if( !_visible) - { - _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0, 0, 0); - } - else - { - // - // calculate the Quad based on the Affine Matrix - // - - Size &size = _rect.size; - - float x1 = _offsetPosition.x; - float y1 = _offsetPosition.y; - - float x2 = x1 + size.width; - float y2 = y1 + size.height; - - float x = _transform.tx; - float y = _transform.ty; - - float cr = _transform.a; - float sr = _transform.b; - float cr2 = _transform.d; - float sr2 = -_transform.c; - float ax = x1 * cr - y1 * sr2 + x; - float ay = x1 * sr + y1 * cr2 + y; - - float bx = x2 * cr - y1 * sr2 + x; - float by = x2 * sr + y1 * cr2 + y; - - float cx = x2 * cr - y2 * sr2 + x; - float cy = x2 * sr + y2 * cr2 + y; - - float dx = x1 * cr - y2 * sr2 + x; - float dy = x1 * sr + y2 * cr2 + y; - - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); - } - - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS - if (_textureAtlas) - { - _textureAtlas->updateQuad(&_quad, _textureAtlas->getTotalQuads()); - } -} - -AffineTransform Skin::getNodeToWorldTransform() const -{ - return AffineTransformConcat(_transform, _bone->getArmature()->getNodeToWorldTransform()); -} - -AffineTransform Skin::getNodeToWorldTransformAR() const -{ - AffineTransform displayTransform = _transform; - Point anchorPoint = _anchorPointInPoints; - - anchorPoint = PointApplyAffineTransform(anchorPoint, displayTransform); - - displayTransform.tx = anchorPoint.x; - displayTransform.ty = anchorPoint.y; - - return AffineTransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); -} - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp deleted file mode 100644 index cbd53fe1e0..0000000000 --- a/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCArmatureDefine.h" - -NS_CC_EXT_ARMATURE_BEGIN - -const char *armatureVersion() -{ - return "0.4.0.0"; -} - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp deleted file mode 100644 index 45b63c4db5..0000000000 --- a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp +++ /dev/null @@ -1,1582 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "support/tinyxml2/tinyxml2.h" -#include "CCDataReaderHelper.h" -#include "CCArmatureDataManager.h" -#include "CCTransformHelp.h" -#include "CCUtilMath.h" -#include "CCArmatureDefine.h" -#include "../datas/CCDatas.h" - - -static const char *VERSION = "version"; -static const float VERSION_2_0 = 2.0f; - -static const char *ARMATURES = "armatures"; -static const char *ARMATURE = "armature"; -static const char *BONE = "b"; -static const char *DISPLAY = "d"; - -static const char *ANIMATIONS = "animations"; -static const char *ANIMATION = "animation"; -static const char *MOVEMENT = "mov"; -static const char *FRAME = "f"; - -static const char *TEXTURE_ATLAS = "TextureAtlas"; -static const char *SUB_TEXTURE = "SubTexture"; - -static const char *A_NAME = "name"; -static const char *A_DURATION = "dr"; -static const char *A_FRAME_INDEX = "fi"; -static const char *A_DURATION_TO = "to"; -static const char *A_DURATION_TWEEN = "drTW"; -static const char *A_LOOP = "lp"; -static const char *A_MOVEMENT_SCALE = "sc"; -static const char *A_MOVEMENT_DELAY = "dl"; -static const char *A_DISPLAY_INDEX = "dI"; - -// static const char *A_VERT = "vert"; -// static const char *A_FRAG = "frag"; -static const char *A_PLIST = "plist"; - -static const char *A_PARENT = "parent"; -static const char *A_SKEW_X = "kX"; -static const char *A_SKEW_Y = "kY"; -static const char *A_SCALE_X = "cX"; -static const char *A_SCALE_Y = "cY"; -static const char *A_Z = "z"; -static const char *A_EVENT = "evt"; -static const char *A_SOUND = "sd"; -static const char *A_SOUND_EFFECT = "sdE"; -static const char *A_TWEEN_EASING = "twE"; -//static const char *A_TWEEN_ROTATE = "twR"; -static const char *A_IS_ARMATURE = "isArmature"; -static const char *A_DISPLAY_TYPE = "displayType"; -static const char *A_MOVEMENT = "mov"; - -static const char *A_X = "x"; -static const char *A_Y = "y"; - -static const char *A_COCOS2DX_X = "cocos2d_x"; -static const char *A_COCOS2DX_Y = "cocos2d_y"; - -static const char *A_WIDTH = "width"; -static const char *A_HEIGHT = "height"; -static const char *A_PIVOT_X = "pX"; -static const char *A_PIVOT_Y = "pY"; - -static const char *A_COCOS2D_PIVOT_X = "cocos2d_pX"; -static const char *A_COCOS2D_PIVOT_Y = "cocos2d_pY"; - -static const char *A_BLEND_TYPE = "bd"; - -static const char *A_ALPHA = "a"; -static const char *A_RED = "r"; -static const char *A_GREEN = "g"; -static const char *A_BLUE = "b"; -static const char *A_ALPHA_OFFSET = "aM"; -static const char *A_RED_OFFSET = "rM"; -static const char *A_GREEN_OFFSET = "gM"; -static const char *A_BLUE_OFFSET = "bM"; -static const char *A_COLOR_TRANSFORM = "colorTransform"; -static const char *A_TWEEN_FRAME = "tweenFrame"; -//static const char *A_ROTATION = "rotation"; -//static const char *A_USE_COLOR_INFO = "uci"; - - - -static const char *CONTOUR = "con"; -static const char *CONTOUR_VERTEX = "con_vt"; - -//static const char *MOVEMENT_EVENT_FRAME = "movementEventFrame"; -//static const char *SOUND_FRAME = "soundFrame"; - - -static const char *FL_NAN = "NaN"; - - -static const char *FRAME_DATA = "frame_data"; -static const char *MOVEMENT_BONE_DATA = "mov_bone_data"; -static const char *MOVEMENT_DATA = "mov_data"; -static const char *ANIMATION_DATA = "animation_data"; -static const char *DISPLAY_DATA = "display_data"; -static const char *SKIN_DATA = "skin_data"; -static const char *BONE_DATA = "bone_data"; -static const char *ARMATURE_DATA = "armature_data"; -static const char *CONTOUR_DATA = "contour_data"; -static const char *TEXTURE_DATA = "texture_data"; -static const char *VERTEX_POINT = "vertex"; -static const char *COLOR_INFO = "color"; - -static const char *CONFIG_FILE_PATH = "config_file_path"; - - -NS_CC_EXT_ARMATURE_BEGIN - - -std::vector s_arrConfigFileList; -float s_PositionReadScale = 1; -static float s_FlashToolVersion = VERSION_2_0; -static float s_CocoStudioVersion = VERSION_COMBINED; - -static std::string s_BasefilePath = ""; - -DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; - - - -//! Async load -void DataReaderHelper::loadData() -{ - AsyncStruct *pAsyncStruct = NULL; - - while (true) - { - // create autorelease pool for iOS - Thread thread; - thread.createAutoreleasePool(); - - std::queue *pQueue = _asyncStructQueue; - _asyncStructQueueMutex.lock(); // get async struct from queue - if (pQueue->empty()) - { - _asyncStructQueueMutex.unlock(); - if (need_quit) - { - break; - } - else - { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); - continue; - } - } - else - { - pAsyncStruct = pQueue->front(); - pQueue->pop(); - _asyncStructQueueMutex.unlock(); - } - - // generate image info - DataInfo *pDataInfo = new DataInfo(); - pDataInfo->asyncStruct = pAsyncStruct; - - if (pAsyncStruct->configType == DragonBone_XML) - { - DataReaderHelper::addDataFromCache(pAsyncStruct->fileContent.c_str(), pDataInfo); - } - else if(pAsyncStruct->configType == CocoStudio_JSON) - { - DataReaderHelper::addDataFromJsonCache(pAsyncStruct->fileContent.c_str(), pDataInfo); - } - - // put the image info into the queue - _dataInfoMutex.lock(); - _dataQueue->push(pDataInfo); - _dataInfoMutex.unlock(); - } - - if( _asyncStructQueue != NULL ) - { - delete _asyncStructQueue; - _asyncStructQueue = NULL; - delete _dataQueue; - _dataQueue = NULL; - } -} - - -DataReaderHelper *DataReaderHelper::getInstance() -{ - if(!_dataReaderHelper) - { - _dataReaderHelper = new DataReaderHelper(); - } - - return _dataReaderHelper; -} - -void DataReaderHelper::setPositionReadScale(float scale) -{ - s_PositionReadScale = scale; -} - -float DataReaderHelper::getPositionReadScale() -{ - return s_PositionReadScale; -} - - -void DataReaderHelper::purge() -{ - DataReaderHelper::clear(); - CC_SAFE_RELEASE_NULL(_dataReaderHelper); -} - -void DataReaderHelper::clear() -{ - s_arrConfigFileList.clear(); -} - -DataReaderHelper::DataReaderHelper() - : _loadingThread(nullptr) - , _asyncStructQueue(nullptr) - , _dataQueue(nullptr) - , need_quit(false) - , _asyncRefCount(0) - , _asyncRefTotalCount(0) -{ - -} - -DataReaderHelper::~DataReaderHelper() -{ - need_quit = true; - - _sleepCondition.notify_one(); - if (_loadingThread) _loadingThread->join(); - - CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; -} - -void DataReaderHelper::addDataFromFile(const char *filePath) -{ - /* - * Check if file is already added to ArmatureDataManager, if then return. - */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) - { - if (s_arrConfigFileList[i].compare(filePath) == 0) - { - return; - } - } - s_arrConfigFileList.push_back(filePath); - - - //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); - if (pos != std::string::npos) - { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); - } - else - { - s_BasefilePath = ""; - } - - - std::string filePathStr = filePath; - size_t startPos = filePathStr.find_last_of("."); - std::string str = &filePathStr[startPos]; - - unsigned long size; - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); - - if (str.compare(".xml") == 0) - { - DataReaderHelper::addDataFromCache(pFileContent); - } - else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) - { - DataReaderHelper::addDataFromJsonCache(pFileContent); - } -} - -void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target, SEL_SCHEDULE selector) -{ - /* - * Check if file is already added to ArmatureDataManager, if then return. - */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) - { - if (s_arrConfigFileList[i].compare(filePath) == 0) - { - if (target && selector) - { - if (_asyncRefTotalCount == 0 && _asyncRefCount == 0) - { - (target->*selector)(1); - } - else - { - (target->*selector)((_asyncRefTotalCount - _asyncRefCount) / (float)_asyncRefTotalCount); - } - } - return; - } - } - s_arrConfigFileList.push_back(filePath); - - //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); - if (pos != std::string::npos) - { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); - } - else - { - s_BasefilePath = ""; - } - - - // lazy init - if (_asyncStructQueue == NULL) - { - _asyncStructQueue = new std::queue(); - _dataQueue = new std::queue(); - - // create a new thread to load images - _loadingThread = new std::thread(&DataReaderHelper::loadData, this); - - need_quit = false; - } - - if (0 == _asyncRefCount) - { - Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); - } - - ++_asyncRefCount; - ++_asyncRefTotalCount; - - if (target) - { - target->retain(); - } - - // generate async struct - AsyncStruct *data = new AsyncStruct(); - data->filename = filePath; - data->baseFilePath = s_BasefilePath; - data->target = target; - data->selector = selector; - data->autoLoadSpriteFile = ArmatureDataManager::getInstance()->isAutoLoadSpriteFile(); - - - std::string filePathStr = filePath; - size_t startPos = filePathStr.find_last_of("."); - std::string str = &filePathStr[startPos]; - - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - unsigned long size; - data->fileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); - - if (str.compare(".xml") == 0) - { - data->configType = DragonBone_XML; - } - else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) - { - data->configType = CocoStudio_JSON; - } - - - // add async struct into queue - _asyncStructQueueMutex.lock(); - _asyncStructQueue->push(data); - _asyncStructQueueMutex.unlock(); - - _sleepCondition.notify_one(); -} - -void DataReaderHelper::addDataAsyncCallBack(float dt) -{ - // the data is generated in loading thread - std::queue *dataQueue = _dataQueue; - - _dataInfoMutex.lock(); - if (dataQueue->empty()) - { - _dataInfoMutex.unlock(); - } - else - { - DataInfo *pDataInfo = dataQueue->front(); - dataQueue->pop(); - _dataInfoMutex.unlock(); - - AsyncStruct *pAsyncStruct = pDataInfo->asyncStruct; - - while (!pDataInfo->configFileQueue.empty()) - { - std::string configPath = pDataInfo->configFileQueue.front(); - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str()); - pDataInfo->configFileQueue.pop(); - } - - - Object *target = pAsyncStruct->target; - SEL_SCHEDULE selector = pAsyncStruct->selector; - - --_asyncRefCount; - - if (target && selector) - { - (target->*selector)((_asyncRefTotalCount - _asyncRefCount) / (float)_asyncRefTotalCount); - target->release(); - } - - - delete pAsyncStruct; - delete pDataInfo; - - if (0 == _asyncRefCount) - { - _asyncRefTotalCount = 0; - CCDirector::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); - } - } -} - - - - - - -void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *dataInfo) -{ - tinyxml2::XMLDocument document; - document.Parse(pFileContent); - - tinyxml2::XMLElement *root = document.RootElement(); - CCASSERT(root, "XML error or XML is empty."); - - root->QueryFloatAttribute(VERSION, &s_FlashToolVersion); - - - /* - * Begin decode armature data from xml - */ - tinyxml2::XMLElement *armaturesXML = root->FirstChildElement(ARMATURES); - tinyxml2::XMLElement *armatureXML = armaturesXML->FirstChildElement(ARMATURE); - while(armatureXML) - { - ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); - armatureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - - armatureXML = armatureXML->NextSiblingElement(ARMATURE); - } - - - /* - * Begin decode animation data from xml - */ - tinyxml2::XMLElement *animationsXML = root->FirstChildElement(ANIMATIONS); - tinyxml2::XMLElement *animationXML = animationsXML->FirstChildElement(ANIMATION); - while(animationXML) - { - AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); - animationData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - animationXML = animationXML->NextSiblingElement(ANIMATION); - } - - - /* - * Begin decode texture data from xml - */ - tinyxml2::XMLElement *texturesXML = root->FirstChildElement(TEXTURE_ATLAS); - tinyxml2::XMLElement *textureXML = texturesXML->FirstChildElement(SUB_TEXTURE); - while(textureXML) - { - TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); - textureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - textureXML = textureXML->NextSiblingElement(SUB_TEXTURE); - } -} - -ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML) -{ - ArmatureData *armatureData = new ArmatureData(); - armatureData->init(); - - const char *name = armatureXML->Attribute(A_NAME); - armatureData->name = name; - - - tinyxml2::XMLElement *boneXML = armatureXML->FirstChildElement(BONE); - - while( boneXML ) - { - /* - * If this bone have parent, then get the parent bone xml - */ - const char *parentName = boneXML->Attribute(A_PARENT); - tinyxml2::XMLElement *parentXML = NULL; - if (parentName) - { - parentXML = armatureXML->FirstChildElement(BONE); - std::string name = parentName; - while (parentXML) - { - if (name.compare(parentXML->Attribute(A_NAME)) == 0) - { - break; - } - parentXML = parentXML->NextSiblingElement(BONE); - } - } - - BoneData *boneData = decodeBone(boneXML, parentXML); - armatureData->addBoneData(boneData); - boneData->release(); - - boneXML = boneXML->NextSiblingElement(BONE); - } - - return armatureData; -} - -BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml) -{ - BoneData *boneData = new BoneData(); - boneData->init(); - - std::string name = boneXML->Attribute(A_NAME); - boneData->name = name; - - if( boneXML->Attribute(A_PARENT) != NULL ) - { - boneData->parentName = boneXML->Attribute(A_PARENT); - } - - boneXML->QueryIntAttribute(A_Z, &boneData->zOrder); - - tinyxml2::XMLElement *displayXML = boneXML->FirstChildElement(DISPLAY); - while(displayXML) - { - DisplayData *displayData = decodeBoneDisplay(displayXML); - boneData->addDisplayData(displayData); - displayData->release(); - - displayXML = displayXML->NextSiblingElement(DISPLAY); - } - - return boneData; -} - -DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML) -{ - int _isArmature = 0; - - DisplayData *displayData; - - if( displayXML->QueryIntAttribute(A_IS_ARMATURE, &(_isArmature)) == tinyxml2::XML_SUCCESS ) - { - if(!_isArmature) - { - displayData = new SpriteDisplayData(); - displayData->displayType = CS_DISPLAY_SPRITE; - } - else - { - displayData = new ArmatureDisplayData(); - displayData->displayType = CS_DISPLAY_ARMATURE; - } - - } - else - { - displayData = new SpriteDisplayData(); - displayData->displayType = CS_DISPLAY_SPRITE; - } - - - if(displayXML->Attribute(A_NAME) != NULL ) - { - if(!_isArmature) - { - ((SpriteDisplayData *)displayData)->displayName = displayXML->Attribute(A_NAME); - } - else - { - ((ArmatureDisplayData *)displayData)->displayName = displayXML->Attribute(A_NAME); - } - - } - - return displayData; -} - -AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML) -{ - AnimationData *aniData = new AnimationData(); - - const char *name = animationXML->Attribute(A_NAME); - - ArmatureData *armatureData = ArmatureDataManager::getInstance()->getArmatureData(name); - - aniData->name = name; - - tinyxml2::XMLElement *movementXML = animationXML->FirstChildElement(MOVEMENT); - - while( movementXML ) - { - MovementData *movementData = decodeMovement(movementXML, armatureData); - aniData->addMovement(movementData); - movementData->release(); - - movementXML = movementXML->NextSiblingElement(MOVEMENT); - - } - - return aniData; -} - -MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData) -{ - MovementData *movementData = new MovementData(); - - const char *movName = movementXML->Attribute(A_NAME); - movementData->name = movName; - - - int duration, durationTo, durationTween, loop, tweenEasing = 0; - - if( movementXML->QueryIntAttribute(A_DURATION, &(duration)) == tinyxml2::XML_SUCCESS) - { - movementData->duration = duration; - } - if( movementXML->QueryIntAttribute(A_DURATION_TO, &(durationTo)) == tinyxml2::XML_SUCCESS) - { - movementData->durationTo = durationTo; - } - if( movementXML->QueryIntAttribute(A_DURATION_TWEEN, &(durationTween)) == tinyxml2::XML_SUCCESS) - { - movementData->durationTween = durationTween; - } - if( movementXML->QueryIntAttribute(A_LOOP, &(loop)) == tinyxml2::XML_SUCCESS) - { - movementData->loop = (bool)loop; - } - - const char *_easing = movementXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) - { - std::string str = _easing; - if(str.compare(FL_NAN) != 0) - { - if( movementXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) - { - movementData->tweenEasing = (CCTweenType)tweenEasing; - } - } - else - { - movementData->tweenEasing = TWEEN_EASING_MAX; - } - } - - tinyxml2::XMLElement *movBoneXml = movementXML->FirstChildElement(BONE); - while(movBoneXml) - { - const char *boneName = movBoneXml->Attribute(A_NAME); - - if (movementData->getMovementBoneData(boneName)) - { - movBoneXml = movBoneXml->NextSiblingElement(); - continue; - } - - - BoneData *boneData = (BoneData *)armatureData->getBoneData(boneName); - - std::string parentName = boneData->parentName; - - - tinyxml2::XMLElement *parentXml = NULL; - if (parentName.length() != 0) - { - parentXml = movementXML->FirstChildElement(BONE); - - while (parentXml) - { - if (parentName.compare(parentXml->Attribute(A_NAME)) == 0) - { - break; - } - parentXml = parentXml->NextSiblingElement(BONE); - } - } - - MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData); - movementData->addMovementBoneData(moveBoneData); - moveBoneData->release(); - - movBoneXml = movBoneXml->NextSiblingElement(BONE); - } - - return movementData; -} - - -MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData) -{ - MovementBoneData *movBoneData = new MovementBoneData(); - movBoneData->init(); - - float scale, delay; - - if( movBoneXml ) - { - if( movBoneXml->QueryFloatAttribute(A_MOVEMENT_SCALE, &scale) == tinyxml2::XML_SUCCESS ) - { - movBoneData->scale = scale; - } - if( movBoneXml->QueryFloatAttribute(A_MOVEMENT_DELAY, &delay) == tinyxml2::XML_SUCCESS ) - { - if(delay > 0) - { - delay -= 1; - } - movBoneData->delay = delay; - } - } - - int length = 0; - int i = 0; - int parentTotalDuration = 0; - int currentDuration = 0; - - tinyxml2::XMLElement *parentFrameXML = NULL; - - std::vector parentXmlList; - - /* - * get the parent frame xml list, we need get the origin data - */ - if( parentXml != NULL ) - { - parentFrameXML = parentXml->FirstChildElement(FRAME); - while (parentFrameXML) - { - parentXmlList.push_back(parentFrameXML); - parentFrameXML = parentFrameXML->NextSiblingElement(FRAME); - } - - parentFrameXML = NULL; - - length = parentXmlList.size(); - } - - - int totalDuration = 0; - - std::string name = movBoneXml->Attribute(A_NAME); - - movBoneData->name = name; - - tinyxml2::XMLElement *frameXML = movBoneXml->FirstChildElement(FRAME); - - while( frameXML ) - { - if(parentXml) - { - /* - * in this loop we get the corresponding parent frame xml - */ - while(i < length && (parentFrameXML ? (totalDuration < parentTotalDuration || totalDuration >= parentTotalDuration + currentDuration) : true)) - { - parentFrameXML = parentXmlList[i]; - parentTotalDuration += currentDuration; - parentFrameXML->QueryIntAttribute(A_DURATION, ¤tDuration); - i++; - - } - } - - FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData); - movBoneData->addFrameData(frameData); - frameData->release(); - - frameData->frameID = totalDuration; - totalDuration += frameData->duration; - movBoneData->duration = totalDuration; - - frameXML = frameXML->NextSiblingElement(FRAME); - } - - - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } - - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } - - - // - FrameData *frameData = new FrameData(); - frameData->copy((FrameData *)movBoneData->frameList.getLastObject()); - frameData->frameID = movBoneData->duration; - movBoneData->addFrameData(frameData); - frameData->release(); - - return movBoneData; -} - -FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData) -{ - float x, y, scale_x, scale_y, skew_x, skew_y = 0; - int duration, displayIndex, zOrder, tweenEasing, blendType = 0; - - FrameData *frameData = new FrameData(); - - if(frameXML->Attribute(A_MOVEMENT) != NULL) - { - frameData->strMovement = frameXML->Attribute(A_MOVEMENT); - } - if(frameXML->Attribute(A_EVENT) != NULL) - { - frameData->strEvent = frameXML->Attribute(A_EVENT); - } - if(frameXML->Attribute(A_SOUND) != NULL) - { - frameData->strSound = frameXML->Attribute(A_SOUND); - } - if(frameXML->Attribute(A_SOUND_EFFECT) != NULL) - { - frameData->strSoundEffect = frameXML->Attribute(A_SOUND_EFFECT); - } - - - - if (s_FlashToolVersion >= VERSION_2_0) - { - if(frameXML->QueryFloatAttribute(A_COCOS2DX_X, &x) == tinyxml2::XML_SUCCESS) - { - frameData->x = x; - frameData->x *= s_PositionReadScale; - } - if(frameXML->QueryFloatAttribute(A_COCOS2DX_Y, &y) == tinyxml2::XML_SUCCESS) - { - frameData->y = -y; - frameData->y *= s_PositionReadScale; - } - } - else - { - if(frameXML->QueryFloatAttribute(A_X, &x) == tinyxml2::XML_SUCCESS) - { - frameData->x = x; - frameData->x *= s_PositionReadScale; - } - if(frameXML->QueryFloatAttribute(A_Y, &y) == tinyxml2::XML_SUCCESS) - { - frameData->y = -y; - frameData->y *= s_PositionReadScale; - } - } - - if( frameXML->QueryFloatAttribute(A_SCALE_X, &scale_x) == tinyxml2::XML_SUCCESS ) - { - frameData->scaleX = scale_x; - } - if( frameXML->QueryFloatAttribute(A_SCALE_Y, &scale_y) == tinyxml2::XML_SUCCESS ) - { - frameData->scaleY = scale_y; - } - if( frameXML->QueryFloatAttribute(A_SKEW_X, &skew_x) == tinyxml2::XML_SUCCESS ) - { - frameData->skewX = CC_DEGREES_TO_RADIANS(skew_x); - } - if( frameXML->QueryFloatAttribute(A_SKEW_Y, &skew_y) == tinyxml2::XML_SUCCESS ) - { - frameData->skewY = CC_DEGREES_TO_RADIANS(-skew_y); - } - if( frameXML->QueryIntAttribute(A_DURATION, &duration) == tinyxml2::XML_SUCCESS ) - { - frameData->duration = duration; - } - if( frameXML->QueryIntAttribute(A_DISPLAY_INDEX, &displayIndex) == tinyxml2::XML_SUCCESS ) - { - frameData->displayIndex = displayIndex; - } - if( frameXML->QueryIntAttribute(A_Z, &zOrder) == tinyxml2::XML_SUCCESS ) - { - frameData->zOrder = zOrder; - } - if ( frameXML->QueryIntAttribute(A_BLEND_TYPE, &blendType) == tinyxml2::XML_SUCCESS ) - { - frameData->blendType = (BlendType)blendType; - } - - tinyxml2::XMLElement *colorTransformXML = frameXML->FirstChildElement(A_COLOR_TRANSFORM); - if (colorTransformXML) - { - int alpha, red, green, blue = 100; - int alphaOffset, redOffset, greenOffset, blueOffset = 0; - - colorTransformXML->QueryIntAttribute(A_ALPHA, &alpha); - colorTransformXML->QueryIntAttribute(A_RED, &red); - colorTransformXML->QueryIntAttribute(A_GREEN, &green); - colorTransformXML->QueryIntAttribute(A_BLUE, &blue) ; - - colorTransformXML->QueryIntAttribute(A_ALPHA_OFFSET, &alphaOffset); - colorTransformXML->QueryIntAttribute(A_RED_OFFSET, &redOffset); - colorTransformXML->QueryIntAttribute(A_GREEN_OFFSET, &greenOffset); - colorTransformXML->QueryIntAttribute(A_BLUE_OFFSET, &blueOffset) ; - - frameData->a = 2.55 * alphaOffset + alpha; - frameData->r = 2.55 * redOffset + red; - frameData->g = 2.55 * greenOffset + green; - frameData->b = 2.55 * blueOffset + blue; - - frameData->isUseColorInfo = true; - } - - - const char *_easing = frameXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) - { - std::string str = _easing; - if(str.compare(FL_NAN) != 0) - { - if( frameXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) - { - frameData->tweenEasing = (CCTweenType)tweenEasing; - } - } - else - { - frameData->tweenEasing = TWEEN_EASING_MAX; - } - } - - if(parentFrameXml) - { - /* - * recalculate frame data from parent frame data, use for translate matrix - */ - BaseData helpNode; - if (s_FlashToolVersion >= VERSION_2_0) - { - parentFrameXml->QueryFloatAttribute(A_COCOS2DX_X, &helpNode.x); - parentFrameXml->QueryFloatAttribute(A_COCOS2DX_Y, &helpNode.y); - } - else - { - parentFrameXml->QueryFloatAttribute(A_X, &helpNode.x); - parentFrameXml->QueryFloatAttribute(A_Y, &helpNode.y); - } - - - parentFrameXml->QueryFloatAttribute(A_SKEW_X, &helpNode.skewX); - parentFrameXml->QueryFloatAttribute(A_SKEW_Y, &helpNode.skewY); - - helpNode.y = -helpNode.y; - helpNode.skewX = CC_DEGREES_TO_RADIANS(helpNode.skewX); - helpNode.skewY = CC_DEGREES_TO_RADIANS(-helpNode.skewY); - - TransformHelp::transformFromParent(*frameData, helpNode); - } - return frameData; -} - -TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) -{ - TextureData *textureData = new TextureData(); - textureData->init(); - - if( textureXML->Attribute(A_NAME) != NULL) - { - textureData->name = textureXML->Attribute(A_NAME); - } - - float px, py, width, height = 0; - - if(s_FlashToolVersion >= VERSION_2_0) - { - textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_X, &px); - textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_Y, &py); - } - else - { - textureXML->QueryFloatAttribute(A_PIVOT_X, &px); - textureXML->QueryFloatAttribute(A_PIVOT_Y, &py); - } - - textureXML->QueryFloatAttribute(A_WIDTH, &width); - textureXML->QueryFloatAttribute(A_HEIGHT, &height); - - float anchorPointX = px / width; - float anchorPointY = (height - py) / height; - - textureData->pivotX = anchorPointX; - textureData->pivotY = anchorPointY; - - tinyxml2::XMLElement *contourXML = textureXML->FirstChildElement(CONTOUR); - - while (contourXML) - { - ContourData *contourData = decodeContour(contourXML); - textureData->addContourData(contourData); - contourData->release(); - - contourXML = contourXML->NextSiblingElement(CONTOUR); - } - - return textureData; -} - -ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML) -{ - ContourData *contourData = new ContourData(); - contourData->init(); - - tinyxml2::XMLElement *vertexDataXML = contourXML->FirstChildElement(CONTOUR_VERTEX); - - while (vertexDataXML) - { - ContourVertex2 *vertex = new ContourVertex2(0, 0); - vertex->release(); - - vertexDataXML->QueryFloatAttribute(A_X, &vertex->x); - vertexDataXML->QueryFloatAttribute(A_Y, &vertex->y); - - vertex->y = -vertex->y; - contourData->vertexList.addObject(vertex); - - vertexDataXML = vertexDataXML->NextSiblingElement(CONTOUR_VERTEX); - } - - return contourData; -} - - - -void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo) -{ - cs::JsonDictionary json; - json.initWithDescription(fileContent); - - // Decode armatures - int length = json.getArrayItemCount(ARMATURE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); - ArmatureData *armatureData = decodeArmature(*armatureDic); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); - armatureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - delete armatureDic; - } - - // Decode animations - length = json.getArrayItemCount(ANIMATION_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); - AnimationData *animationData = decodeAnimation(*animationDic); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); - animationData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - delete animationDic; - } - - // Decode textures - length = json.getArrayItemCount(TEXTURE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); - TextureData *textureData = decodeTexture(*textureDic); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); - textureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - delete textureDic; - } - - // Auto load sprite file - bool autoLoad = dataInfo == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; - if (autoLoad) - { - length = json.getArrayItemCount(CONFIG_FILE_PATH); - for (int i = 0; i < length; i++) - { - const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i); - if (path == NULL) - { - CCLOG("load CONFIG_FILE_PATH error."); - return; - } - - std::string filePath = path; - filePath = filePath.erase(filePath.find_last_of(".")); - - if (dataInfo != NULL) - { - dataInfo->configFileQueue.push(filePath); - } - else - { - std::string plistPath = filePath + ".plist"; - std::string pngPath = filePath + ".png"; - - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((s_BasefilePath + plistPath).c_str(), (s_BasefilePath + pngPath).c_str()); - } - } - } -} - -ArmatureData *DataReaderHelper::decodeArmature(cs::JsonDictionary &json) -{ - ArmatureData *armatureData = new ArmatureData(); - armatureData->init(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - armatureData->name = name; - } - - s_CocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); - - int length = json.getArrayItemCount(BONE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); - BoneData *boneData = decodeBone(*dic); - armatureData->addBoneData(boneData); - boneData->release(); - - delete dic; - } - - return armatureData; -} - -BoneData *DataReaderHelper::decodeBone(cs::JsonDictionary &json) -{ - BoneData *boneData = new BoneData(); - boneData->init(); - - decodeNode(boneData, json); - - const char *str = json.getItemStringValue(A_NAME); - if(str != NULL) - { - boneData->name = str; - } - - str = json.getItemStringValue(A_PARENT); - if(str != NULL) - { - boneData->parentName = str; - } - - int length = json.getArrayItemCount(DISPLAY_DATA); - - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); - DisplayData *displayData = decodeBoneDisplay(*dic); - boneData->addDisplayData(displayData); - displayData->release(); - - delete dic; - } - - return boneData; -} - -DisplayData *DataReaderHelper::decodeBoneDisplay(cs::JsonDictionary &json) -{ - DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); - - DisplayData *displayData = NULL; - - switch (displayType) - { - case CS_DISPLAY_SPRITE: - { - displayData = new SpriteDisplayData(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - ((SpriteDisplayData *)displayData)->displayName = name; - } - - cs::JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); - if (dic != NULL) - { - SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; - sdd->skinData.x = dic->getItemFloatValue(A_X, 0) * s_PositionReadScale; - sdd->skinData.y = dic->getItemFloatValue(A_Y, 0) * s_PositionReadScale; - sdd->skinData.scaleX = dic->getItemFloatValue(A_SCALE_X, 1); - sdd->skinData.scaleY = dic->getItemFloatValue(A_SCALE_Y, 1); - sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); - sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); - delete dic; - } - } - - break; - case CS_DISPLAY_ARMATURE: - { - displayData = new ArmatureDisplayData(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - ((ArmatureDisplayData *)displayData)->displayName = name; - } - } - break; - case CS_DISPLAY_PARTICLE: - { - displayData = new ParticleDisplayData(); - - const char *plist = json.getItemStringValue(A_PLIST); - if(plist != NULL) - { - ((ParticleDisplayData *)displayData)->plist = s_BasefilePath + plist; - } - } - break; - default: - displayData = new SpriteDisplayData(); - - break; - } - - - displayData->displayType = displayType; - - return displayData; -} - -AnimationData *DataReaderHelper::decodeAnimation(cs::JsonDictionary &json) -{ - AnimationData *aniData = new AnimationData(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - aniData->name = name; - } - - int length = json.getArrayItemCount(MOVEMENT_DATA); - - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); - MovementData *movementData = decodeMovement(*dic); - aniData->addMovement(movementData); - movementData->release(); - - delete dic; - } - - return aniData; -} - -MovementData *DataReaderHelper::decodeMovement(cs::JsonDictionary &json) -{ - MovementData *movementData = new MovementData(); - - movementData->loop = json.getItemBoolvalue(A_LOOP, true); - movementData->durationTween = json.getItemIntValue(A_DURATION_TWEEN, 0); - movementData->durationTo = json.getItemIntValue(A_DURATION_TO, 0); - movementData->duration = json.getItemIntValue(A_DURATION, 0); - movementData->scale = json.getItemFloatValue(A_MOVEMENT_SCALE, 1); - movementData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - movementData->name = name; - } - - int length = json.getArrayItemCount(MOVEMENT_BONE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); - MovementBoneData *movementBoneData = decodeMovementBone(*dic); - movementData->addMovementBoneData(movementBoneData); - movementBoneData->release(); - - delete dic; - } - - return movementData; -} - -MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) -{ - MovementBoneData *movementBoneData = new MovementBoneData(); - movementBoneData->init(); - - movementBoneData->delay = json.getItemFloatValue(A_MOVEMENT_DELAY, 0); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - movementBoneData->name = name; - } - - int length = json.getArrayItemCount(FRAME_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); - FrameData *frameData = decodeFrame(*dic); - - movementBoneData->addFrameData(frameData); - frameData->release(); - - if (s_CocoStudioVersion < VERSION_COMBINED) - { - frameData->frameID = movementBoneData->duration; - movementBoneData->duration += frameData->duration; - } - - delete dic; - } - - - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) - { - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movementBoneData->frameList.data->arr; - for (int i = movementBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } - - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } - } - - if (s_CocoStudioVersion < VERSION_COMBINED) - { - if (movementBoneData->frameList.count() > 0) - { - FrameData *frameData = new FrameData(); - frameData->copy((FrameData *)movementBoneData->frameList.getLastObject()); - movementBoneData->addFrameData(frameData); - frameData->release(); - - frameData->frameID = movementBoneData->duration; - } - } - - return movementBoneData; -} - -FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json) -{ - FrameData *frameData = new FrameData(); - - decodeNode(frameData, json); - - frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); - frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); - frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); - frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); - - const char *event = json.getItemStringValue(A_EVENT); - if (event != NULL) - { - frameData->strEvent = event; - } - - if (s_CocoStudioVersion < VERSION_COMBINED) - { - frameData->duration = json.getItemIntValue(A_DURATION, 1); - } - else - { - frameData->frameID = json.getItemIntValue(A_FRAME_INDEX, 0); - } - - return frameData; -} - -TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) -{ - TextureData *textureData = new TextureData(); - textureData->init(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - textureData->name = name; - } - - textureData->width = json.getItemFloatValue(A_WIDTH, 0); - textureData->height = json.getItemFloatValue(A_HEIGHT, 0); - textureData->pivotX = json.getItemFloatValue(A_PIVOT_X, 0); - textureData->pivotY = json.getItemFloatValue(A_PIVOT_Y, 0); - - int length = json.getArrayItemCount(CONTOUR_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i); - ContourData *contourData = decodeContour(*dic); - textureData->contourDataList.addObject(contourData); - contourData->release(); - - delete dic; - } - - return textureData; -} - -ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) -{ - ContourData *contourData = new ContourData(); - contourData->init(); - - int length = json.getArrayItemCount(VERTEX_POINT); - for (int i = length - 1; i >= 0; i--) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i); - - ContourVertex2 *vertex = new ContourVertex2(0, 0); - - vertex->x = dic->getItemFloatValue(A_X, 0); - vertex->y = dic->getItemFloatValue(A_Y, 0); - - contourData->vertexList.addObject(vertex); - vertex->release(); - - delete dic; - } - - return contourData; -} - -void DataReaderHelper::decodeNode(BaseData *node, cs::JsonDictionary &json) -{ - node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; - node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; - node->zOrder = json.getItemIntValue(A_Z, 0); - - node->skewX = json.getItemFloatValue(A_SKEW_X, 0); - node->skewY = json.getItemFloatValue(A_SKEW_Y, 0); - node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); - node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - - cs::JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); - - if (colorDic) - { - node->a = colorDic->getItemIntValue(A_ALPHA, 255); - node->r = colorDic->getItemIntValue(A_RED, 255); - node->g = colorDic->getItemIntValue(A_GREEN, 255); - node->b = colorDic->getItemIntValue(A_BLUE, 255); - - node->isUseColorInfo = true; - - delete colorDic; - } - -} - -NS_CC_EXT_ARMATURE_END diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 0b662d9c15..b571dfb808 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -15,7 +15,7 @@ static int s_nActionIdx = -1; Layer *CreateLayer(int index) { - Layer *pLayer = NULL; + Layer *pLayer = nullptr; switch(index) { case TEST_ASYNCHRONOUS_LOADING: @@ -167,7 +167,7 @@ void ArmatureTestLayer::onEnter() restartItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(ArmatureTestLayer::restartCallback, this) ); nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(ArmatureTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); + Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); menu->setPosition(Point::ZERO); backItem->setPosition(Point(VisibleRect::center().x - restartItem->getContentSize().width * 2, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); @@ -183,7 +183,7 @@ void ArmatureTestLayer::onExit() { removeAllChildren(); - backItem = restartItem = nextItem = NULL; + backItem = restartItem = nextItem = nullptr; Layer::onExit(); } @@ -319,7 +319,7 @@ std::string TestDirectLoading::title() void TestCSWithSkeleton::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; armature = Armature::create("Cowboy"); armature->getAnimation()->playByIndex(0); armature->setScale(0.2f); @@ -340,7 +340,7 @@ void TestDragonBones20::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; armature = Armature::create("Dragon"); armature->getAnimation()->playByIndex(1); armature->getAnimation()->setSpeedScale(0.4f); @@ -372,7 +372,7 @@ void TestPerformance::onEnter() MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); increase->setColor(Color3B(0,200,20)); - Menu *menu = Menu::create(decrease, increase, NULL); + Menu *menu = Menu::create(decrease, increase, nullptr); menu->alignItemsHorizontally(); menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); addChild(menu, 10000); @@ -413,7 +413,7 @@ void TestPerformance::addArmature(int number) { armatureCount++; - Armature *armature = NULL; + Armature *armature = nullptr; armature = new Armature(); armature->init("Knight_f/Knight"); armature->getAnimation()->playByIndex(0); @@ -467,7 +467,7 @@ void TestChangeZorder::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; currentTag = -1; armature = Armature::create("Knight_f/Knight"); @@ -524,7 +524,7 @@ void TestAnimationEvent::onEnter() /* * Set armature's movement event callback function - * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + * To disconnect this event, just setMovementEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(TestAnimationEvent::animationEvent)); addChild(armature); @@ -543,14 +543,14 @@ void TestAnimationEvent::animationEvent(Armature *armature, MovementEventType mo { ActionInterval *actionToRight = MoveTo::create(2, Point(VisibleRect::right().x - 50, VisibleRect::right().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), NULL)); + armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), nullptr)); armature->getAnimation()->play("Walk"); } else if (id.compare("FireMax") == 0) { ActionInterval *actionToLeft = MoveTo::create(2, Point(VisibleRect::left().x + 50, VisibleRect::left().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), NULL)); + armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), nullptr)); armature->getAnimation()->play("Walk"); } } @@ -580,7 +580,7 @@ void TestFrameEvent::onEnter() /* * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestFrameEvent::onFrameEvent)); @@ -608,8 +608,8 @@ void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIn } void TestFrameEvent::checkAction(float dt) { - if ( this->numberOfRunningActions() == 0 && this->getGrid() != NULL) - this->setGrid(NULL); + if ( this->numberOfRunningActions() == 0 && this->getGrid() != nullptr) + this->setGrid(nullptr); } @@ -750,7 +750,7 @@ void TestColliderDetector::onEnter() /* * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestColliderDetector::onFrameEvent)); @@ -1011,7 +1011,7 @@ void TestColliderDetector::initWorld() ColliderFilter filter = ColliderFilter(eEnemyTag); armature2->setColliderFilter(&filter); - cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); + cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, nullptr, nullptr, endHit, nullptr); } #endif @@ -1106,7 +1106,7 @@ void TestArmatureNesting::onTouchesEnded(const std::vector& touches, Eve ++weaponIndex; weaponIndex = weaponIndex % 4; - if(armature != NULL) + if(armature != nullptr) { armature->getBone("armInside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); armature->getBone("armOutside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); @@ -1125,18 +1125,18 @@ Hero *Hero::create(const char *name) return hero; } CC_SAFE_DELETE(hero); - return NULL; + return nullptr; } Hero::Hero() - : m_pMount(NULL) - , m_pLayer(NULL) + : m_pMount(nullptr) + , m_pLayer(nullptr) { } void Hero::changeMount(Armature *armature) { - if (armature == NULL) + if (armature == nullptr) { retain(); @@ -1203,7 +1203,7 @@ void TestArmatureNesting2::onEnter() LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::ChangeMountCallback, this)); - Menu* pMenu =Menu::create(pMenuItem, NULL); + Menu* pMenu =Menu::create(pMenuItem, nullptr); pMenu->setPosition( Point() ); pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); @@ -1241,7 +1241,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev { Point point = touches[0]->getLocation(); - Armature *armature = hero->getMount() == NULL ? hero : hero->getMount(); + Armature *armature = hero->getMount() == nullptr ? hero : hero->getMount(); //Set armature direction if (point.x < armature->getPositionX()) @@ -1255,7 +1255,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev ActionInterval *move = CCMoveTo::create(2, point); armature->stopAllActions(); - armature->runAction(Sequence::create(move, NULL)); + armature->runAction(Sequence::create(move, nullptr)); } void TestArmatureNesting2::ChangeMountCallback(Object* pSender) @@ -1264,7 +1264,7 @@ void TestArmatureNesting2::ChangeMountCallback(Object* pSender) if (hero->getMount()) { - hero->changeMount(NULL); + hero->changeMount(nullptr); } else { From 963d7f3bd00a00b8b7d57b72fef1e4b73d935c9e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 5 Nov 2013 15:33:34 +0800 Subject: [PATCH 065/197] Changes the touch id declaration from int to long. --- cocos/2d/platform/linux/CCEGLView.cpp | 6 +++--- cocos/2d/platform/win32/CCEGLView.cpp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 33b8796959..a136ba54b3 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -186,7 +186,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -195,7 +195,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -231,7 +231,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index 6b19ec5bb5..3a18b81917 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -303,7 +303,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -312,7 +312,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -348,7 +348,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } From 8c62bf813fc0e2433ee9483ebc14d806b517fe20 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 5 Nov 2013 15:54:33 +0800 Subject: [PATCH 066/197] issue #2771: enhance API and add Slice demo --- cocos/physics/CCPhysicsBody.cpp | 26 +++- cocos/physics/CCPhysicsBody.h | 10 +- cocos/physics/CCPhysicsContact.cpp | 9 +- cocos/physics/CCPhysicsContact.h | 1 + cocos/physics/CCPhysicsShape.cpp | 18 +++ cocos/physics/CCPhysicsShape.h | 2 + cocos/physics/CCPhysicsWorld.cpp | 22 ++- cocos/physics/CCPhysicsWorld.h | 14 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 137 ++++++++++++++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 27 +++- 10 files changed, 233 insertions(+), 33 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 152a4fc454..8a177e6252 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -157,12 +157,12 @@ PhysicsBody* PhysicsBody::create(float mass, float moment) } -PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeCircle::create(radius, material)); + body->addShape(PhysicsShapeCircle::create(radius, material, offset)); body->autorelease(); return body; } @@ -171,12 +171,12 @@ PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeBox::create(size, material)); + body->addShape(PhysicsShapeBox::create(size, material, offset)); body->autorelease(); return body; } @@ -185,12 +185,12 @@ PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(points, count, material)); + body->addShape(PhysicsShapePolygon::create(points, count, material, offset)); body->autorelease(); return body; } @@ -214,12 +214,12 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial ma return nullptr; } -PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeBox::create(size, material, border)); + body->addShape(PhysicsShapeEdgeBox::create(size, material, border, offset)); body->_dynamic = false; body->autorelease(); return body; @@ -536,6 +536,16 @@ Point PhysicsBody::getVelocity() return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); } +Point PhysicsBody::getVelocityAtLocalPoint(Point point) +{ + return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->body, PhysicsHelper::point2cpv(point))); +} + +Point PhysicsBody::getVelocityAtWorldPoint(Point point) +{ + return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->body, PhysicsHelper::point2cpv(point))); +} + void PhysicsBody::setAngularVelocity(float velocity) { cpBodySetAngVel(_info->body, PhysicsHelper::float2cpfloat(velocity)); diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index a4bad406b8..60dd314966 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -59,16 +59,16 @@ public: /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); /** * @brief Create a body contains a EdgeSegment shape. @@ -77,7 +77,7 @@ public: /** * @brief Create a body contains a EdgeBox shape. */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, Point offset = Point::ZERO); /** * @brief Create a body contains a EdgePolygon shape. */ @@ -113,6 +113,8 @@ public: virtual void setVelocity(Point velocity); virtual Point getVelocity(); virtual void setAngularVelocity(float velocity); + virtual Point getVelocityAtLocalPoint(Point point); + virtual Point getVelocityAtWorldPoint(Point point); virtual float getAngularVelocity(); virtual void setVelocityLimit(float limit); virtual float getVelocityLimit(); diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index b5a7c7e0a3..e3a4907a97 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -120,6 +120,11 @@ PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* c { } +PhysicsContactPreSolve::~PhysicsContactPreSolve() +{ + CC_SAFE_DELETE(_preContactData); +} + float PhysicsContactPreSolve::getElasticity() const { return static_cast(_contactInfo)->e; @@ -150,9 +155,9 @@ void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); } -PhysicsContactPreSolve::~PhysicsContactPreSolve() +void PhysicsContactPreSolve::ignore() { - CC_SAFE_DELETE(_preContactData); + cpArbiterIgnore(static_cast(_contactInfo)); } // PhysicsContactPostSolve implementation diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 32127da7a5..ee279ef474 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -139,6 +139,7 @@ public: void setElasticity(float elasticity); void setFriction(float friction); void setSurfaceVelocity(Point surfaceVelocity); + void ignore(); private: PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo); diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index c2334ec719..fea8365c08 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -594,6 +594,11 @@ float PhysicsShapePolygon::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } +Point PhysicsShapePolygon::getPoint(int i) const +{ + return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->shapes.front(), i)); +} + Point* PhysicsShapePolygon::getPoints(Point* points) const { cpShape* shape = _info->shapes.front(); @@ -792,6 +797,19 @@ void PhysicsShape::setGroup(int group) } } +bool PhysicsShape::containsPoint(Point point) const +{ + for (auto shape : _info->shapes) + { + if (cpShapePointQuery(shape, PhysicsHelper::point2cpv(point))) + { + return true; + } + } + + return false; +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 31497d14a2..4ddcfe8a18 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -98,6 +98,7 @@ public: virtual float calculateDefaultArea() { return 0; } virtual Point getOffset() { return Point::ZERO; } virtual Point getCenter() { return getOffset(); } + bool containsPoint(Point point) const; static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); static Point getPolyonCenter(Point* points, int count); @@ -203,6 +204,7 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; + Point getPoint(int i) const; Point* getPoints(Point* points) const; int getPointsCount() const; Point getCenter() override; diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 913713277b..cafdb79be8 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -146,12 +146,17 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect auto it = PhysicsShapeInfo::map.find(shape); CC_ASSERT(it != PhysicsShapeInfo::map.end()); - PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->shape, - Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), - Point(n.x, n.y), - (float)t, - info->data); + PhysicsRayCastCallback::Info callbackInfo = + { + it->second->shape, + info->p1, + info->p2, + Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), + Point(n.x, n.y), + (float)t, + }; + + PhysicsWorldCallback::continues = info->callback->report(*info->world, callbackInfo, info->data); } void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) @@ -747,6 +752,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { if (!contact.getNotify()) { + cpArbiterIgnore(static_cast(contact._contactInfo)); return true; } @@ -811,6 +817,8 @@ void PhysicsWorld::setGravity(Point gravity) void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) { + CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + if (callback.report != nullptr) { RayCastCallbackInfo info = { this, &callback, point1, point2, data }; @@ -829,6 +837,8 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) { + CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + if (callback.report != nullptr) { RectQueryCallbackInfo info = {this, &callback, data}; diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 2d4e7def57..360844db3f 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -50,6 +50,18 @@ class DrawNode; class PhysicsWorld; class PhysicsRayCastCallback { +public: + typedef struct Info + { + PhysicsShape* shape; + Point start; + Point end; + Point contact; + Point normal; + float fraction; + void* data; + }Info; + public: PhysicsRayCastCallback() : report(nullptr) @@ -65,7 +77,7 @@ public: * @param normal the normal vector at the point of intersection * @return true to continue, false to terminate */ - std::function report; + std::function report; }; class PhysicsRectQueryCallback diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 866cec82fd..99ce9d0c90 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -14,6 +14,7 @@ namespace CL(PhysicsDemoActions), CL(PhysicsDemoPump), CL(PhysicsDemoOneWayPlatform), + CL(PhysicsDemoSlice), }; static int sceneIdx=-1; @@ -601,9 +602,9 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data) { - *((Point*)data) = point; + *((Point*)data) = info.contact; return false; } @@ -619,12 +620,12 @@ private: PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() : _friction(1.0f) { - report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool + report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool { - if (_friction > fraction) + if (_friction > info.fraction) { - *((Point*)data) = point; - _friction = fraction; + *((Point*)data) = info.contact; + _friction = info.fraction; } return true; @@ -649,11 +650,11 @@ public: PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() : num(0) { - report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool + report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool { if (num < MAX_MULTI_RAYCAST_NUM) { - points[num++] = point; + points[num++] = info.contact; } return true; @@ -675,7 +676,7 @@ void PhysicsDemoRayCast::update(float delta) { PhysicsRayCastCallback callback; Point point3 = point2; - callback.report = anyRay; + callback.report = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); _node->drawSegment(point1, point3, 1, STATIC_COLOR); @@ -941,8 +942,9 @@ void PhysicsDemoPump::onEnter() // pump auto pump = Node::create(); - pump->setPosition(PhysicsShape::getPolyonCenter(vec, 4)); - auto pumpB = PhysicsBody::createPolygon(PhysicsShape::recenterPoints(vec, 4), 4); + auto center = PhysicsShape::getPolyonCenter(vec, 4); + pump->setPosition(center); + auto pumpB = PhysicsBody::createPolygon(vec, 4, PHYSICSBODY_MATERIAL_DEFAULT, -center); pump->setPhysicsBody(pumpB); this->addChild(pump); pumpB->setCategoryBitmask(0x02); @@ -1062,4 +1064,117 @@ bool PhysicsDemoOneWayPlatform::onContactBegin(EventCustom* event, const Physics std::string PhysicsDemoOneWayPlatform::title() { return "One Way Platform"; +} + +void PhysicsDemoSlice::onEnter() +{ + PhysicsDemo::onEnter(); + + _sliceTag = 1; + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = [](Touch* touch, Event* event)->bool{ return true; }; + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoSlice::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto ground = Node::create(); + ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(ground); + + auto box = Node::create(); + Point points[4] = {Point(-100, -100), Point(-100, 100), Point(100, 100), Point(100, -100)}; + box->setPhysicsBody(PhysicsBody::createPolygon(points, 4)); + box->setPosition(VisibleRect::center()); + box->getPhysicsBody()->setTag(_sliceTag); + addChild(box); +} + +bool PhysicsDemoSlice::slice(PhysicsWorld &world, PhysicsRayCastCallback::Info &info, void *data) +{ + if (info.shape->getBody()->getTag() != _sliceTag) + { + return true; + } + + if (!info.shape->containsPoint(info.start) && !info.shape->containsPoint(info.end)) + { + Point normal = info.end - info.start; + normal = normal.getPerp().normalize(); + float dist = info.start.dot(normal); + dist = dist; + + clipPoly(dynamic_cast(info.shape), normal, dist); + clipPoly(dynamic_cast(info.shape), -normal, -dist); + + info.shape->getBody()->removeFromWorld(); + } + + return true; +} + +void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float distance) +{ + PhysicsBody* body = shape->getBody(); + int count = shape->getPointsCount(); + int pointsCount = 0; + Point* points = new Point[count + 1]; + + for (int i=0, j=count-1; ilocal2World(shape->getPoint(j)); + float aDist = a.dot(normal) - distance; + + if (aDist < 0.0f) + { + points[pointsCount] = a; + ++pointsCount; + } + + Point b = body->local2World(shape->getPoint(i)); + float bDist = b.dot(normal) - distance; + + if (aDist*bDist < 0.0f) + { + float t = abs(aDist)/(abs(aDist) + abs(bDist)); + points[pointsCount] = a.lerp(b, t); + ++pointsCount; + } + } + + Point center = PhysicsShape::getPolyonCenter(points, pointsCount); + Node* node = Node::create(); + PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center); + node->setPosition(center); + node->setPhysicsBody(polyon); + polyon->setVelocity(body->getVelocityAtWorldPoint(center)); + polyon->setAngularVelocity(body->getAngularVelocity()); + polyon->setTag(_sliceTag); + addChild(node); +} + +void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) +{ + PhysicsRayCastCallback callback; + callback.report = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); + _scene->getPhysicsWorld()->rayCast(callback, touch->getStartLocation(), touch->getLocation(), nullptr); +} + +std::string PhysicsDemoSlice::title() +{ + return "Slice"; +} + +std::string PhysicsDemoSlice::subtitle() +{ + return "click and drag to slice up the block"; +} + +void PhysicsDemoWater::onEnter() +{ + +} + +std::string PhysicsDemoWater::title() +{ + return "Water"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 4de964f2d3..425dbc56f9 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -96,7 +96,7 @@ public: void changeModeCallback(Object* sender); - static bool anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data); + bool anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); private: float _angle; @@ -143,4 +143,29 @@ public: bool onContactBegin(EventCustom* event, const PhysicsContact& contact); }; +class PhysicsDemoSlice : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + std::string subtitle() override; + + bool slice(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); + void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); + + bool onTouchBegan(Touch *touch, Event *event); + void onTouchMoved(Touch *touch, Event *event); + void onTouchEnded(Touch *touch, Event *event); + +private: + int _sliceTag; +}; + +class PhysicsDemoWater : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; +}; + #endif From f2f7e61b073b99369e1ac06feada5402c4dc239e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 5 Nov 2013 16:04:06 +0800 Subject: [PATCH 067/197] Update CHNAGELOG[ci skip] --- CHANGELOG | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 0d0efb8f2d..797c52821d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Added Mouse Support For Desktop Platforms. [FIX] EventListeners can't be removed sometimes. [FIX] When parsing XML using TinyXML, the data size has to be specified. + [NEW] Arm64 support. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again @@ -25,6 +26,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Removed unused CCLOG() from GL initialization [iOS] [FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox. +[Linux] + [NEW] Used CMake to build linux projects. [Desktop] [FIX] Trigger onKeyReleased only after the key has been released. [Javascript binding] From 8c75cd0dfa490d0e29ad70dd14a963572f63ae2c Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 5 Nov 2013 08:07:15 +0000 Subject: [PATCH 068/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 56a3820b26..4ea4a8fa89 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 56a3820b2660d69ebd958838f515cd75f08eaf18 +Subproject commit 4ea4a8fa89fd3b9b5ec3e8b6f69841dfe0e3b75c From 61d8f9673cc18fcb8f3ae95672e54d59aa4c14ed Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 5 Nov 2013 17:34:25 +0800 Subject: [PATCH 069/197] issue #2868:Move armature related lua binding from namespace 'cc' to namespace 'ccd' --- .../cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/scripting/lua/bindings/Android.mk | 1 + cocos/scripting/lua/bindings/Makefile | 1 + tools/tolua/cocos2dx_studio.ini | 6 +++--- tools/tolua/genbindings.sh | 7 +++++++ 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b99b211450..91f22feb89 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -ab3cbe9f9358e0c472a7775bb7087507f50892e9 \ No newline at end of file +db96f13af3f35778c8d9c2b6bec189fcdaf7216e \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/Android.mk b/cocos/scripting/lua/bindings/Android.mk index b39ee5f6a5..f198157af9 100644 --- a/cocos/scripting/lua/bindings/Android.mk +++ b/cocos/scripting/lua/bindings/Android.mk @@ -17,6 +17,7 @@ LOCAL_SRC_FILES := CCLuaBridge.cpp \ LuaBasicConversions.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ + ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ lua_cocos2dx_manual.cpp \ lua_cocos2dx_extension_manual.cpp \ lua_cocos2dx_deprecated.cpp \ diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile index c797ce3b9e..546ad977b4 100644 --- a/cocos/scripting/lua/bindings/Makefile +++ b/cocos/scripting/lua/bindings/Makefile @@ -49,6 +49,7 @@ SOURCES = ../../../../external/lua/lua/lapi.c \ tolua_fix.c \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ + ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ CCLuaBridge.cpp \ CCLuaEngine.cpp \ CCLuaStack.cpp \ diff --git a/tools/tolua/cocos2dx_studio.ini b/tools/tolua/cocos2dx_studio.ini index c30134f97d..8959fd0005 100644 --- a/tools/tolua/cocos2dx_studio.ini +++ b/tools/tolua/cocos2dx_studio.ini @@ -23,11 +23,11 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h %(cocosdir)s/cocos/gui/CocosGUI.h +headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes =Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ UIWidget GUIRenderer Layout RectClippingNode UIRootWidget UIButton UICheckBox UIImageView UILabel UICCLabelAtlas UILabelAtlas UILoadingBar UIScrollView UISlider UICCTextField UITextField UIListView UIDragPanel UILabelBMFont UIPageView UIHelper UILayer +classes = Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -38,7 +38,7 @@ classes =Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ UIWid skip = .*Delegate::[*], .*Loader.*::[*], - *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener addEventListener], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], Skin::[(s|g)etSkinData], diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index e6997542bf..9dc005d4a0 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -78,5 +78,12 @@ echo -e "$_CONTENTS" > "$_CONF_INI_FILE" echo --- # Generate bindings for cocos2dx +echo "Generating bindings for cocos2dx..." +set -x +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto + +echo "Generating bindings for cocos2dx_extension..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto + echo "Generating bindings for cocos2dx_studio..." LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto From 66256e9ad7f726739e423d27b97d6388172fa92c Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 5 Nov 2013 17:48:29 +0800 Subject: [PATCH 070/197] issue #2868:Move armature related lua binding from namespace 'cc' to namespace 'ccs' --- cocos/scripting/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt index bee2a84fe8..478ae9a039 100644 --- a/cocos/scripting/CMakeLists.txt +++ b/cocos/scripting/CMakeLists.txt @@ -1,6 +1,7 @@ set(LUABINDING_SRC auto-generated/lua-bindings/lua_cocos2dx_auto.cpp auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp + auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp lua/bindings/tolua_fix.c lua/bindings/CCLuaBridge.cpp lua/bindings/CCLuaEngine.cpp From 47e0d343ff8968d2971c4e3a8a5bacbfd12216b5 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 5 Nov 2013 11:30:43 +0000 Subject: [PATCH 071/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 4ea4a8fa89..c2b42be577 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 4ea4a8fa89fd3b9b5ec3e8b6f69841dfe0e3b75c +Subproject commit c2b42be577425e4dd6c2501e8f0cd1520ca3d059 From 16c23d0ad3ca414b206232e0082222b40f65f97d Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 19:53:38 +0800 Subject: [PATCH 072/197] remove CC_PROPERTY and CC_SYNTHESIZE. --- .../editor-support/cocostudio/CCArmature.cpp | 16 ++--- cocos/editor-support/cocostudio/CCArmature.h | 62 ++++++++++------ .../cocostudio/CCArmatureAnimation.cpp | 12 ++-- .../cocostudio/CCArmatureAnimation.h | 18 +++-- .../editor-support/cocostudio/CCBatchNode.cpp | 6 +- cocos/editor-support/cocostudio/CCBatchNode.h | 16 ++--- cocos/editor-support/cocostudio/CCBone.cpp | 8 +-- cocos/editor-support/cocostudio/CCBone.h | 64 +++++++++++------ .../cocostudio/CCColliderDetector.cpp | 4 +- .../cocostudio/CCColliderDetector.h | 72 ++++++++++++++----- .../cocostudio/CCDecorativeDisplay.h | 41 +++++++++-- .../cocostudio/CCDisplayManager.cpp | 22 +++--- .../cocostudio/CCDisplayManager.h | 26 +++---- .../editor-support/cocostudio/CCProcessBase.h | 35 ++++++--- cocos/editor-support/cocostudio/CCSkin.cpp | 2 +- cocos/editor-support/cocostudio/CCSkin.h | 20 ++++-- cocos/editor-support/cocostudio/CCTween.cpp | 2 +- cocos/editor-support/cocostudio/CCTween.h | 5 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 8 +-- .../CocoStudioArmatureTest/ArmatureScene.h | 2 +- 20 files changed, 297 insertions(+), 144 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index be5c9d0c33..7cd7ad9295 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -335,7 +335,7 @@ void Armature::changeBoneParent(Bone *bone, const char *parentName) } } -Dictionary *Armature::getBoneDic() +const Dictionary *Armature::getBoneDic() const { return _boneDic; } @@ -437,12 +437,12 @@ void Armature::setAnimation(ArmatureAnimation *animation) _animation = animation; } -ArmatureAnimation *Armature::getAnimation() +ArmatureAnimation *Armature::getAnimation() const { return _animation; } -bool Armature::getArmatureTransformDirty() +bool Armature::getArmatureTransformDirty() const { return _armatureTransformDirty; } @@ -673,7 +673,7 @@ Rect Armature::getBoundingBox() const return RectApplyAffineTransform(boundingBox, getNodeToParentTransform()); } -Bone *Armature::getBoneAtPoint(float x, float y) +Bone *Armature::getBoneAtPoint(float x, float y) const { int length = _children->count(); Bone *bs; @@ -689,7 +689,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) return nullptr; } -TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) +TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) const { int key = texture->getName(); @@ -723,7 +723,7 @@ void Armature::setParentBone(Bone *parentBone) } } -Bone *Armature::getParentBone() +Bone *Armature::getParentBone() const { return _parentBone; } @@ -739,7 +739,7 @@ void CCArmature::setColliderFilter(ColliderFilter *filter) } #if ENABLE_PHYSICS_BOX2D_DETECT -b2Body *Armature::getBody() +b2Body *Armature::getBody() const { return _body; } @@ -787,7 +787,7 @@ b2Fixture *Armature::getShapeList() } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT -cpBody *Armature::getBody() +cpBody *Armature::getBody() const { return _body; } diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 9f6fc3331b..6182072265 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -99,7 +99,7 @@ public: /** * Init the empty armature */ - virtual bool init(); + virtual bool init() override; /** * Init an armature with specified name @@ -140,14 +140,14 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - cocos2d::Dictionary *getBoneDic(); + const cocos2d::Dictionary *getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time */ - virtual cocos2d::Rect getBoundingBox() const; + virtual cocos2d::Rect getBoundingBox() const override; - Bone *getBoneAtPoint(float x, float y); + Bone *getBoneAtPoint(float x, float y) const; // overrides /** @@ -170,18 +170,43 @@ public: virtual void updateOffsetPoint(); virtual void setAnimation(ArmatureAnimation *animation); - virtual ArmatureAnimation *getAnimation(); + virtual ArmatureAnimation *getAnimation() const; - virtual bool getArmatureTransformDirty(); + virtual bool getArmatureTransformDirty() const; - virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture) const; virtual void setColliderFilter(ColliderFilter *filter); + + virtual void setArmatureData(ArmatureData *armatureData) { _armatureData = armatureData; } + virtual const ArmatureData *getArmatureData() const { return _armatureData; } + + virtual void setBatchNode(BatchNode *batchNode) { _batchNode = batchNode; } + virtual const BatchNode *getBatchNode() const { return _batchNode; } + + virtual void setName(const std::string &name) { _name = name; } + virtual const std::string &getName() const { return _name; } + + virtual void setTextureAtlas(cocos2d::TextureAtlas *atlas) { _atlas = atlas; } + virtual cocos2d::TextureAtlas *getTextureAtlas() const { return _atlas; } + + virtual void setParentBone(Bone *parentBone); + virtual Bone *getParentBone() const; + + virtual void setVersion(float version) { _version = version; } + virtual float getVersion() const { return _version; } + #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); + + virtual void setBody(b2Body *body); + virtual b2Body *getBody() const; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT virtual cpShape *getShapeList(); + + virtual void setBody(cpBody *body); + virtual cpBody *getBody() const; #endif protected: @@ -194,19 +219,14 @@ protected: //! Update blend function void updateBlendType(BlendType blendType); - CC_SYNTHESIZE(ArmatureData *, _armatureData, ArmatureData); - - CC_SYNTHESIZE(BatchNode *, _batchNode, BatchNode); - - CC_SYNTHESIZE(std::string, _name, Name); - - CC_SYNTHESIZE(cocos2d::TextureAtlas *, _atlas, TextureAtlas); - - CC_PROPERTY(Bone *, _parentBone, ParentBone); - - CC_SYNTHESIZE(float, _version, Version); - protected: + ArmatureData *_armatureData; + BatchNode *_batchNode; + std::string _name; + cocos2d::TextureAtlas *_atlas; + Bone *_parentBone; + float _version; + mutable bool _armatureTransformDirty; cocos2d::Dictionary *_boneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone or the indirect bone. It is different from m_pChindren. @@ -222,9 +242,9 @@ protected: cocos2d::Dictionary *_textureAtlasDic; #if ENABLE_PHYSICS_BOX2D_DETECT - CC_PROPERTY(b2Body *, _body, Body); + b2Body *_body; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_PROPERTY(cpBody *, _body, Body); + cpBody *_body; #endif }; diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 8f9c9252bd..6b234782bd 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -146,7 +146,7 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; DictElement *element = nullptr; - Dictionary *dict = _armature->getBoneDic(); + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); @@ -174,7 +174,7 @@ void ArmatureAnimation::setAnimationInternal(float animationInternal) _animationInternal = animationInternal; DictElement *element = nullptr; - Dictionary *dict = _armature->getBoneDic(); + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); @@ -236,7 +236,7 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura _tweenList->removeAllObjects(); DictElement *element = nullptr; - Dictionary *dict = _armature->getBoneDic(); + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -261,7 +261,7 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura } else { - if(!bone->getIgnoreMovementBoneData()) + if(!bone->isIgnoreMovementBoneData()) { //! this bone is not include in this movement, so hide it bone->getDisplayManager()->changeDisplayByIndex(-1, false); @@ -319,7 +319,7 @@ void ArmatureAnimation::gotoAndPause(int frameIndex) pause(); } -int ArmatureAnimation::getMovementCount() +int ArmatureAnimation::getMovementCount() const { return _animationData->getMovementCount(); } @@ -416,7 +416,7 @@ void ArmatureAnimation::updateHandler() } } -std::string ArmatureAnimation::getCurrentMovementID() +std::string ArmatureAnimation::getCurrentMovementID() const { if (_isComplete) { diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 3c6e7e5a2c..8d306398e9 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -170,7 +170,7 @@ public: /** * Get movement count */ - int getMovementCount(); + int getMovementCount() const; void update(float dt); @@ -178,7 +178,7 @@ public: * Get current movementID * @return The name of current movement */ - std::string getCurrentMovementID(); + std::string getCurrentMovementID() const; /** * Set armature's movement event callback function @@ -192,6 +192,16 @@ public: */ void setFrameEventCallFunc(cocos2d::Object *target, SEL_FrameEventCallFunc callFunc); + virtual void setAnimationData(AnimationData *data) + { + if (_animationData != data) + { + CC_SAFE_RETAIN(data); + CC_SAFE_RELEASE(_animationData); + _animationData = data; + } + } + virtual AnimationData *getAnimationData() const { return _animationData; } protected: /** @@ -209,12 +219,12 @@ protected: */ void frameEvent(Bone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); - inline bool isIgnoreFrameEvent() { return _ignoreFrameEvent; } + bool isIgnoreFrameEvent() const { return _ignoreFrameEvent; } friend class Tween; protected: //! AnimationData save all MovementDatas this animation used. - CC_SYNTHESIZE_RETAIN(AnimationData *, _animationData, AnimationData); + AnimationData *_animationData; //! Scale the animation speed float _speedScale; diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index d674d8487b..36158a12dd 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -83,7 +83,7 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) { armature->setBatchNode(this); - Dictionary *dict = armature->getBoneDic(); + const Dictionary *dict = armature->getBoneDic(); DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { @@ -111,7 +111,7 @@ void BatchNode::removeChild(Node* child, bool cleanup) { armature->setBatchNode(nullptr); - Dictionary *dict = armature->getBoneDic(); + const Dictionary *dict = armature->getBoneDic(); DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { @@ -188,7 +188,7 @@ void BatchNode::draw() } } -TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) +TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) const { int key = texture->getName(); diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index 44f10872c2..fa654a19ba 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -40,15 +40,15 @@ public: BatchNode(); ~BatchNode(); - virtual bool init(); - virtual void addChild(cocos2d::Node *pChild); - virtual void addChild(cocos2d::Node *pChild, int zOrder); - virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag); - virtual void removeChild(cocos2d::Node* child, bool cleanup); - virtual void visit(); - void draw(); + virtual bool init() override; + virtual void addChild(cocos2d::Node *pChild) override; + virtual void addChild(cocos2d::Node *pChild, int zOrder) override; + virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag) override; + virtual void removeChild(cocos2d::Node* child, bool cleanup) override; + virtual void visit() override; + void draw() override; - virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture) const; protected: cocos2d::TextureAtlas *_atlas; cocos2d::Dictionary *_textureAtlasDic; diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 45562f898e..26c5653d58 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -127,7 +127,7 @@ bool Bone::init(const char *name) _worldInfo = new BaseData(); CC_SAFE_DELETE(_boneData); - _boneData = new CCBoneData(); + _boneData = new BoneData(); bRet = true; } @@ -153,7 +153,7 @@ void Bone::setBoneData(BoneData *boneData) _displayManager->initDisplayList(boneData); } -BoneData *Bone::getBoneData() +BoneData *Bone::getBoneData() const { return _boneData; } @@ -174,7 +174,7 @@ void Bone::setArmature(Armature *armature) } -Armature *Bone::getArmature() +Armature *Bone::getArmature() const { return _armature; } @@ -376,7 +376,7 @@ void Bone::setChildArmature(Armature *armature) } } -Armature *Bone::getChildArmature() +Armature *Bone::getChildArmature() const { return _childArmature; } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 58a15c3987..9082f1ebb3 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -63,7 +63,7 @@ public: /** * Initializes an empty Bone with nothing init. */ - virtual bool init(); + virtual bool init() override; /** * Initializes a Bone with the specified name @@ -124,10 +124,10 @@ public: */ void removeChildBone(Bone *bone, bool recursion); - void update(float delta); + void update(float delta) override; - void updateDisplayedColor(const cocos2d::Color3B &parentColor); - void updateDisplayedOpacity(GLubyte parentOpacity); + void updateDisplayedColor(const cocos2d::Color3B &parentColor) override; + void updateDisplayedOpacity(GLubyte parentOpacity) override; virtual void setColor(const cocos2d::Color3B& color) override; virtual void setOpacity(GLubyte opacity) override; @@ -138,15 +138,15 @@ public: //! Update zorder void updateZOrder(); - virtual void setZOrder(int zOrder); + virtual void setZOrder(int zOrder) override; Tween *getTween(); /* * Whether or not the bone's transform property changed. if true, the bone will update the transform. */ - virtual inline void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } - virtual inline bool isTransformDirty() { return _boneTransformDirty; } + virtual void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } + virtual bool isTransformDirty() { return _boneTransformDirty; } virtual cocos2d::AffineTransform getNodeToArmatureTransform() const; virtual cocos2d::AffineTransform getNodeToWorldTransform() const override; @@ -161,45 +161,69 @@ public: virtual void setColliderFilter(ColliderFilter *filter); virtual ColliderFilter *getColliderFilter(); -public: + + virtual void setBoneData(BoneData *boneData); + virtual BoneData *getBoneData() const; + + virtual void setArmature(Armature *armature); + virtual Armature *getArmature() const; + + virtual void setChildArmature(Armature *childArmature); + virtual Armature *getChildArmature() const; + + virtual DisplayManager *getDisplayManager() const { return _displayManager; } + + virtual void setIgnoreMovementBoneData(bool ignore) { _ignoreMovementBoneData = ignore; } + virtual bool isIgnoreMovementBoneData() const { return _ignoreMovementBoneData; } + + virtual void setBlendType(BlendType type) { _blendType = type; } + virtual BlendType getBlendType() const { return _blendType; } + + virtual FrameData *getTweenData() const { return _tweenData; } + + virtual void setName(const std::string &name) { _name = name; } + virtual const std::string getName() const { return _name; } + + virtual const BaseData *getWorldInfo() const { return _worldInfo; } +protected: + void applyParentTransform(Bone *parent); + /* * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData * when call setData function, it will copy from the BoneData. */ - CC_PROPERTY(BoneData *, _boneData, BoneData); + BoneData *_boneData; //! A weak reference to the Armature - CC_PROPERTY(Armature *, _armature, Armature); + Armature *_armature; //! A weak reference to the child Armature - CC_PROPERTY(Armature *, _childArmature, ChildArmature); + Armature *_childArmature; - CC_SYNTHESIZE(DisplayManager *, _displayManager, DisplayManager) + DisplayManager *_displayManager; /* * When Armature play an animation, if there is not a MovementBoneData of this bone in this MovementData, this bone will be hidden. * Set IgnoreMovementBoneData to true, then this bone will also be shown. */ - CC_SYNTHESIZE(bool, _ignoreMovementBoneData, IgnoreMovementBoneData) + bool _ignoreMovementBoneData; - CC_SYNTHESIZE(BlendType, _blendType, BlendType) -protected: - void applyParentTransform(Bone *parent); + BlendType _blendType; Tween *_tween; //! Calculate tween effect //! Used for making tween effect in every frame - CC_SYNTHESIZE_READONLY(FrameData *, _tweenData, TweenData); + FrameData *_tweenData; - CC_SYNTHESIZE(std::string, _name, Name); + std::string _name; - Bone *_parentBone; //! A weak reference to its parent + Bone *_parentBone; //! A weak reference to its parent bool _boneTransformDirty; //! Whether or not transform dirty //! self Transform, use this to change display's state cocos2d::AffineTransform _worldTransform; - CC_SYNTHESIZE_READONLY(BaseData*, _worldInfo, WorldInfo); + BaseData *_worldInfo; //! Armature's parent bone Bone *_armatureParentBone; diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index be587ecefb..adbea59a31 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -449,7 +449,7 @@ void ColliderDetector::setBody(b2Body *pBody) } } -b2Body *ColliderDetector::getBody() +b2Body *ColliderDetector::getBody() const { return _body; } @@ -492,7 +492,7 @@ void ColliderDetector::setBody(cpBody *pBody) } } -cpBody *ColliderDetector::getBody() +cpBody *ColliderDetector::getBody() const { return _body; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 0b9c058aa8..2737980f60 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -55,29 +55,37 @@ public: public: ColliderFilter(unsigned short categoryBits = 0x0001, unsigned short maskBits = 0xFFFF, signed short groupIndex = 0); void updateShape(b2Fixture *fixture); + + virtual void setCategoryBits(unsigned short categoryBits) { _categoryBits = categoryBits; } + virtual unsigned short getCategoryBits() const { return _categoryBits; } + + virtual void setMaskBits(unsigned short maskBits) { _maskBits = maskBits; } + virtual unsigned short getMaskBits() const { return _maskBits; } + + virtual void setGroupIndex(signed short groupIndex) { _groupIndex = groupIndex; } + virtual signed short getGroupIndex() const { return _groupIndex; } protected: - CC_SYNTHESIZE(unsigned short, _categoryBits, CategoryBits); - CC_SYNTHESIZE(unsigned short, _maskBits, MaskBits); - CC_SYNTHESIZE(signed short, _groupIndex, GroupIndex); + unsigned short _categoryBits; + unsigned short _maskBits; + signed short _groupIndex; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT public: ColliderFilter(uintptr_t collisionType = 0, uintptr_t group = 0); void updateShape(cpShape *shape); + + virtual void setCollisionType(uintptr_t collisionType) { _collisionType = collisionType; } + virtual uintptr_t getCollisionType() const { return _collisionType; } + + virtual void setGroup(uintptr_t group) { _group = group; } + virtual uintptr_t getGroup() const { return _group; } protected: - CC_SYNTHESIZE(uintptr_t, _collisionType, CollisionType); - CC_SYNTHESIZE(uintptr_t, _group, Group); + uintptr_t _collisionType; + uintptr_t _group; #endif }; class ColliderBody : public cocos2d::Object { -public: -#if ENABLE_PHYSICS_BOX2D_DETECT - CC_SYNTHESIZE(b2Fixture *, _fixture, B2Fixture) -#elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_SYNTHESIZE(cpShape *, _shape, Shape) -#endif - public: ColliderBody(ContourData *contourData); ~ColliderBody(); @@ -86,12 +94,31 @@ public: void setColliderFilter(ColliderFilter *filter); ColliderFilter *getColliderFilter(); + +#if ENABLE_PHYSICS_BOX2D_DETECT + virtual void setB2Fixture(b2Fixture *fixture) { _fixture = fixture; } + virtual b2Fixture *getB2Fixture() const { return _fixture; } +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setShape(cpShape *shape) { _shape = shape; } + virtual cpShape *getShape() const { return _shape; } +#endif + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + virtual const cocos2d::Array *getCalculatedVertexList() const { return _calculatedVertexList; } +#endif private: + +#if ENABLE_PHYSICS_BOX2D_DETECT + b2Fixture *_fixture; +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + cpShape *_shape; +#endif + ContourData *_contourData; ColliderFilter *_filter; #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX - CC_SYNTHESIZE_READONLY(CCArray *, _calculatedVertexList, CalculatedVertexList); + cocos2d::Array *_calculatedVertexList; #endif }; @@ -132,16 +159,27 @@ public: virtual void setColliderFilter(ColliderFilter *filter); virtual ColliderFilter *getColliderFilter(); -protected: + + virtual void setBone(Bone *bone) { _bone = bone; } + virtual Bone *getBone() const { return _bone; } + +#if ENABLE_PHYSICS_BOX2D_DETECT + virtual void setBody(b2Body *body); + virtual b2Body *getBody() const; +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setBody(cpBody *body); + virtual cpBody *getBody() const; +#endif + protected: cocos2d::Array *_colliderBodyList; ColliderFilter *_filter; - CC_SYNTHESIZE(Bone *, _bone, Bone); + Bone *_bone; #if ENABLE_PHYSICS_BOX2D_DETECT - CC_PROPERTY(b2Body *, _body, Body); + b2Body *_body; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_PROPERTY(cpBody *, _body, Body); + cpBody *_body; #endif protected: diff --git a/cocos/editor-support/cocostudio/CCDecorativeDisplay.h b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h index 7196d0e9ec..0444cae440 100644 --- a/cocos/editor-support/cocostudio/CCDecorativeDisplay.h +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h @@ -53,13 +53,46 @@ public: virtual bool init(); -protected: + virtual void setDisplay(cocos2d::Node *display) + { + if (_display != display) + { + CC_SAFE_RETAIN(display); + CC_SAFE_RELEASE(_display); + _display = display; + } + } + virtual cocos2d::Node *getDisplay() const { return _display; } - CC_SYNTHESIZE_RETAIN(cocos2d::Node *, _display, Display); - CC_SYNTHESIZE_RETAIN(DisplayData *, _displayData, DisplayData); + virtual void setDisplayData(DisplayData *data) + { + if (_displayData != data) + { + CC_SAFE_RETAIN(data); + CC_SAFE_RELEASE(_displayData); + _displayData = data; + } + } + virtual DisplayData *getDisplayData() const { return _displayData; } #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_SYNTHESIZE_RETAIN(ColliderDetector *, _colliderDetector, ColliderDetector); + virtual void setColliderDetector(ColliderDetector *detector) + { + if (_colliderDetector != detector) + { + CC_SAFE_RETAIN(detector); + CC_SAFE_RELEASE(_colliderDetector); + _colliderDetector = detector; + } + } + virtual ColliderDetector *getColliderDetector() const { return _colliderDetector; } +#endif +protected: + cocos2d::Node *_display; + DisplayData *_displayData; + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + ColliderDetector *_colliderDetector; #endif }; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 5efa5510c7..52af6b2d1d 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -182,7 +182,7 @@ void DisplayManager::removeDisplay(int index) _decoDisplayList->removeObjectAtIndex(index); } -Array *DisplayManager::getDecorativeDisplayList() +Array *DisplayManager::getDecorativeDisplayList() const { return _decoDisplayList; } @@ -276,28 +276,28 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) } } -Node *DisplayManager::getDisplayRenderNode() +Node *DisplayManager::getDisplayRenderNode() const { return _displayRenderNode; } -DisplayType DisplayManager::getDisplayRenderNodeType() +DisplayType DisplayManager::getDisplayRenderNodeType() const { return _displayType; } -int DisplayManager::getCurrentDisplayIndex() +int DisplayManager::getCurrentDisplayIndex() const { return _displayIndex; } -DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() +DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() const { return _currentDecoDisplay; } -DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) +DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) const { return (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); } @@ -377,32 +377,32 @@ void DisplayManager::setVisible(bool visible) _displayRenderNode->setVisible(visible); } -bool DisplayManager::isVisible() +bool DisplayManager::isVisible() const { return _visible; } -Size DisplayManager::getContentSize() +Size DisplayManager::getContentSize() const { CS_RETURN_IF(!_displayRenderNode) Size(0, 0); return _displayRenderNode->getContentSize(); } -Rect DisplayManager::getBoundingBox() +Rect DisplayManager::getBoundingBox() const { CS_RETURN_IF(!_displayRenderNode) Rect(0, 0, 0, 0); return _displayRenderNode->getBoundingBox(); } -Point DisplayManager::getAnchorPoint() +Point DisplayManager::getAnchorPoint() const { CS_RETURN_IF(!_displayRenderNode) Point(0, 0); return _displayRenderNode->getAnchorPoint(); } -Point DisplayManager::getAnchorPointInPoints() +Point DisplayManager::getAnchorPointInPoints() const { CS_RETURN_IF(!_displayRenderNode) Point(0, 0); return _displayRenderNode->getAnchorPointInPoints(); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.h b/cocos/editor-support/cocostudio/CCDisplayManager.h index 0856886c57..1f1b4190ba 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/CCDisplayManager.h @@ -76,7 +76,7 @@ public: void removeDisplay(int index); - cocos2d::Array *getDecorativeDisplayList(); + cocos2d::Array *getDecorativeDisplayList() const; /** * Change display by index. You can just use this method to change display in the display list. @@ -90,14 +90,14 @@ public: void changeDisplayByIndex(int index, bool force); - cocos2d::Node *getDisplayRenderNode(); - DisplayType getDisplayRenderNodeType(); + cocos2d::Node *getDisplayRenderNode() const; + DisplayType getDisplayRenderNodeType() const; - int getCurrentDisplayIndex(); + int getCurrentDisplayIndex() const; virtual void setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay); - virtual DecorativeDisplay *getCurrentDecorativeDisplay(); - virtual DecorativeDisplay *getDecorativeDisplayByIndex( int index); + virtual DecorativeDisplay *getCurrentDecorativeDisplay() const; + virtual DecorativeDisplay *getDecorativeDisplayByIndex( int index) const; /** * Sets whether the display is visible @@ -112,13 +112,13 @@ public: * @see setVisible(bool) * @return true if the node is visible, false if the node is hidden. */ - virtual bool isVisible(); + virtual bool isVisible() const; - cocos2d::Size getContentSize(); - cocos2d::Rect getBoundingBox(); + cocos2d::Size getContentSize() const; + cocos2d::Rect getBoundingBox() const; - cocos2d::Point getAnchorPoint(); - cocos2d::Point getAnchorPointInPoints(); + cocos2d::Point getAnchorPoint() const; + cocos2d::Point getAnchorPointInPoints() const; /** * Check if the position is inside the bone. @@ -130,6 +130,8 @@ public: */ virtual bool containPoint(float x, float y); + virtual void setForceChangeDisplay(bool force) { _forceChangeDisplay = force; } + virtual bool isForceChangeDisplay() const { return _forceChangeDisplay; } protected: cocos2d::Array *_decoDisplayList; //! Display render node. @@ -141,7 +143,7 @@ protected: //! Current display index int _displayIndex; - CC_SYNTHESIZE(bool, _forceChangeDisplay, ForceChangeDisplay) + bool _forceChangeDisplay; //! Whether of not the bone is visible. Default is true bool _visible; diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index e59244433e..c6b62793b4 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -114,6 +114,23 @@ public: virtual int getCurrentFrameIndex(); + virtual void setProcessScale(float processScale) { _processScale = processScale; } + virtual float getProcessScale() const { return _processScale; } + + virtual void setIsPause(bool pause) { _isPause = pause; } + virtual bool isPause() const { return _isPause; } + + virtual void setIsComplete(bool complete) { _isComplete = complete; } + virtual bool isComplete() const { return _isComplete; } + + virtual void setIsPlaying(bool playing) { _isPlaying = playing; } + virtual bool isPlaying() const { return _isPlaying; } + + virtual float getCurrentPercent() const { return _currentPercent; } + virtual int getRawDuration() const { return _rawDuration; } + + virtual void setAnimationInternal(float animationInternal) { _animationInternal = animationInternal; } + virtual float getAnimationInternal() const { return _animationInternal; } protected: virtual void gotoFrame(int frameIndex); @@ -125,31 +142,31 @@ protected: protected: //! Scale the process speed - CC_SYNTHESIZE(float, _processScale, ProcessScale); + float _processScale; //! Set and get whether the aniamtion is pause - CC_SYNTHESIZE(bool, _isPause, IsPause); + bool _isPause; //! Set and get whether the aniamtion is complete - CC_SYNTHESIZE(bool, _isComplete, IsComplete); + bool _isComplete; //! Set and get whether the aniamtion is playing - CC_SYNTHESIZE(bool, _isPlaying, IsPlaying); + bool _isPlaying; //! Current percent this process arrived - CC_SYNTHESIZE(float, _currentPercent, CurrentPercent); + float _currentPercent; //! The raw duration - CC_SYNTHESIZE(int, _rawDuration, RawDuration); + int _rawDuration; //! The animation whether or not loop - CC_SYNTHESIZE(AnimationType, _loopType, LoopType); + AnimationType _loopType; //! The tween easing effect - CC_SYNTHESIZE(TweenType, _tweenEasing, TweenEasing); + TweenType _tweenEasing; //! The animation update speed - CC_SYNTHESIZE(float, _animationInternal, AnimationInternal); + float _animationInternal; protected: diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index b0496729f4..62710e561d 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -224,7 +224,7 @@ void Skin::setBone(Bone *bone) } } -Bone *Skin::getBone() +Bone *Skin::getBone() const { return _bone; } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 2d934b8e4b..6e62da7d22 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,22 +39,28 @@ public: public: Skin(); - bool initWithSpriteFrameName(const char *pszSpriteFrameName); - bool initWithFile(const char *pszFilename); + bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; + bool initWithFile(const char *pszFilename) override; void updateArmatureTransform(); - void updateTransform(); + void updateTransform() override; - cocos2d::AffineTransform getNodeToWorldTransform() const; + cocos2d::AffineTransform getNodeToWorldTransform() const override; cocos2d::AffineTransform getNodeToWorldTransformAR() const; - CC_PROPERTY_PASS_BY_REF(BaseData, _skinData, SkinData); - CC_PROPERTY(Bone *, _bone, Bone); + virtual void setSkinData(const BaseData &data); + virtual const BaseData &getSkinData() const; + virtual void setBone(Bone *bone); + virtual Bone *getBone() const; + + virtual const std::string &getDisplayName() const { return _displayName; } protected: + BaseData _skinData; + Bone *_bone; Armature *_armature; cocos2d::AffineTransform _skinTransform; - CC_SYNTHESIZE_READONLY(std::string, _displayName, DisplayName) + std::string _displayName; }; } diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 75ff8bbb7e..dec84bf295 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -328,7 +328,7 @@ void Tween::arriveKeyFrame(FrameData *keyFrameData) //! Change bone's display int displayIndex = keyFrameData->displayIndex; - if (!displayManager->getForceChangeDisplay()) + if (!displayManager->isForceChangeDisplay()) { displayManager->changeDisplayByIndex(displayIndex, false); } diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index ce08f2264e..8b4dcba9d2 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -88,6 +88,9 @@ public: virtual void gotoAndPlay(int frameIndex); virtual void gotoAndPause(int frameIndex); + + virtual void setMovementBoneData(MovementBoneData *data) { _movementBoneData = data; } + virtual const MovementBoneData *getMovementBoneData() const { return _movementBoneData; } protected: /** @@ -121,7 +124,7 @@ protected: virtual void arriveKeyFrame(FrameData *keyFrameData); protected: //! A weak reference to the current MovementBoneData. The data is in the data pool - CC_SYNTHESIZE(MovementBoneData *, _movementBoneData, MovementBoneData) + MovementBoneData *_movementBoneData; FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData FrameData *_from; //! From frame data, used for calculate between value diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index b571dfb808..65cd9044ef 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -271,9 +271,9 @@ std::string TestAsynchronousLoading::subtitle() return "current percent : "; } -void TestAsynchronousLoading::restartCallback(CCObject* pSender) +void TestAsynchronousLoading::restartCallback(Object* pSender) { - ArmatureDataManager::getInstance()->purge(); + ArmatureDataManager::getInstance()->destoryInstance(); ArmatureTestLayer::restartCallback(pSender); } void TestAsynchronousLoading::dataLoaded(float percent) @@ -307,7 +307,7 @@ void TestDirectLoading::onEnter() Armature *armature = Armature::create("bear"); armature->getAnimation()->playByIndex(0); - armature->setPosition(ccp(VisibleRect::center().x, VisibleRect::center().y)); + armature->setPosition(Point(VisibleRect::center().x, VisibleRect::center().y)); addChild(armature); } std::string TestDirectLoading::title() @@ -608,7 +608,7 @@ void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIn } void TestFrameEvent::checkAction(float dt) { - if ( this->numberOfRunningActions() == 0 && this->getGrid() != nullptr) + if ( this->getNumberOfRunningActions() == 0 && this->getGrid() != nullptr) this->setGrid(nullptr); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index f8429fc595..79e29b61dc 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -74,7 +74,7 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); - virtual void restartCallback(CCObject* pSender); + virtual void restartCallback(Object* pSender); void dataLoaded(float percent); }; From af129e25f008aeeb58eba99677a8c0e44c2e1f11 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 5 Nov 2013 20:02:58 +0800 Subject: [PATCH 073/197] issue #2771: change some coding style --- cocos/base/CCGeometry.cpp | 10 ++ cocos/base/CCGeometry.h | 10 ++ cocos/physics/CCPhysicsBody.cpp | 100 ++++++++--------- cocos/physics/CCPhysicsBody.h | 32 +++--- cocos/physics/CCPhysicsContact.cpp | 4 +- cocos/physics/CCPhysicsContact.h | 2 +- cocos/physics/CCPhysicsJoint.cpp | 26 ++--- cocos/physics/CCPhysicsSetting.h | 3 + cocos/physics/CCPhysicsShape.cpp | 104 +++++++++--------- cocos/physics/CCPhysicsShape.h | 48 ++++---- cocos/physics/CCPhysicsWorld.cpp | 88 +++++++-------- cocos/physics/CCPhysicsWorld.h | 14 +-- .../chipmunk/CCPhysicsBodyInfo_chipmunk.cpp | 9 +- .../chipmunk/CCPhysicsBodyInfo_chipmunk.h | 8 +- .../CCPhysicsContactInfo_chipmunk.cpp | 2 +- .../chipmunk/CCPhysicsContactInfo_chipmunk.h | 5 +- .../chipmunk/CCPhysicsJointInfo_chipmunk.cpp | 28 ++--- .../chipmunk/CCPhysicsJointInfo_chipmunk.h | 12 +- .../chipmunk/CCPhysicsShapeInfo_chipmunk.cpp | 56 +++++----- .../chipmunk/CCPhysicsShapeInfo_chipmunk.h | 20 +++- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 8 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 6 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 12 +- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 4 +- 24 files changed, 325 insertions(+), 286 deletions(-) diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 1d5c4896c6..8ab9e39dda 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -96,6 +96,16 @@ bool Point::operator!=(const Point& right) return this->x != right.x || this->y != right.y; } +bool Point::operator==(const Point& right) const +{ + return this->x == right.x && this->y == right.y; +} + +bool Point::operator!=(const Point& right) const +{ + return this->x != right.x || this->y != right.y; +} + Point Point::operator*(float a) const { return Point(this->x * a, this->y * a); diff --git a/cocos/base/CCGeometry.h b/cocos/base/CCGeometry.h index 847557cb35..3b6b8c2655 100644 --- a/cocos/base/CCGeometry.h +++ b/cocos/base/CCGeometry.h @@ -123,6 +123,16 @@ public: * @lua NA */ bool operator!=(const Point& right); + /** + * @js NA + * @lua NA + */ + bool operator==(const Point& right) const; + /** + * @js NA + * @lua NA + */ + bool operator!=(const Point& right) const; /** * @js NA * @lua NA diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 8a177e6252..131bfdc3c5 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -157,7 +157,7 @@ PhysicsBody* PhysicsBody::create(float mass, float moment) } -PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material, Point offset) +PhysicsBody* PhysicsBody::createCircle(float radius, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -171,7 +171,7 @@ PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material, P return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material, Point offset) +PhysicsBody* PhysicsBody::createBox(const Size& size, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -185,7 +185,7 @@ PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material, Point o return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material, Point offset) +PhysicsBody* PhysicsBody::createPolygon(const Point* points, int count, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -199,7 +199,7 @@ PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMateria return nullptr; } -PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -214,7 +214,7 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial ma return nullptr; } -PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/, Point offset) +PhysicsBody* PhysicsBody::createEdgeBox(const Size& size, const PhysicsMaterial& material, float border/* = 1*/, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -230,7 +230,7 @@ PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, flo return nullptr; } -PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -246,7 +246,7 @@ PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMat return nullptr; } -PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeChain(const Point* points, int count, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -272,9 +272,9 @@ bool PhysicsBody::init() CC_BREAK_IF(_shapes == nullptr); _shapes->retain(); - _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); + _info->setBody(cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment))); - CC_BREAK_IF(_info->body == nullptr); + CC_BREAK_IF(_info->getBody() == nullptr); return true; } while (false); @@ -289,19 +289,19 @@ void PhysicsBody::setDynamic(bool dynamic) _dynamic = dynamic; if (dynamic) { - cpBodySetMass(_info->body, _mass); + cpBodySetMass(_info->getBody(), _mass); if (_world != nullptr) { - cpSpaceAddBody(_world->_info->space, _info->body); + cpSpaceAddBody(_world->_info->getSpace(), _info->getBody()); } }else { - cpBodySetMass(_info->body, PHYSICS_INFINITY); + cpBodySetMass(_info->getBody(), PHYSICS_INFINITY); if (_world != nullptr) { - cpSpaceRemoveBody(_world->_info->space, _info->body); + cpSpaceRemoveBody(_world->_info->getSpace(), _info->getBody()); } } @@ -312,7 +312,7 @@ void PhysicsBody::setRotationEnable(bool enable) { if (_rotationEnable != enable) { - cpBodySetMoment(_info->body, enable ? _moment : PHYSICS_INFINITY); + cpBodySetMoment(_info->getBody(), enable ? _moment : PHYSICS_INFINITY); _rotationEnable = enable; } } @@ -338,23 +338,23 @@ void PhysicsBody::setGravityEnable(bool enable) void PhysicsBody::setPosition(Point position) { - cpBodySetPos(_info->body, PhysicsHelper::point2cpv(position)); + cpBodySetPos(_info->getBody(), PhysicsHelper::point2cpv(position)); } void PhysicsBody::setRotation(float rotation) { - cpBodySetAngle(_info->body, PhysicsHelper::float2cpfloat(rotation)); + cpBodySetAngle(_info->getBody(), PhysicsHelper::float2cpfloat(rotation)); } Point PhysicsBody::getPosition() const { - cpVect vec = cpBodyGetPos(_info->body); + cpVect vec = cpBodyGetPos(_info->getBody()); return PhysicsHelper::cpv2point(vec); } float PhysicsBody::getRotation() const { - return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->body) / 3.14f * 180.0f); + return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->getBody()) / 3.14f * 180.0f); } PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) @@ -388,29 +388,29 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) return shape; } -void PhysicsBody::applyForce(Point force) +void PhysicsBody::applyForce(const Vect& force) { applyForce(force, Point::ZERO); } -void PhysicsBody::applyForce(Point force, Point offset) +void PhysicsBody::applyForce(const Vect& force, const Point& offset) { - cpBodyApplyForce(_info->body, PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset)); + cpBodyApplyForce(_info->getBody(), PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset)); } -void PhysicsBody::applyImpulse(Point impulse) +void PhysicsBody::applyImpulse(const Vect& impulse) { applyImpulse(impulse, Point()); } -void PhysicsBody::applyImpulse(Point impulse, Point offset) +void PhysicsBody::applyImpulse(const Vect& impulse, const Point& offset) { - cpBodyApplyImpulse(_info->body, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); + cpBodyApplyImpulse(_info->getBody(), PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); } void PhysicsBody::applyTorque(float torque) { - cpBodySetTorque(_info->body, PhysicsHelper::float2cpfloat(torque)); + cpBodySetTorque(_info->getBody(), PhysicsHelper::float2cpfloat(torque)); } void PhysicsBody::setMass(float mass) @@ -439,7 +439,7 @@ void PhysicsBody::setMass(float mass) } } - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMass(_info->getBody(), PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMass(float mass) @@ -481,7 +481,7 @@ void PhysicsBody::addMass(float mass) } } - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMass(_info->getBody(), PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMoment(float moment) @@ -522,58 +522,58 @@ void PhysicsBody::addMoment(float moment) if (_rotationEnable) { - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_info->getBody(), PhysicsHelper::float2cpfloat(_moment)); } } -void PhysicsBody::setVelocity(Point velocity) +void PhysicsBody::setVelocity(const Point& velocity) { - cpBodySetVel(_info->body, PhysicsHelper::point2cpv(velocity)); + cpBodySetVel(_info->getBody(), PhysicsHelper::point2cpv(velocity)); } Point PhysicsBody::getVelocity() { - return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); + return PhysicsHelper::cpv2point(cpBodyGetVel(_info->getBody())); } -Point PhysicsBody::getVelocityAtLocalPoint(Point point) +Point PhysicsBody::getVelocityAtLocalPoint(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->getBody(), PhysicsHelper::point2cpv(point))); } -Point PhysicsBody::getVelocityAtWorldPoint(Point point) +Point PhysicsBody::getVelocityAtWorldPoint(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->getBody(), PhysicsHelper::point2cpv(point))); } void PhysicsBody::setAngularVelocity(float velocity) { - cpBodySetAngVel(_info->body, PhysicsHelper::float2cpfloat(velocity)); + cpBodySetAngVel(_info->getBody(), PhysicsHelper::float2cpfloat(velocity)); } float PhysicsBody::getAngularVelocity() { - return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->getBody())); } void PhysicsBody::setVelocityLimit(float limit) { - cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_info->getBody(), PhysicsHelper::float2cpfloat(limit)); } float PhysicsBody::getVelocityLimit() { - return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->getBody())); } void PhysicsBody::setAngularVelocityLimit(float limit) { - cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_info->getBody(), PhysicsHelper::float2cpfloat(limit)); } float PhysicsBody::getAngularVelocityLimit() { - return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->getBody())); } void PhysicsBody::setMoment(float moment) @@ -583,11 +583,11 @@ void PhysicsBody::setMoment(float moment) if (_rotationEnable) { - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_info->getBody(), PhysicsHelper::float2cpfloat(_moment)); } } -PhysicsShape* PhysicsBody::getShapeByTag(int tag) const +PhysicsShape* PhysicsBody::getShape(int tag) const { for (auto child : *_shapes) { @@ -601,7 +601,7 @@ PhysicsShape* PhysicsBody::getShapeByTag(int tag) const return nullptr; } -void PhysicsBody::removeShapeByTag(int tag) +void PhysicsBody::removeShape(int tag) { for (auto child : *_shapes) { @@ -685,7 +685,7 @@ void PhysicsBody::setEnable(bool enable) bool PhysicsBody::isResting() const { - return cpBodyIsSleeping(_info->body) == cpTrue; + return cpBodyIsSleeping(_info->getBody()) == cpTrue; } void PhysicsBody::update(float delta) @@ -693,9 +693,9 @@ void PhysicsBody::update(float delta) // damping compute if (_dynamic) { - _info->body->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); - _info->body->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); - _info->body->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); + _info->getBody()->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->getBody()->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->getBody()->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); } } @@ -739,12 +739,12 @@ void PhysicsBody::setGroup(int group) Point PhysicsBody::world2Local(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->getBody(), PhysicsHelper::point2cpv(point))); } Point PhysicsBody::local2World(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->getBody(), PhysicsHelper::point2cpv(point))); } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 60dd314966..7c0c79002e 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -59,62 +59,62 @@ public: /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); + static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); + static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); + static PhysicsBody* createPolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a EdgeSegment shape. */ - static PhysicsBody* createEdgeSegment(Point a, Point b, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeBox shape. */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, Point offset = Point::ZERO); + static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); /** * @brief Create a body contains a EdgePolygon shape. */ - static PhysicsBody* createEdgePolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeChain shape. */ - static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeChain(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); virtual PhysicsShape* addShape(PhysicsShape* shape); /** * @brief Applies a immediate force to body. */ - virtual void applyForce(Point force); + virtual void applyForce(const Vect& force); /** * @brief Applies a immediate force to body. */ - virtual void applyForce(Point force, Point offset); + virtual void applyForce(const Vect& force, const Point& offset); /** * @brief Applies a continuous force to body. */ - virtual void applyImpulse(Point impulse); + virtual void applyImpulse(const Vect& impulse); /** * @brief Applies a continuous force to body. */ - virtual void applyImpulse(Point impulse, Point offset); + virtual void applyImpulse(const Vect& impulse, const Point& offset); /** * @brief Applies a torque force to body. */ virtual void applyTorque(float torque); - virtual void setVelocity(Point velocity); + virtual void setVelocity(const Vect& velocity); virtual Point getVelocity(); virtual void setAngularVelocity(float velocity); - virtual Point getVelocityAtLocalPoint(Point point); - virtual Point getVelocityAtWorldPoint(Point point); + virtual Point getVelocityAtLocalPoint(const Point& point); + virtual Point getVelocityAtWorldPoint(const Point& point); virtual float getAngularVelocity(); virtual void setVelocityLimit(float limit); virtual float getVelocityLimit(); @@ -129,12 +129,12 @@ public: * @brief get the first body shapes. */ inline PhysicsShape* getShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } - PhysicsShape* getShapeByTag(int tag) const; + PhysicsShape* getShape(int tag) const; /* * @brief remove a shape from body */ void removeShape(PhysicsShape* shape); - void removeShapeByTag(int tag); + void removeShape(int tag); /* * @brief remove all shapes */ diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index e3a4907a97..71bdf5a1d0 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -150,9 +150,9 @@ void PhysicsContactPreSolve::setFriction(float friction) static_cast(_contactInfo)->u = friction; } -void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) +void PhysicsContactPreSolve::setSurfaceVelocity(const Vect& velocity) { - static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); + static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(velocity); } void PhysicsContactPreSolve::ignore() diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index ee279ef474..3982f4fdd6 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -138,7 +138,7 @@ public: Point getSurfaceVelocity() const; void setElasticity(float elasticity); void setFriction(float friction); - void setSurfaceVelocity(Point surfaceVelocity); + void setSurfaceVelocity(const Vect& velocity); void ignore(); private: diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 694559264e..791266f8ba 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -197,13 +197,13 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) getBodyNode(b)->setPosition(anchr); // add a pivot joint to fixed two body together - cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. - joint = cpGearJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, 0, 1); + joint = cpGearJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), 0, 1); CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -233,7 +233,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); @@ -248,12 +248,12 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) void PhysicsJointPin::setMaxForce(float force) { - _info->joints.front()->maxForce = PhysicsHelper::float2cpfloat(force); + _info->getJoints().front()->maxForce = PhysicsHelper::float2cpfloat(force); } float PhysicsJointPin::getMaxForce() const { - return PhysicsHelper::cpfloat2float(_info->joints.front()->maxForce); + return PhysicsHelper::cpfloat2float(_info->getJoints().front()->maxForce); } PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) @@ -275,7 +275,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(grooveA), PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); @@ -310,7 +310,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2), 0, @@ -328,22 +328,22 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 float PhysicsJointLimit::getMin() const { - return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->joints.front())); + return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->getJoints().front())); } void PhysicsJointLimit::setMin(float min) { - cpSlideJointSetMin(_info->joints.front(), PhysicsHelper::float2cpfloat(min)); + cpSlideJointSetMin(_info->getJoints().front(), PhysicsHelper::float2cpfloat(min)); } float PhysicsJointLimit::getMax() const { - return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->joints.front())); + return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->getJoints().front())); } void PhysicsJointLimit::setMax(float max) { - cpSlideJointSetMax(_info->joints.front(), PhysicsHelper::float2cpfloat(max)); + cpSlideJointSetMax(_info->getJoints().front(), PhysicsHelper::float2cpfloat(max)); } PhysicsJointDistance* PhysicsJointDistance::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) @@ -365,8 +365,8 @@ bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anc { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->body, - getBodyInfo(b)->body, + cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->getBody(), + getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); CC_BREAK_IF(joint == nullptr); diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index ee3214bcd7..9eb82f2fa2 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -47,6 +47,9 @@ namespace cocos2d { extern const float PHYSICS_INFINITY; + class Point; + typedef Point Vect; + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) static const int PHYSICS_CONTACT_POINT_MAX = 4; #else diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index fea8365c08..89d0551cff 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -105,7 +105,7 @@ void PhysicsShape::setMoment(float moment) _moment = moment; } -void PhysicsShape::setMaterial(PhysicsMaterial material) +void PhysicsShape::setMaterial(const PhysicsMaterial& material) { setDensity(material.density); setRestitution(material.restitution); @@ -216,7 +216,7 @@ void PhysicsShape::setRestitution(float restitution) { _material.restitution = restitution; - for (cpShape* shape : _info->shapes) + for (cpShape* shape : _info->getShapes()) { cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(restitution)); } @@ -226,14 +226,14 @@ void PhysicsShape::setFriction(float friction) { _material.friction = friction; - for (cpShape* shape : _info->shapes) + for (cpShape* shape : _info->getShapes()) { cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction)); } } -Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) +Point* PhysicsShape::recenterPoints(Point* points, int count, const Point& center) { cpVect* cpvs = new cpVect[count]; cpRecenterPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); @@ -251,7 +251,7 @@ Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) return points; } -Point PhysicsShape::getPolyonCenter(Point* points, int count) +Point PhysicsShape::getPolyonCenter(const Point* points, int count) { cpVect* cpvs = new cpVect[count]; cpVect center = cpCentroidForPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); @@ -280,14 +280,14 @@ void PhysicsShape::setBody(PhysicsBody *body) _body = nullptr; }else { - _info->setBody(body->_info->body); + _info->setBody(body->_info->getBody()); //_info->setGroup(body->_info->group); _body = body; } } // PhysicsShapeCircle -PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeCircle* shape = new PhysicsShapeCircle(); if (shape && shape->init(radius, material, offset)) @@ -300,13 +300,13 @@ PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial mat return nullptr; } -bool PhysicsShapeCircle::init(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeCircle::init(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/) { do { CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE)); - cpShape* shape = cpCircleShapeNew(_info->shareBody, radius, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpCircleShapeNew(_info->getSharedBody(), radius, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); @@ -328,7 +328,7 @@ float PhysicsShapeCircle::calculateArea(float radius) return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); } -float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset) +float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Point& offset) { return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), @@ -339,12 +339,12 @@ float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset float PhysicsShapeCircle::calculateDefaultArea() { - return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->shapes.front()))); + return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->getShapes().front()))); } float PhysicsShapeCircle::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), @@ -355,16 +355,16 @@ float PhysicsShapeCircle::calculateDefaultMoment() float PhysicsShapeCircle::getRadius() const { - return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->shapes.front())); + return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->getShapes().front())); } Point PhysicsShapeCircle::getOffset() { - return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->shapes.front())); + return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->getShapes().front())); } // PhysicsShapeEdgeSegment -PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(const Point& a, const Point& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment(); if (shape && shape->init(a, b, material, border)) @@ -377,13 +377,13 @@ PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, Physi return nullptr; } -bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgeSegment::init(const Point& a, const Point& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { do { CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT)); - cpShape* shape = cpSegmentShapeNew(_info->shareBody, + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), PhysicsHelper::point2cpv(a), PhysicsHelper::point2cpv(b), PhysicsHelper::float2cpfloat(border)); @@ -407,12 +407,12 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* Point PhysicsShapeEdgeSegment::getPointA() const { - return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->ta); + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->ta); } Point PhysicsShapeEdgeSegment::getPointB() const { - return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->tb); + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->tb); } Point PhysicsShapeEdgeSegment::getCenter() @@ -421,7 +421,7 @@ Point PhysicsShapeEdgeSegment::getCenter() } // PhysicsShapeBox -PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeBox* PhysicsShapeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeBox* shape = new PhysicsShapeBox(); if (shape && shape->init(size, material, offset)) @@ -434,7 +434,7 @@ PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = return nullptr; } -bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/) { do { @@ -446,7 +446,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} }; - cpShape* shape = cpPolyShapeNew(_info->shareBody, 4, vec, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), 4, vec, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); @@ -465,7 +465,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau return false; } -float PhysicsShapeBox::calculateArea(Size size) +float PhysicsShapeBox::calculateArea(const Size& size) { cpVect wh = PhysicsHelper::size2cpv(size); cpVect vec[4] = @@ -475,7 +475,7 @@ float PhysicsShapeBox::calculateArea(Size size) return PhysicsHelper::cpfloat2float(cpAreaForPoly(4, vec)); } -float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) +float PhysicsShapeBox::calculateMoment(float mass, const Size& size, const Point& offset) { cpVect wh = PhysicsHelper::size2cpv(size); cpVect vec[4] = @@ -492,20 +492,20 @@ float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) float PhysicsShapeBox::calculateDefaultArea() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); } float PhysicsShapeBox::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } Point* PhysicsShapeBox::getPoints(Point* points) const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); return points; @@ -513,13 +513,13 @@ Point* PhysicsShapeBox::getPoints(Point* points) const Size PhysicsShapeBox::getSize() const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1)), cpvdist(cpPolyShapeGetVert(shape, 1), cpPolyShapeGetVert(shape, 2)))); } // PhysicsShapePolygon -PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapePolygon* PhysicsShapePolygon::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); if (shape && shape->init(points, count, material, offset)) @@ -532,7 +532,7 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, Physi return nullptr; } -bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { do { @@ -540,7 +540,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); - cpShape* shape = cpPolyShapeNew(_info->shareBody, count, vecs, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), count, vecs, PhysicsHelper::point2cpv(offset)); CC_SAFE_DELETE(vecs); CC_BREAK_IF(shape == nullptr); @@ -560,7 +560,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia return false; } -float PhysicsShapePolygon::calculateArea(Point* points, int count) +float PhysicsShapePolygon::calculateArea(const Point* points, int count) { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -570,7 +570,7 @@ float PhysicsShapePolygon::calculateArea(Point* points, int count) return area; } -float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, Point offset) +float PhysicsShapePolygon::calculateMoment(float mass, const Point* points, int count, const Point& offset) { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -583,31 +583,31 @@ float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, float PhysicsShapePolygon::calculateDefaultArea() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); } float PhysicsShapePolygon::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } Point PhysicsShapePolygon::getPoint(int i) const { - return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->shapes.front(), i)); + return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->getShapes().front(), i)); } Point* PhysicsShapePolygon::getPoints(Point* points) const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } int PhysicsShapePolygon::getPointsCount() const { - return ((cpPolyShape*)_info->shapes.front())->numVerts; + return ((cpPolyShape*)_info->getShapes().front())->numVerts; } Point PhysicsShapePolygon::getCenter() @@ -616,7 +616,7 @@ Point PhysicsShapePolygon::getCenter() } // PhysicsShapeEdgeBox -PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox(); if (shape && shape->init(size, material, border, offset)) @@ -629,7 +629,7 @@ PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial mate return nullptr; } -bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/*= Point(0, 0)*/) +bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Point& offset/*= Point(0, 0)*/) { do { @@ -644,7 +644,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD int i = 0; for (; i < 4; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%4], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%4], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); _info->add(shape); @@ -664,7 +664,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD } // PhysicsShapeEdgeBox -PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon(); if (shape && shape->init(points, count, material, border)) @@ -677,7 +677,7 @@ PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int coun return nullptr; } -bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do @@ -691,7 +691,7 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial mat int i = 0; for (; i < count; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%count], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%count], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -722,11 +722,11 @@ Point PhysicsShapeEdgePolygon::getCenter() int PhysicsShapeEdgePolygon::getPointsCount() const { - return _info->shapes.size() + 1; + return _info->getShapes().size() + 1; } // PhysicsShapeEdgeChain -PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain(); if (shape && shape->init(points, count, material, border)) @@ -739,7 +739,7 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, P return nullptr; } -bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgeChain::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do @@ -753,7 +753,7 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater int i = 0; for (; i < count - 1; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[i+1], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[i+1], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -783,23 +783,23 @@ Point PhysicsShapeEdgeChain::getCenter() int PhysicsShapeEdgeChain::getPointsCount() const { - return _info->shapes.size() + 1; + return _info->getShapes().size() + 1; } void PhysicsShape::setGroup(int group) { if (group < 0) { - for (auto shape : _info->shapes) + for (auto shape : _info->getShapes()) { cpShapeSetGroup(shape, (cpGroup)group); } } } -bool PhysicsShape::containsPoint(Point point) const +bool PhysicsShape::containsPoint(const Point& point) const { - for (auto shape : _info->shapes) + for (auto shape : _info->getShapes()) { if (cpShapePointQuery(shape, PhysicsHelper::point2cpv(point))) { diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 4ddcfe8a18..4aba49d4d7 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -92,16 +92,16 @@ public: void setDensity(float density); void setRestitution(float restitution); void setFriction(float friction); - void setMaterial(PhysicsMaterial material); + void setMaterial(const PhysicsMaterial& material); virtual float calculateDefaultMoment() { return 0; } virtual float calculateDefaultArea() { return 0; } virtual Point getOffset() { return Point::ZERO; } virtual Point getCenter() { return getOffset(); } - bool containsPoint(Point point) const; + bool containsPoint(const Point& point) const; - static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); - static Point getPolyonCenter(Point* points, int count); + static Point* recenterPoints(Point* points, int count, const Point& center = Point::ZERO); + static Point getPolyonCenter(const Point* points, int count); inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } inline int getCategoryBitmask() const { return _categoryBitmask; } @@ -150,9 +150,9 @@ protected: class PhysicsShapeCircle : public PhysicsShape { public: - static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + static PhysicsShapeCircle* create(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point(0, 0)); static float calculateArea(float radius); - static float calculateMoment(float mass, float radius, Point offset = Point(0, 0)); + static float calculateMoment(float mass, float radius, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; @@ -160,7 +160,7 @@ public: float getRadius() const; Point getOffset() override; protected: - bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeCircle(); @@ -171,9 +171,9 @@ protected: class PhysicsShapeBox : public PhysicsShape { public: - static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Size size); - static float calculateMoment(float mass, Size size, Point offset = Point(0, 0)); + static PhysicsShapeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); + static float calculateArea(const Size& size); + static float calculateMoment(float mass, const Size& size, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; @@ -183,7 +183,7 @@ public: Point getOffset() override { return _offset; } protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeBox(); @@ -197,9 +197,9 @@ protected: class PhysicsShapePolygon : public PhysicsShape { public: - static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Point* points, int count); - static float calculateMoment(float mass, Point* points, int count, Point offset = Point(0, 0)); + static PhysicsShapePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); + static float calculateArea(const Point* points, int count); + static float calculateMoment(float mass, const Point* points, int count, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; @@ -209,7 +209,7 @@ public: int getPointsCount() const; Point getCenter() override; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapePolygon(); @@ -223,14 +223,14 @@ protected: class PhysicsShapeEdgeSegment : public PhysicsShape { public: - static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgeSegment* create(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getPointA() const; Point getPointB() const; Point getCenter() override; protected: - bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeSegment(); @@ -246,13 +246,13 @@ protected: class PhysicsShapeEdgeBox : public PhysicsShape { public: - static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); + static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Point& offset = Point::ZERO); Point getOffset() override { return _offset; } - Point* getPoints(Point* points) const; + Point* getPoints(const Point* points) const; int getPointsCount() const; protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); + bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); protected: PhysicsShapeEdgeBox(); @@ -268,13 +268,13 @@ protected: class PhysicsShapeEdgePolygon : public PhysicsShape { public: - static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; int getPointsCount() const; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgePolygon(); @@ -290,13 +290,13 @@ protected: class PhysicsShapeEdgeChain : public PhysicsShape { public: - static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgeChain* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; int getPointsCount() const; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeChain(); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index cafdb79be8..2a067720c1 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -106,11 +106,11 @@ int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSp { CP_ARBITER_GET_SHAPES(arb, a, b); - auto ita = PhysicsShapeInfo::map.find(a); - auto itb = PhysicsShapeInfo::map.find(b); - CC_ASSERT(ita != PhysicsShapeInfo::map.end() && itb != PhysicsShapeInfo::map.end()); + auto ita = PhysicsShapeInfo::getMap().find(a); + auto itb = PhysicsShapeInfo::getMap().find(b); + CC_ASSERT(ita != PhysicsShapeInfo::getMap().end() && itb != PhysicsShapeInfo::getMap().end()); - PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); + PhysicsContact* contact = PhysicsContact::create(ita->second->getShape(), itb->second->getShape()); arb->data = contact; contact->_contactInfo = arb; @@ -143,12 +143,12 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect return; } - auto it = PhysicsShapeInfo::map.find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + auto it = PhysicsShapeInfo::getMap().find(shape); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); PhysicsRayCastCallback::Info callbackInfo = { - it->second->shape, + it->second->getShape(), info->p1, info->p2, Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), @@ -161,9 +161,9 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) { - auto it = PhysicsShapeInfo::map.find(shape); + auto it = PhysicsShapeInfo::getMap().find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); if (!PhysicsWorldCallback::continues) { @@ -171,17 +171,17 @@ void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallba } PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->shape, + *it->second->getShape(), info->data); } void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) { - auto it = PhysicsShapeInfo::map.find(shape); + auto it = PhysicsShapeInfo::getMap().find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - arr->addObject(it->second->shape); + arr->addObject(it->second->getShape()); } bool PhysicsWorld::init(Scene& scene) @@ -202,9 +202,9 @@ bool PhysicsWorld::init(Scene& scene) _scene = &scene; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); + cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(_gravity)); - cpSpaceSetDefaultCollisionHandler(_info->space, + cpSpaceSetDefaultCollisionHandler(_info->getSpace(), (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, @@ -225,7 +225,7 @@ void PhysicsWorld::delayTestAddBody(PhysicsBody* body) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (_delayAddBodies->getIndexOfObject(body) == UINT_MAX) { @@ -246,7 +246,7 @@ void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (_delayRemoveBodies->getIndexOfObject(body) == UINT_MAX) { @@ -268,7 +268,7 @@ void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) { @@ -290,7 +290,7 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) { @@ -338,7 +338,7 @@ void PhysicsWorld::removeAllJoints() PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) { - for (auto cps : shape->_info->shapes) + for (auto cps : shape->_info->getShapes()) { _info->addShape(cps); } @@ -348,7 +348,7 @@ PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) void PhysicsWorld::realAddJoint(PhysicsJoint *joint) { - for (auto subjoint : joint->_info->joints) + for (auto subjoint : joint->_info->getJoints()) { _info->addJoint(subjoint); } @@ -374,7 +374,7 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) // add body to space if (body->isDynamic()) { - _info->addBody(body->_info->body); + _info->addBody(body->_info->getBody()); } // add shapes to space @@ -401,7 +401,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) _bodies->removeObject(body); } -void PhysicsWorld::removeBodyByTag(int tag) +void PhysicsWorld::removeBody(int tag) { for (Object* obj : *_bodies) { @@ -442,14 +442,14 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) } // remove body - _info->removeBody(body->_info->body); + _info->removeBody(body->_info->getBody()); body->_world = nullptr; } void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) { - for (auto subjoint : joint->_info->joints) + for (auto subjoint : joint->_info->getJoints()) { _info->removeJoint(subjoint); } @@ -468,18 +468,18 @@ void PhysicsWorld::removeAllBodies() void PhysicsWorld::removeShape(PhysicsShape* shape) { - for (auto cps : shape->_info->shapes) + for (auto cps : shape->_info->getShapes()) { - if (cpSpaceContainsShape(_info->space, cps)) + if (cpSpaceContainsShape(_info->getSpace(), cps)) { - cpSpaceRemoveShape(_info->space, cps); + cpSpaceRemoveShape(_info->getSpace(), cps); } } } void PhysicsWorld::updateBodies() { - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { return; } @@ -500,7 +500,7 @@ void PhysicsWorld::updateBodies() void PhysicsWorld::updateJoints() { - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { return; } @@ -533,7 +533,7 @@ void PhysicsWorld::update(float delta) body->update(delta); } - cpSpaceStep(_info->space, delta); + cpSpaceStep(_info->getSpace(), delta); if (_drawNode) { @@ -577,7 +577,7 @@ void PhysicsWorld::debugDraw() void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) { - for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) + for (auto it = joint->_info->getJoints().begin(); it != joint->_info->getJoints().end(); ++it) { cpConstraint *constraint = *it; @@ -638,7 +638,7 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) { - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) + for (auto it = shape->_info->getShapes().begin(); it != shape->_info->getShapes().end(); ++it) { cpShape *shape = *it; @@ -811,11 +811,11 @@ void PhysicsWorld::setGravity(Point gravity) } _gravity = gravity; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); + cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(gravity)); } -void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) +void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data) { CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); @@ -824,7 +824,7 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point RayCastCallbackInfo info = { this, &callback, point1, point2, data }; PhysicsWorldCallback::continues = true; - cpSpaceSegmentQuery(this->_info->space, + cpSpaceSegmentQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point1), PhysicsHelper::point2cpv(point2), CP_ALL_LAYERS, @@ -835,7 +835,7 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point } -void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) +void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data) { CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); @@ -844,7 +844,7 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void RectQueryCallbackInfo info = {this, &callback, data}; PhysicsWorldCallback::continues = true; - cpSpaceBBQuery(this->_info->space, + cpSpaceBBQuery(this->_info->getSpace(), PhysicsHelper::rect2cpbb(rect), CP_ALL_LAYERS, CP_NO_GROUP, @@ -853,10 +853,10 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } -Array* PhysicsWorld::getShapesAtPoint(Point point) const +Array* PhysicsWorld::getShapes(const Point& point) const { Array* arr = Array::create(); - cpSpaceNearestPointQuery(this->_info->space, + cpSpaceNearestPointQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, @@ -867,16 +867,16 @@ Array* PhysicsWorld::getShapesAtPoint(Point point) const return arr; } -PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) const +PhysicsShape* PhysicsWorld::getShape(const Point& point) const { - cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->space, + cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, CP_NO_GROUP, nullptr); - return shape == nullptr ? nullptr : PhysicsShapeInfo::map.find(shape)->second->shape; + return shape == nullptr ? nullptr : PhysicsShapeInfo::getMap().find(shape)->second->getShape(); } Array* PhysicsWorld::getAllBodies() const @@ -884,7 +884,7 @@ Array* PhysicsWorld::getAllBodies() const return _bodies; } -PhysicsBody* PhysicsWorld::getBodyByTag(int tag) const +PhysicsBody* PhysicsWorld::getBody(int tag) const { for (auto body : *_bodies) { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 360844db3f..e4cad6e7eb 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -77,7 +77,7 @@ public: * @param normal the normal vector at the point of intersection * @return true to continue, false to terminate */ - std::function report; + std::function report; }; class PhysicsRectQueryCallback @@ -106,15 +106,15 @@ public: virtual void removeAllJoints(); virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); + virtual void removeBody(int tag); virtual void removeAllBodies(); - void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); - void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); - Array* getShapesAtPoint(Point point) const; - PhysicsShape* getShapeAtPoint(Point point) const; + void rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data); + void rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data); + Array* getShapes(const Point& point) const; + PhysicsShape* getShape(const Point& point) const; Array* getAllBodies() const; - PhysicsBody* getBodyByTag(int tag) const; + PhysicsBody* getBody(int tag) const; /** Register a listener to receive contact callbacks*/ //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 42ce5cc7ec..79ad011c17 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -27,18 +27,13 @@ NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() -: body(nullptr) +: _body(nullptr) { } PhysicsBodyInfo::~PhysicsBodyInfo() { - if (body) cpBodyFree(body); -} - -Clonable* PhysicsBodyInfo::clone() const -{ - return nullptr; + if (_body) cpBodyFree(_body); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index 19e43c23fb..dd2d276ac5 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -34,16 +34,18 @@ NS_CC_BEGIN -class PhysicsBodyInfo : public Clonable +class PhysicsBodyInfo { public: - cpBody* body; + inline cpBody* getBody() const { return _body; } + inline void setBody(cpBody* body) { _body = body; } private: PhysicsBodyInfo(); ~PhysicsBodyInfo(); - Clonable* clone() const override; +private: + cpBody* _body; friend class PhysicsBody; }; diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index 283a4998ab..150c77a030 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -27,7 +27,7 @@ NS_CC_BEGIN PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact) -: contact(contact) +: _contact(contact) { } diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 7dc6561fec..4b01ad9d53 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -36,12 +36,15 @@ class PhysicsContact; class PhysicsContactInfo { public: - PhysicsContact* contact; + inline PhysicsContact* getContact() const { return _contact; } private: PhysicsContactInfo(PhysicsContact* contact); ~PhysicsContactInfo(); +private: + PhysicsContact* _contact; + friend class PhysicsContact; }; diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index 82053ce4b1..2f8b7817cf 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -27,16 +27,16 @@ #include NS_CC_BEGIN -std::map PhysicsJointInfo::map; +std::map PhysicsJointInfo::_map; PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) -: joint(joint) +: _joint(joint) { } PhysicsJointInfo::~PhysicsJointInfo() { - for (cpConstraint* joint : joints) + for (cpConstraint* joint : _joints) { cpConstraintFree(joint); } @@ -46,21 +46,21 @@ void PhysicsJointInfo::add(cpConstraint* joint) { if (joint == nullptr) return; - joints.push_back(joint); - map.insert(std::pair(joint, this)); + _joints.push_back(joint); + _map.insert(std::pair(joint, this)); } void PhysicsJointInfo::remove(cpConstraint* joint) { if (joint == nullptr) return; - auto it = std::find(joints.begin(), joints.end(), joint); - if (it != joints.end()) + auto it = std::find(_joints.begin(), _joints.end(), joint); + if (it != _joints.end()) { - joints.erase(it); + _joints.erase(it); - auto mit = map.find(joint); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(joint); + if (mit != _map.end()) _map.erase(mit); cpConstraintFree(joint); } @@ -68,14 +68,14 @@ void PhysicsJointInfo::remove(cpConstraint* joint) void PhysicsJointInfo::removeAll() { - for (cpConstraint* joint : joints) + for (cpConstraint* joint : _joints) { - auto mit = map.find(joint); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(joint); + if (mit != _map.end()) _map.erase(mit); cpConstraintFree(joint); } - joints.clear(); + _joints.clear(); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 8116c48eae..016cd74d12 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -43,15 +43,19 @@ public: void remove(cpConstraint* shape); void removeAll(); -public: - std::vector joints; - PhysicsJoint* joint; - static std::map map; + PhysicsJoint* getJoint() const { return _joint; } + std::vector& getJoints() { return _joints; } + static std::map& getMap() { return _map; } private: PhysicsJointInfo(PhysicsJoint* joint); ~PhysicsJointInfo(); +private: + std::vector _joints; + PhysicsJoint* _joint; + static std::map _map; + friend class PhysicsJoint; }; diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index 74abfc75f1..d12a053181 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -27,27 +27,27 @@ #include NS_CC_BEGIN -std::map PhysicsShapeInfo::map; -cpBody* PhysicsShapeInfo::shareBody = nullptr; +std::map PhysicsShapeInfo::_map; +cpBody* PhysicsShapeInfo::_sharedBody = nullptr; PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) -: shape(shape) -, group(CP_NO_GROUP) +: _shape(shape) +, _group(CP_NO_GROUP) { - if (shareBody == nullptr) + if (_sharedBody == nullptr) { - shareBody = cpBodyNewStatic(); + _sharedBody = cpBodyNewStatic(); } - body = shareBody; + _body = _sharedBody; } PhysicsShapeInfo::~PhysicsShapeInfo() { - for (auto shape : shapes) + for (auto shape : _shapes) { - auto it = map.find(shape); - if (it != map.end()) map.erase(shape); + auto it = _map.find(shape); + if (it != _map.end()) _map.erase(shape); cpShapeFree(shape); } @@ -55,9 +55,9 @@ PhysicsShapeInfo::~PhysicsShapeInfo() void PhysicsShapeInfo::setGroup(cpGroup group) { - this->group = group; + this->_group = group; - for (cpShape* shape : shapes) + for (cpShape* shape : _shapes) { cpShapeSetGroup(shape, group); } @@ -65,12 +65,12 @@ void PhysicsShapeInfo::setGroup(cpGroup group) void PhysicsShapeInfo::setBody(cpBody* body) { - if (this->body != body) + if (this->_body != body) { - this->body = body; - for (cpShape* shape : shapes) + this->_body = body; + for (cpShape* shape : _shapes) { - cpShapeSetBody(shape, body == nullptr ? shareBody : body); + cpShapeSetBody(shape, body == nullptr ? _sharedBody : body); } } } @@ -79,22 +79,22 @@ void PhysicsShapeInfo::add(cpShape* shape) { if (shape == nullptr) return; - cpShapeSetGroup(shape, group); - shapes.push_back(shape); - map.insert(std::pair(shape, this)); + cpShapeSetGroup(shape, _group); + _shapes.push_back(shape); + _map.insert(std::pair(shape, this)); } void PhysicsShapeInfo::remove(cpShape* shape) { if (shape == nullptr) return; - auto it = std::find(shapes.begin(), shapes.end(), shape); - if (it != shapes.end()) + auto it = std::find(_shapes.begin(), _shapes.end(), shape); + if (it != _shapes.end()) { - shapes.erase(it); + _shapes.erase(it); - auto mit = map.find(shape); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(shape); + if (mit != _map.end()) _map.erase(mit); cpShapeFree(shape); } @@ -102,14 +102,14 @@ void PhysicsShapeInfo::remove(cpShape* shape) void PhysicsShapeInfo::removeAll() { - for (cpShape* shape : shapes) + for (cpShape* shape : _shapes) { - auto mit = map.find(shape); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(shape); + if (mit != _map.end()) _map.erase(mit); cpShapeFree(shape); } - shapes.clear(); + _shapes.clear(); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 83be655b02..b519fd378a 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -47,17 +47,25 @@ public: void setBody(cpBody* body); public: - std::vector shapes; - PhysicsShape* shape; - cpBody* body; - cpGroup group; - static std::map map; - static cpBody* shareBody; + PhysicsShape* getShape() const { return _shape; } + std::vector& getShapes() { return _shapes; } + cpBody* getBody() const { return _body; } + cpGroup getGourp() const { return _group; } + static std::map& getMap() { return _map; } + static cpBody* getSharedBody() { return _sharedBody; } private: PhysicsShapeInfo(PhysicsShape* shape); ~PhysicsShapeInfo(); +private: + std::vector _shapes; + PhysicsShape* _shape; + cpBody* _body; + cpGroup _group; + static std::map _map; + static cpBody* _sharedBody; + friend class PhysicsShape; }; diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index fecf2009aa..a12e473ec1 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -29,12 +29,12 @@ NS_CC_BEGIN #define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ void PhysicsWorldInfo::add##name(cp##type* data) \ { \ - if (!cpSpaceContains##type(space, data)) cpSpaceAdd##type(space, data); \ + if (!cpSpaceContains##type(_space, data)) cpSpaceAdd##type(_space, data); \ } \ \ void PhysicsWorldInfo::remove##name(cp##type* data) \ { \ - if (cpSpaceContains##type(space, data)) cpSpaceRemove##type(space, data); \ + if (cpSpaceContains##type(_space, data)) cpSpaceRemove##type(_space, data); \ } \ PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) @@ -43,12 +43,12 @@ PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) PhysicsWorldInfo::PhysicsWorldInfo() { - space = cpSpaceNew(); + _space = cpSpaceNew(); } PhysicsWorldInfo::~PhysicsWorldInfo() { - cpSpaceFree(space); + cpSpaceFree(_space); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 5e6c78bc97..b50e1a3240 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -36,8 +36,7 @@ NS_CC_BEGIN class PhysicsWorldInfo { public: - cpSpace* space; - + cpSpace* getSpace() const { return _space; } void addShape(cpShape* shape); void removeShape(cpShape* shape); void addBody(cpBody* body); @@ -49,6 +48,9 @@ private: PhysicsWorldInfo(); ~PhysicsWorldInfo(); +private: + cpSpace* _space; + friend class PhysicsWorld; }; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 99ce9d0c90..88b17e365e 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -602,7 +602,7 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data) { *((Point*)data) = info.contact; return false; @@ -620,7 +620,7 @@ private: PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() : _friction(1.0f) { - report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool + report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool { if (_friction > info.fraction) { @@ -650,7 +650,7 @@ public: PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() : num(0) { - report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool + report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool { if (num < MAX_MULTI_RAYCAST_NUM) { @@ -1089,7 +1089,7 @@ void PhysicsDemoSlice::onEnter() addChild(box); } -bool PhysicsDemoSlice::slice(PhysicsWorld &world, PhysicsRayCastCallback::Info &info, void *data) +bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastCallback::Info &info, void *data) { if (info.shape->getBody()->getTag() != _sliceTag) { @@ -1150,6 +1150,8 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float polyon->setAngularVelocity(body->getAngularVelocity()); polyon->setTag(_sliceTag); addChild(node); + + delete[] points; } void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) @@ -1171,7 +1173,7 @@ std::string PhysicsDemoSlice::subtitle() void PhysicsDemoWater::onEnter() { - + PhysicsDemo::onEnter(); } std::string PhysicsDemoWater::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 425dbc56f9..7355045cad 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -96,7 +96,7 @@ public: void changeModeCallback(Object* sender); - bool anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); + bool anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); private: float _angle; @@ -150,7 +150,7 @@ public: std::string title() override; std::string subtitle() override; - bool slice(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); + bool slice(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); bool onTouchBegan(Touch *touch, Event *event); From 8b86373b08ccc2126c8cb1eac4e6ae59331bc325 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 20:33:29 +0800 Subject: [PATCH 074/197] 1.Change to range-based loop --- .../cocostudio/CCArmatureDataManager.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index c8278387ce..0e139ef560 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -115,24 +115,24 @@ void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) { if (RelativeData *data = getRelativeData(configFilePath)) { - for (std::vector::iterator i = data->armatures.begin(); i != data->armatures.end(); i++) + for (std::string str : data->armatures) { - removeArmatureData(i->c_str()); + removeArmatureData(str.c_str()); } - for (std::vector::iterator i = data->animations.begin(); i != data->animations.end(); i++) + for (std::string str : data->animations) { - removeAnimationData(i->c_str()); + removeAnimationData(str.c_str()); } - for (std::vector::iterator i = data->textures.begin(); i != data->textures.end(); i++) + for (std::string str : data->textures) { - removeTextureData(i->c_str()); + removeTextureData(str.c_str()); } - for (std::vector::iterator i = data->plistFiles.begin(); i != data->plistFiles.end(); i++) + for (std::string str : data->plistFiles) { - SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(i->c_str()); + SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(str.c_str()); } _relativeDatas.erase(configFilePath); From 471dd07f3b33074755807a3b95e29f0497523975 Mon Sep 17 00:00:00 2001 From: Chris Hannon Date: Tue, 5 Nov 2013 15:54:31 -0500 Subject: [PATCH 075/197] [android] update nativeactivity.cpp to work with changes made in commit 0220f27 (AMD support), changing int to long int for the second argument in most touch callbacks --- cocos/2d/platform/android/nativeactivity.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index 5ac17a5ee5..12e25d597d 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -292,7 +292,7 @@ static void engine_term_display(struct engine* engine) { /* * Get X, Y positions and ID's for all pointers */ -static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { +static void getTouchPos(AInputEvent *event, long ids[], float xs[], float ys[]) { int pointerCount = AMotionEvent_getPointerCount(event); for(int i = 0; i < pointerCount; ++i) { ids[i] = AMotionEvent_getPointerId(event, i); @@ -321,7 +321,7 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -340,7 +340,7 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -353,10 +353,10 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; + long ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); return 1; } break; @@ -369,7 +369,7 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -387,7 +387,7 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", xP, yP, pointerIndex); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -400,10 +400,10 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; + long ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); return 1; } break; From 84a6aa29cd61e7624830f1461d6aa00047d0a934 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 5 Nov 2013 17:36:44 -0800 Subject: [PATCH 076/197] Adds more 64-bit fixes Replaces more `int` with `long` where it makes sense. Also , it repalces some `unsigned long` with `long` for "lenght" values as described in our c++ guideline --- cocos/2d/CCDirector.cpp | 4 +- cocos/2d/CCDirector.h | 2 +- cocos/2d/CCFontFreeType.cpp | 4 +- cocos/2d/CCTextureCache.cpp | 6 +-- cocos/2d/CCUserDefault.cpp | 2 +- cocos/2d/CCUserDefault.mm | 4 +- cocos/2d/TGAlib.cpp | 10 ++--- cocos/2d/ZipUtils.cpp | 28 +++++++------- cocos/2d/ZipUtils.h | 20 +++++----- cocos/2d/platform/CCFileUtils.cpp | 4 +- cocos/2d/platform/CCFileUtils.h | 4 +- cocos/2d/platform/CCImage.h | 4 +- cocos/2d/platform/CCImageCommon_cpp.h | 28 +++++++------- cocos/2d/platform/CCSAXParser.cpp | 8 ++-- cocos/base/CCString.cpp | 38 +++++++++---------- .../editor-support/cocosbuilder/CCBReader.cpp | 2 +- .../cocosbuilder/CCNodeLoader.cpp | 2 +- .../cocostudio/CCDataReaderHelper.cpp | 4 +- .../cocostudio/CCSGUIReader.cpp | 4 +- .../cocostudio/CCSSceneReader.cpp | 8 ++-- cocos/editor-support/spine/spine-cocos2dx.cpp | 2 +- .../javascript/bindings/ScriptingCore.cpp | 2 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 23 files changed, 96 insertions(+), 96 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 7255659d07..130d170d30 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -831,7 +831,7 @@ void Director::calculateMPF() } // returns the FPS image data pointer and len -void Director::getFPSImageData(unsigned char** datapointer, unsigned int* length) +void Director::getFPSImageData(unsigned char** datapointer, long* length) { // XXX fixed me if it should be used *datapointer = cc_fps_images_png; @@ -855,7 +855,7 @@ void Director::createStatsLabel() Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); unsigned char *data = nullptr; - unsigned int dataLength = 0; + long dataLength = 0; getFPSImageData(&data, &dataLength); Image* image = new Image(); diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 5f0d6eb0a8..b01b0fe954 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -376,7 +376,7 @@ protected: void showStats(); void createStatsLabel(); void calculateMPF(); - void getFPSImageData(unsigned char** datapointer, unsigned int* length); + void getFPSImageData(unsigned char** datapointer, long* length); /** calculates delta time since last time it was called */ void calculateDeltaTime(); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 0e4e49d96f..5e2173204f 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -99,8 +99,8 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) { FT_Face face; - int len = 0; - _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len)); + long len = 0; + _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len); if (!_ttfData) return false; diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 95c02f8ff4..8f3fc6fe3a 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -614,10 +614,10 @@ void VolatileTexture::reloadAllTextures() case kImageFile: { Image* image = new Image(); - unsigned long nSize = 0; - unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &nSize); + long size = 0; + unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &size); - if (image && image->initWithImageData(pBuffer, nSize)) + if (image && image->initWithImageData(pBuffer, size)) { Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat); diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index 5a85d65b41..2104051f76 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -58,7 +58,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; //CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt"); - unsigned long nSize; + long nSize; const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) diff --git a/cocos/2d/CCUserDefault.mm b/cocos/2d/CCUserDefault.mm index b55acfcf24..da1c8827fd 100644 --- a/cocos/2d/CCUserDefault.mm +++ b/cocos/2d/CCUserDefault.mm @@ -73,8 +73,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - unsigned long nSize; - const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); + long size; + const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) { diff --git a/cocos/2d/TGAlib.cpp b/cocos/2d/TGAlib.cpp index ba4ca83b01..8725e765cb 100644 --- a/cocos/2d/TGAlib.cpp +++ b/cocos/2d/TGAlib.cpp @@ -198,8 +198,8 @@ tImageTGA * tgaLoad(const char *filename) int mode,total; tImageTGA *info = NULL; - unsigned long nSize = 0; - unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &nSize); + long size = 0; + unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &size); do { @@ -207,7 +207,7 @@ tImageTGA * tgaLoad(const char *filename) info = (tImageTGA *)malloc(sizeof(tImageTGA)); // get the file header info - if (! tgaLoadHeader(pBuffer, nSize, info)) + if (! tgaLoadHeader(pBuffer, size, info)) { info->status = TGA_ERROR_MEMORY; break; @@ -245,11 +245,11 @@ tImageTGA * tgaLoad(const char *filename) // finally load the image pixels if ( info->type == 10 ) { - bLoadImage = tgaLoadRLEImageData(pBuffer, nSize, info); + bLoadImage = tgaLoadRLEImageData(pBuffer, size, info); } else { - bLoadImage = tgaLoadImageData(pBuffer, nSize, info); + bLoadImage = tgaLoadImageData(pBuffer, size, info); } // check for errors when reading the pixels diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index db2fab18ce..2e5d9fe43f 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -39,7 +39,7 @@ bool ZipUtils::s_bEncryptionKeyIsValid = false; // --------------------- ZipUtils --------------------- -inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len) +inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, long len) { const int enclen = 1024; const int securelen = 512; @@ -108,7 +108,7 @@ inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len) } } -inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len) +inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, long len) { unsigned int cs = 0; const int cslen = 128; @@ -127,12 +127,12 @@ inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len) // Should buffer factor be 1.5 instead of 2 ? #define BUFFER_INC_FACTOR (2) -int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, unsigned int outLenghtHint) +int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint) { /* ret value */ int err = Z_OK; - int bufferSize = outLenghtHint; + long bufferSize = outLenghtHint; *out = new unsigned char[bufferSize]; z_stream d_stream; /* decompression stream */ @@ -192,9 +192,9 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, return err; } -int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLengthHint) +int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint) { - unsigned int outLength = 0; + long outLength = 0; int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); if (err != Z_OK || *out == NULL) { @@ -223,7 +223,7 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, return outLength; } -int ZipUtils::ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out) +int ZipUtils::ccInflateMemory(unsigned char *in, long inLength, unsigned char **out) { // 256k for hint return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024); @@ -304,7 +304,7 @@ bool ZipUtils::ccIsCCZFile(const char *path) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -316,7 +316,7 @@ bool ZipUtils::ccIsCCZFile(const char *path) return ccIsCCZBuffer(compressed, fileLen); } -bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, int len) +bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, long len) { if (len < sizeof(struct CCZHeader)) { @@ -333,7 +333,7 @@ bool ZipUtils::ccIsGZipFile(const char *path) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -345,7 +345,7 @@ bool ZipUtils::ccIsGZipFile(const char *path) return ccIsGZipBuffer(compressed, fileLen); } -bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, int len) +bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, long len) { if (len < 2) { @@ -356,7 +356,7 @@ bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, int len) } -int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, int bufferLen, unsigned char **out) +int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsigned char **out) { struct CCZHeader *header = (struct CCZHeader*) buffer; @@ -454,7 +454,7 @@ int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -582,7 +582,7 @@ bool ZipFile::fileExists(const std::string &fileName) const return ret; } -unsigned char *ZipFile::getFileData(const std::string &fileName, unsigned long *pSize) +unsigned char *ZipFile::getFileData(const std::string &fileName, long *pSize) { unsigned char * pBuffer = NULL; if (pSize) diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index 5564807540..48552502b4 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -64,7 +64,7 @@ namespace cocos2d * @since v0.8.1 */ - static int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out); + static int ccInflateMemory(unsigned char *in, long inLength, unsigned char **out); /** * Inflates either zlib or gzip deflated memory. The inflated memory is @@ -76,7 +76,7 @@ namespace cocos2d * @since v1.0.0 */ - static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLenghtHint); + static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLenghtHint); /** inflates a GZip file into memory * @@ -100,7 +100,7 @@ namespace cocos2d * * @since v3.0 */ - static bool ccIsGZipBuffer(const unsigned char *buffer, int len); + static bool ccIsGZipBuffer(const unsigned char *buffer, long len); /** inflates a CCZ file into memory * @@ -116,7 +116,7 @@ namespace cocos2d * * @since v3.0 */ - static int ccInflateCCZBuffer(const unsigned char *buffer, int len, unsigned char **out); + static int ccInflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out); /** test a file is a CCZ format file or not * @@ -132,7 +132,7 @@ namespace cocos2d * * @since v3.0 */ - static bool ccIsCCZBuffer(const unsigned char *buffer, int len); + static bool ccIsCCZBuffer(const unsigned char *buffer, long len); /** Sets the pvr.ccz encryption key parts separately for added * security. @@ -187,10 +187,10 @@ namespace cocos2d static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); private: - static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, - unsigned int outLenghtHint); - static inline void ccDecodeEncodedPvr (unsigned int *data, int len); - static inline unsigned int ccChecksumPvr(const unsigned int *data, int len); + static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, + long outLenghtHint); + static inline void ccDecodeEncodedPvr (unsigned int *data, long len); + static inline unsigned int ccChecksumPvr(const unsigned int *data, long len); static unsigned int s_uEncryptedPvrKeyParts[4]; static unsigned int s_uEncryptionKey[1024]; @@ -253,7 +253,7 @@ namespace cocos2d * * @since v2.0.5 */ - unsigned char *getFileData(const std::string &fileName, unsigned long *pSize); + unsigned char *getFileData(const std::string &fileName, long *size); private: /** Internal data like zip file pointer / file list array and so on */ diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index d7244ba6f0..6760432cad 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -488,7 +488,7 @@ void FileUtils::purgeCachedEntries() _fullPathCache.clear(); } -unsigned char* FileUtils::getFileData(const char* filename, const char* mode, unsigned long * size) +unsigned char* FileUtils::getFileData(const char* filename, const char* mode, long *size) { unsigned char * buffer = NULL; CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); @@ -518,7 +518,7 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, un return buffer; } -unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long * size) +unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, long *size) { unsigned char * buffer = NULL; unzFile pFile = NULL; diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 299807af01..855f016fe5 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -88,7 +88,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size); + virtual unsigned char* getFileData(const char* filename, const char* mode, long *size); /** * Gets resource file data from a zip file. @@ -98,7 +98,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long *size); + virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, long *size); /** Returns the fullpath for a given filename. diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index 25f09dade2..1f2e04ced7 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -119,10 +119,10 @@ public: * @js NA * @lua NA */ - bool initWithImageData(const unsigned char * data, int dataLen); + bool initWithImageData(const unsigned char * data, long dataLen); // @warning kFmtRawData only support RGBA8888 - bool initWithRawData(const unsigned char * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti = false); + bool initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti = false); /** @brief Create image with specified string. diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index be7480a0ae..f2fc7a9a08 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -416,7 +416,7 @@ bool Image::initWithImageFile(const char * strPath) SDL_FreeSurface(iSurf); #else - unsigned long bufferLen = 0; + long bufferLen = 0; unsigned char* buffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "rb", &bufferLen); if (buffer != nullptr && bufferLen > 0) @@ -432,23 +432,23 @@ bool Image::initWithImageFile(const char * strPath) bool Image::initWithImageFileThreadSafe(const char *fullpath) { - bool bRet = false; - unsigned long dataLen = 0; + bool ret = false; + long dataLen = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) FileUtilsAndroid *fileUitls = (FileUtilsAndroid*)FileUtils::getInstance(); - unsigned char *pBuffer = fileUitls->getFileDataForAsync(fullpath, "rb", &dataLen); + unsigned char *buffer = fileUitls->getFileDataForAsync(fullpath, "rb", &dataLen); #else - unsigned char *pBuffer = FileUtils::getInstance()->getFileData(fullpath, "rb", &dataLen); + unsigned char *buffer = FileUtils::getInstance()->getFileData(fullpath, "rb", &dataLen); #endif - if (pBuffer != NULL && dataLen > 0) + if (buffer != NULL && dataLen > 0) { - bRet = initWithImageData(pBuffer, dataLen); + ret = initWithImageData(buffer, dataLen); } - CC_SAFE_DELETE_ARRAY(pBuffer); - return bRet; + CC_SAFE_DELETE_ARRAY(buffer); + return ret; } -bool Image::initWithImageData(const unsigned char * data, int dataLen) +bool Image::initWithImageData(const unsigned char * data, long dataLen) { bool ret = false; @@ -1190,13 +1190,13 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) if (!testFormatForPvr2TCSupport(formatFlags)) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end()) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } @@ -1204,7 +1204,7 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) if (it == Texture2D::getPixelFormatInfoMap().end()) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } @@ -1757,7 +1757,7 @@ bool Image::initWithWebpData(const unsigned char * data, int dataLen) return bRet; } -bool Image::initWithRawData(const unsigned char * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti) +bool Image::initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti) { bool bRet = false; do diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 0f823f938d..04201557c1 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -114,15 +114,15 @@ bool SAXParser::parse(const char* pXMLData, unsigned int uDataLength) bool SAXParser::parse(const char *pszFile) { - bool bRet = false; - unsigned long size = 0; + bool ret = false; + long size = 0; char* pBuffer = (char*)FileUtils::getInstance()->getFileData(pszFile, "rt", &size); if (pBuffer != NULL && size > 0) { - bRet = parse(pBuffer, size); + ret = parse(pBuffer, size); } CC_SAFE_DELETE_ARRAY(pBuffer); - return bRet; + return ret; } void SAXParser::startElement(void *ctx, const CC_XML_CHAR *name, const CC_XML_CHAR **atts) diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index f9962b1ba4..67193eb52c 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -216,15 +216,15 @@ bool String::isEqual(const Object* pObject) String* String::create(const std::string& str) { - String* pRet = new String(str); - pRet->autorelease(); - return pRet; + String* ret = new String(str); + ret->autorelease(); + return ret; } -String* String::createWithData(const unsigned char* pData, unsigned long nLen) +String* String::createWithData(const unsigned char* data, unsigned long nLen) { - String* pRet = NULL; - if (pData != NULL) + String* ret = NULL; + if (data != NULL) { char* pStr = (char*)malloc(nLen+1); if (pStr != NULL) @@ -232,36 +232,36 @@ String* String::createWithData(const unsigned char* pData, unsigned long nLen) pStr[nLen] = '\0'; if (nLen > 0) { - memcpy(pStr, pData, nLen); + memcpy(pStr, data, nLen); } - pRet = String::create(pStr); + ret = String::create(pStr); free(pStr); } } - return pRet; + return ret; } String* String::createWithFormat(const char* format, ...) { - String* pRet = String::create(""); + String* ret = String::create(""); va_list ap; va_start(ap, format); - pRet->initWithFormatAndValist(format, ap); + ret->initWithFormatAndValist(format, ap); va_end(ap); - return pRet; + return ret; } String* String::createWithContentsOfFile(const char* filename) { - unsigned long size = 0; - unsigned char* pData = 0; - String* pRet = NULL; - pData = FileUtils::getInstance()->getFileData(filename, "rb", &size); - pRet = String::createWithData(pData, size); - CC_SAFE_DELETE_ARRAY(pData); - return pRet; + long size = 0; + unsigned char* data = 0; + String* ret = NULL; + data = FileUtils::getInstance()->getFileData(filename, "rb", &size); + ret = String::createWithData(data, size); + CC_SAFE_DELETE_ARRAY(data); + return ret; } void String::acceptVisitor(DataVisitor &visitor) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 938c595f46..154d2b0b36 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -244,7 +244,7 @@ Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, } std::string strPath = FileUtils::getInstance()->fullPathForFilename(strCCBFileName.c_str()); - unsigned long size = 0; + long size = 0; unsigned char * pBytes = FileUtils::getInstance()->getFileData(strPath.c_str(), "rb", &size); Data *data = new Data(pBytes, size); diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index f1aedc7104..e82764ce86 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -918,7 +918,7 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader // Load sub file std::string path = FileUtils::getInstance()->fullPathForFilename(ccbFileName.c_str()); - unsigned long size = 0; + long size = 0; unsigned char * pBytes = FileUtils::getInstance()->getFileData(path.c_str(), "rb", &size); CCBReader * reader = new CCBReader(pCCBReader); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 4749f5eaf9..b03d2b1f1f 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -298,7 +298,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) size_t startPos = filePathStr.find_last_of("."); std::string str = &filePathStr[startPos]; - unsigned long size; + long size; std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); @@ -389,7 +389,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target std::string str = &filePathStr[startPos]; std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - unsigned long size; + long size; data->fileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); if (str.compare(".xml") == 0) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 77cb5d56de..5e199edbbc 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -207,7 +207,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) JsonDictionary *jsonDict = NULL; jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName); - unsigned long size = 0; + long size = 0; des = (char*)(FileUtils::getInstance()->getFileData(jsonpath.c_str(),"r" , &size)); if(NULL == des || strcmp(des, "") == 0) { @@ -225,7 +225,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) } int texturesCount = DICTOOL->getArrayCount_json(jsonDict, "textures"); - int pos = jsonpath.find_last_of('/'); + long pos = jsonpath.find_last_of('/'); m_strFilePath = jsonpath.substr(0,pos+1); for (int i=0; igetFileData(pPath.c_str(),"r" , &size)); JsonDictionary *jsonDict = new JsonDictionary(); jsonDict->initWithDescription(des); @@ -227,7 +227,7 @@ namespace cocostudio { const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); - for (int i = 0; i < childrenCount; ++i) + for (long i = 0; i < childrenCount; ++i) { const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", i); std::string plistpath; @@ -283,7 +283,7 @@ namespace cocostudio { if (nResType == 0) { pAttribute = ComAttribute::create(); - unsigned long size = 0; + long size = 0; const char* pData = 0; pData = (char*)(cocos2d::FileUtils::getInstance()->getFileData(pPath.c_str(), "r", &size)); if(pData != NULL && strcmp(pData, "") != 0) diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index cd9ea67e30..dbc389db51 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -47,7 +47,7 @@ void _AtlasPage_disposeTexture (AtlasPage* self) { } char* _Util_readFile (const char* path, int* length) { - unsigned long size; + long size; char* data = reinterpret_cast(FileUtils::getInstance()->getFileData( FileUtils::getInstance()->fullPathForFilename(path).c_str(), "r", &size)); *length = size; diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 5d902c1c23..1f7f01c566 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -527,7 +527,7 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; - unsigned long length = 0; + long length = 0; unsigned char* data = futil->getFileData(byteCodePath.c_str(), "rb", &length); diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 39e01fd1ef..071cbc433d 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -c93df276adb92b5e076db49c4f9482b8eb37d45c \ No newline at end of file +827b30175daeeaa135581f3546d5458db6d9dcdf \ No newline at end of file From 8b1d3af720c334546f7d1cb4cf86d4bbddd66b6f Mon Sep 17 00:00:00 2001 From: Luis Parravicini Date: Tue, 5 Nov 2013 23:55:24 -0300 Subject: [PATCH 077/197] added | operator for Control::EventType --- .../GUI/CCControlExtension/CCControl.cpp | 5 +++++ extensions/GUI/CCControlExtension/CCControl.h | 2 ++ .../CCControlButtonTest.cpp | 19 ++++++++++++++++++- .../CCControlButtonTest/CCControlButtonTest.h | 2 ++ 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 13d86e629c..15fe7b1a8d 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -326,4 +326,9 @@ bool Control::hasVisibleParents() const } return true; } + +Control::EventType operator|(Control::EventType a, Control::EventType b) { + return static_cast(static_cast(a) | static_cast(b)); +} + NS_CC_EXT_END diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index d8644a516f..12533f7041 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -262,6 +262,8 @@ protected: CC_SYNTHESIZE_READONLY(State, _state, State); }; +Control::EventType operator|(Control::EventType a, Control::EventType b); + // end of GUI group /// @} /// @} diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp index a7fe134383..d5914b2db1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp @@ -110,6 +110,7 @@ ControlButton *ControlButtonTest_HelloVariableSize::standardButtonWithTitle(cons ControlButtonTest_Event::ControlButtonTest_Event() : _displayValueLabel(NULL) +, _displayBitmaskLabel(NULL) { } @@ -117,6 +118,7 @@ ControlButtonTest_Event::ControlButtonTest_Event() ControlButtonTest_Event::~ControlButtonTest_Event() { CC_SAFE_RELEASE_NULL(_displayValueLabel); + CC_SAFE_RELEASE_NULL(_displayBitmaskLabel); } bool ControlButtonTest_Event::init() @@ -130,7 +132,13 @@ bool ControlButtonTest_Event::init() _displayValueLabel->setAnchorPoint(Point(0.5f, -1)); _displayValueLabel->setPosition(Point(screenSize.width / 2.0f, screenSize.height / 2.0f)); addChild(_displayValueLabel, 1); - + + setDisplayBitmaskLabel(LabelTTF::create("No bitmask event", "Marker Felt", 24)); + _displayBitmaskLabel->setAnchorPoint(Point(0.5f, -1)); + Point bitmaskLabelPos = _displayValueLabel->getPosition() - Point(0, _displayBitmaskLabel->getBoundingBox().size.height); + _displayBitmaskLabel->setPosition(bitmaskLabelPos); + addChild(_displayBitmaskLabel, 1); + // Add the button auto backgroundButton = Scale9Sprite::create("extensions/button.png"); auto backgroundHighlightedButton = Scale9Sprite::create("extensions/buttonHighlighted.png"); @@ -162,11 +170,20 @@ bool ControlButtonTest_Event::init() controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchUpInsideAction), Control::EventType::TOUCH_UP_INSIDE); controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchUpOutsideAction), Control::EventType::TOUCH_UP_OUTSIDE); controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchCancelAction), Control::EventType::TOUCH_CANCEL); + // test for issue 2882 + controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchBitmaskAction), + Control::EventType::TOUCH_DOWN | Control::EventType::DRAG_INSIDE | Control::EventType::DRAG_OUTSIDE | Control::EventType::DRAG_ENTER | Control::EventType::DRAG_EXIT | Control::EventType::TOUCH_UP_INSIDE | Control::EventType::TOUCH_UP_OUTSIDE | Control::EventType::TOUCH_CANCEL | Control::EventType::VALUE_CHANGED); + return true; } return false; } +void ControlButtonTest_Event::touchBitmaskAction(Object *senderz, Control::EventType controlEvent) +{ + _displayBitmaskLabel->setString(String::createWithFormat("using bitmask (%d)", controlEvent)->getCString()); +} + void ControlButtonTest_Event::touchDownAction(Object *senderz, Control::EventType controlEvent) { _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h index 6e4d602107..1efbf9c604 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h @@ -54,8 +54,10 @@ public: void touchUpInsideAction(Object *sender, Control::EventType controlEvent); void touchUpOutsideAction(Object *sender, Control::EventType controlEvent); void touchCancelAction(Object *sender, Control::EventType controlEvent); + void touchBitmaskAction(Object *sender, Control::EventType controlEvent); protected: CC_SYNTHESIZE_RETAIN(LabelTTF *, _displayValueLabel, DisplayValueLabel) + CC_SYNTHESIZE_RETAIN(LabelTTF *, _displayBitmaskLabel, DisplayBitmaskLabel) CONTROL_SCENE_CREATE_FUNC(ControlButtonTest_Event) }; From c364c4f083c815b133f7f5580e2345b8112b3f77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 10:55:39 +0800 Subject: [PATCH 078/197] issue #3113: Updating CMakeLists.txt, Improve Copying files. --- build/BuildHelpers.CMakeLists.txt | 60 +++++------------------------ samples/Cpp/HelloCpp/CMakeLists.txt | 5 ++- samples/Cpp/TestCpp/CMakeLists.txt | 5 ++- samples/Lua/HelloLua/CMakeLists.txt | 8 ++-- samples/Lua/TestLua/CMakeLists.txt | 11 +++--- 5 files changed, 27 insertions(+), 62 deletions(-) diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt index 92d537dd7d..6e848d4f29 100644 --- a/build/BuildHelpers.CMakeLists.txt +++ b/build/BuildHelpers.CMakeLists.txt @@ -1,53 +1,13 @@ -# This file was copied from GamePlay -# Copies files for the given game into the target res directory -# GAME_NAME name of the game -# REL_DIR to which directory these files are relative -# SRC_FILES which files from the REL_DIR to copy (GLOB) -macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES) - file( GLOB_RECURSE RES_FILES RELATIVE ${REL_DIR} ${SRC_FILES} ) +macro(pre_build TARGET_NAME) + add_custom_target( ${TARGET_NAME}_PRE_BUILD ALL ) - set(ALL_FILES) - foreach(SRC_FILE ${RES_FILES}) - IF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) - add_custom_command( - OUTPUT "${APP_BIN_DIR}/${SRC_FILE}" - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${REL_DIR}/${SRC_FILE}" - "${APP_BIN_DIR}/Resources/${SRC_FILE}" - COMMENT "Copy ${SRC_FILE}" - ) - list(APPEND ALL_FILES "${APP_BIN_DIR}/${SRC_FILE}" ) - ENDIF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) - endforeach() - # create target for copying these files - add_custom_target( ${GAME_RES_TARGET} DEPENDS ${ALL_FILES} ) -endmacro() + add_custom_command( + TARGET ${TARGET_NAME}_PRE_BUILD + ${ARGN} + PRE_BUILD + COMMENT "${TARGET_NAME}_PRE_BUILD ..." + ) -# convenience to call above with current directory and everything in "res" -macro(COPY_RES GAME_NAME) - # a target for all addition asserts (will be done in default compile, but if you target the executable - # it won't be done -- good for testing) - add_custom_target( ${GAME_NAME}_ASSETS ALL ) - - # copy entire "res" directory and "game.config" if there is one - set(CRG_PATTERN "*") - COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_CORE_RES - ${CMAKE_CURRENT_SOURCE_DIR}/Resources - "${CRG_PATTERN}" - ) - add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_CORE_RES ) -endmacro() - -# Copies resources from an additional directory -# GAME_NAME name of the game -# REL_DIR from which directory -# ARGN which patterns to copy (should include res/ in name if to be placed in the res/ output) -macro(COPY_RES_EXTRA GAME_NAME EXTRA_RES REL_DIR) - # convert src's to full paths (based on rel_dir) - set(SRC_FILES) - foreach(SRC_FILE ${ARGN} ) - list(APPEND SRC_FILES "${REL_DIR}/${SRC_FILE}") - endforeach() - COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_${EXTRA_RES} ${REL_DIR} "${SRC_FILES}" ) - add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_${EXTRA_RES} ) + add_custom_target( ${TARGET_NAME}_CORE_PRE_BUILD ) + add_dependencies( ${TARGET_NAME}_PRE_BUILD ${TARGET_NAME}_CORE_PRE_BUILD ) endmacro() diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index b335cf89fc..667bf7cd18 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -18,5 +18,8 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${APP_NAME} ) +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index a4237425f9..e5493d194c 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -159,5 +159,8 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${APP_NAME} ) +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index c048fae5c0..e0d1f3a753 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -33,8 +33,8 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${APP_NAME} ) - -COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua - script/* +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources ) diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index dc81be8941..743f3eeb3f 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -33,11 +33,10 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES(${APP_NAME}) -COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua - script/* - ) -COPY_RES_EXTRA(${APP_NAME} copy_cpp_res ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources - * +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources ${APP_BIN_DIR}/Resources ) From 555f3609c84c87c07f07c2c4172e0967e67f737a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 5 Nov 2013 19:02:03 -0800 Subject: [PATCH 079/197] Uses `const std::string&` ... instead of const char* * Because it is more robust * and it is faster... yes faster. It is faster because internally some of our classes use std::string (like FileUtils and Dictionary) so converting back-and-forth from const char * to std::string is very expensive. It is faster to have everthing in std::string as soon as possible to prevent further conversions. There are still some parts of the code that require conversion, but most of the code was converted. --- cocos/2d/CCAnimationCache.cpp | 40 +++++++++---------- cocos/2d/CCAnimationCache.h | 12 +++--- cocos/2d/CCLabel.cpp | 14 +++---- cocos/2d/CCLabel.h | 8 ++-- cocos/2d/CCLabelAtlas.cpp | 4 +- cocos/2d/CCLabelAtlas.h | 2 +- cocos/2d/CCLabelBMFont.cpp | 45 +++++++++------------ cocos/2d/CCLabelBMFont.h | 28 ++++++------- cocos/2d/CCLabelTTF.cpp | 4 +- cocos/2d/CCLabelTTF.h | 2 +- cocos/2d/CCParticleSystem.cpp | 14 +++---- cocos/2d/CCParticleSystem.h | 6 +-- cocos/2d/CCProtocols.h | 2 +- cocos/2d/CCSprite.cpp | 24 +++++------ cocos/2d/CCSprite.h | 14 +++---- cocos/2d/CCSpriteFrame.cpp | 36 ++++++++--------- cocos/2d/CCSpriteFrame.h | 8 ++-- cocos/2d/CCSpriteFrameCache.cpp | 70 ++++++++++++++++----------------- cocos/2d/CCSpriteFrameCache.h | 18 ++++----- 19 files changed, 168 insertions(+), 183 deletions(-) diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 37f516347a..a2c0fa9303 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -71,22 +71,20 @@ AnimationCache::~AnimationCache() CC_SAFE_RELEASE(_animations); } -void AnimationCache::addAnimation(Animation *animation, const char * name) +void AnimationCache::addAnimation(Animation *animation, const std::string& name) { _animations->setObject(animation, name); } -void AnimationCache::removeAnimation(const char* name) +void AnimationCache::removeAnimation(const std::string& name) { - if (! name) - { + if (name.size()==0) return; - } _animations->removeObjectForKey(name); } -Animation* AnimationCache::getAnimation(const char* name) +Animation* AnimationCache::getAnimation(const std::string& name) { return (Animation*)_animations->objectForKey(name); } @@ -95,17 +93,17 @@ void AnimationCache::parseVersion1(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); - DictElement* pElement = NULL; - CCDICT_FOREACH(animations, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(animations, element) { - Dictionary* animationDict = static_cast(pElement->getObject()); + Dictionary* animationDict = static_cast(element->getObject()); Array* frameNames = static_cast(animationDict->objectForKey("frames")); float delay = animationDict->valueForKey("delay")->floatValue(); Animation* animation = NULL; if ( frameNames == NULL ) { - CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", pElement->getStrKey()); + CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", element->getStrKey()); continue; } @@ -115,11 +113,11 @@ void AnimationCache::parseVersion1(Dictionary* animations) Object* pObj = NULL; CCARRAY_FOREACH(frameNames, pObj) { - const char* frameName = static_cast(pObj)->getCString(); + const std::string& frameName = static_cast(pObj)->getCString(); SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName); if ( ! spriteFrame ) { - CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", pElement->getStrKey(), frameName); + CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", element->getStrKey(), frameName.c_str()); continue; } @@ -131,15 +129,15 @@ void AnimationCache::parseVersion1(Dictionary* animations) } if ( frames->count() == 0 ) { - CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", pElement->getStrKey()); + CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", element->getStrKey()); continue; } else if ( frames->count() != frameNames->count() ) { - 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.", pElement->getStrKey()); + CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", element->getStrKey()); } animation = Animation::create(frames, delay, 1); - AnimationCache::getInstance()->addAnimation(animation, pElement->getStrKey()); + AnimationCache::getInstance()->addAnimation(animation, element->getStrKey()); frames->release(); } } @@ -148,11 +146,11 @@ void AnimationCache::parseVersion2(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); - DictElement* pElement = NULL; - CCDICT_FOREACH(animations, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(animations, element) { - const char* name = pElement->getStrKey(); - Dictionary* animationDict = static_cast(pElement->getObject()); + const char* name = element->getStrKey(); + Dictionary* animationDict = static_cast(element->getObject()); const String* loops = animationDict->valueForKey("loops"); bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue(); @@ -241,9 +239,9 @@ void AnimationCache::addAnimationsWithDictionary(Dictionary* dictionary) } /** Read an NSDictionary from a plist file and parse it automatically for animations */ -void AnimationCache::addAnimationsWithFile(const char* plist) +void AnimationCache::addAnimationsWithFile(const std::string& plist) { - CCASSERT( plist, "Invalid texture file name"); + CCASSERT( plist.size()>0, "Invalid texture file name"); std::string path = FileUtils::getInstance()->fullPathForFilename(plist); Dictionary* dict = Dictionary::createWithContentsOfFile(path.c_str()); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index f30d6ee94f..475c16ce87 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -76,29 +76,29 @@ public: /** Adds a Animation with a name. */ - void addAnimation(Animation *animation, const char * name); + void addAnimation(Animation *animation, const std::string& name); /** Deletes a Animation from the cache. */ - void removeAnimation(const char* name); + void removeAnimation(const std::string& name); /** @deprecated. Use removeAnimation() instead * @js NA * @lua NA */ - CC_DEPRECATED_ATTRIBUTE void removeAnimationByName(const char* name){ removeAnimation(name);} + CC_DEPRECATED_ATTRIBUTE void removeAnimationByName(const std::string& name){ removeAnimation(name);} /** Returns a Animation that was previously added. If the name is not found it will return nil. You should retain the returned copy if you are going to use it. */ - Animation* getAnimation(const char* name); + Animation* getAnimation(const std::string& name); /** @deprecated. Use getAnimation() instead * @js NA * @lua NA */ - CC_DEPRECATED_ATTRIBUTE Animation* animationByName(const char* name){ return getAnimation(name); } + CC_DEPRECATED_ATTRIBUTE Animation* animationByName(const std::string& name){ return getAnimation(name); } /** Adds an animation from an NSDictionary Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -112,7 +112,7 @@ public: * @js addAnimations * @lua addAnimations */ - void addAnimationsWithFile(const char* plist); + void addAnimationsWithFile(const std::string& plist); private: void parseVersion1(Dictionary* animations); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 68cc984636..0dc7fc5081 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -29,9 +29,9 @@ NS_CC_BEGIN -Label* Label::createWithTTF( const char* label, const char* 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 ) { - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs); + FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs); if (!tmpAtlas) return nullptr; @@ -48,10 +48,10 @@ Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fo return nullptr; } -Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize) +Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize) { - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); + FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str()); if (!tmpAtlas) return 0; @@ -135,12 +135,12 @@ bool Label::init() return true; } -void Label::setString(const char *stringToRender) +void Label::setString(const std::string &stringToRender) { setText(stringToRender, _width, TextHAlignment::CENTER, false); } -bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) +bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) { if (!_fontAtlas) return false; @@ -159,7 +159,7 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment return false; // int numLetter = 0; - unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); + unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str()); if(!utf16String) return false; diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 0d668256f2..a4c9a127e2 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -51,13 +51,13 @@ class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAPr public: // static create - static Label* createWithTTF(const char* label, const char* fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0); + static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0); - static Label* createWithBMFont(const char* label, const char* bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); + static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); - bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); + bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); - virtual void setString(const char *stringToRender) override; + virtual void setString(const std::string &stringToRender) override; virtual void setAlignment(TextHAlignment alignment); virtual void setWidth(float width); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index ca28f930cb..f1a9126b54 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -186,9 +186,9 @@ void LabelAtlas::updateAtlasValues() } //CCLabelAtlas - LabelProtocol -void LabelAtlas::setString(const char *label) +void LabelAtlas::setString(const std::string &label) { - size_t len = strlen(label); + size_t len = label.size(); if (len > _textureAtlas->getTotalQuads()) { _textureAtlas->resizeCapacity(len); diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 2c7d98ea5b..b8df38f62d 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -87,7 +87,7 @@ public: // super methods virtual void updateAtlasValues(); - virtual void setString(const char *label); + virtual void setString(const std::string &label); virtual const char* getString(void) const; #if CC_LABELATLAS_DEBUG_DRAW diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index a9270757c7..1000889c62 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -62,7 +62,7 @@ static unsigned short* copyUTF16StringN(unsigned short* str) // static Dictionary* s_pConfigurations = NULL; -CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) +CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) { CCBMFontConfiguration* pRet = NULL; @@ -75,7 +75,7 @@ CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) pRet = static_cast( s_pConfigurations->objectForKey(fntFile) ); if( pRet == NULL ) { - pRet = CCBMFontConfiguration::create(fntFile); + pRet = CCBMFontConfiguration::create(fntFile.c_str()); if (pRet) { s_pConfigurations->setObject(pRet, fntFile); @@ -180,7 +180,7 @@ void CCBMFontConfiguration::purgeFontDefDictionary() } } -std::set* CCBMFontConfiguration::parseConfigFile(const char *controlFile) +std::set* CCBMFontConfiguration::parseConfigFile(const std::string& controlFile) { std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile); String *contents = String::createWithContentsOfFile(fullpath.c_str()); @@ -191,7 +191,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr if (!contents) { - CCLOG("cocos2d: Error parsing FNTfile %s", controlFile); + CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); return NULL; } @@ -259,7 +259,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr return validCharsString; } -void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile) +void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile) { ////////////////////////////////////////////////////////////////////////// // line to parse: @@ -431,23 +431,23 @@ LabelBMFont * LabelBMFont::create() return NULL; } -LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment) +LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment) { return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO); } -LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width) +LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width) { return LabelBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO); } -LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile) +LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile) { return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); } //LabelBMFont - Creation & Init -LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) +LabelBMFont *LabelBMFont::create(const std::string& str, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) { LabelBMFont *pRet = new LabelBMFont(); if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset)) @@ -461,22 +461,21 @@ LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float wid bool LabelBMFont::init() { - return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); + return initWithString("", "", kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); } -bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) +bool LabelBMFont::initWithString(const std::string& theString, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) { CCASSERT(!_configuration, "re-init is no longer supported"); - CCASSERT( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont"); - + Texture2D *texture = NULL; - if (fntFile) + if (fntFile.size() > 0 ) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); if (!newConf) { - CCLOG("cocos2d: WARNING. LabelBMFont: Impossible to create font. Please check file: '%s'", fntFile); + CCLOG("cocos2d: WARNING. LabelBMFont: Impossible to create font. Please check file: '%s'", fntFile.c_str()); release(); return false; } @@ -495,12 +494,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo texture->autorelease(); } - if (theString == NULL) - { - theString = ""; - } - - if (SpriteBatchNode::initWithTexture(texture, strlen(theString))) + if (SpriteBatchNode::initWithTexture(texture, theString.size())) { _width = width; _alignment = alignment; @@ -724,20 +718,17 @@ void LabelBMFont::createFontChars() } //LabelBMFont - LabelProtocol protocol -void LabelBMFont::setString(const char *newString) +void LabelBMFont::setString(const std::string &newString) { this->setString(newString, true); } -void LabelBMFont::setString(const char *newString, bool needUpdateLabel) +void LabelBMFont::setString(const std::string &newString, bool needUpdateLabel) { - if (newString == NULL) { - newString = ""; - } if (needUpdateLabel) { _initialStringUTF8 = newString; } - unsigned short* utf16String = cc_utf8_to_utf16(newString); + unsigned short* utf16String = cc_utf8_to_utf16(newString.c_str()); setString(utf16String, needUpdateLabel); CC_SAFE_DELETE_ARRAY(utf16String); } diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index 11ff078ac5..0da1584387 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -145,16 +145,16 @@ public: /** initializes a BitmapFontConfiguration with a FNT file */ bool initWithFNTfile(const char *FNTfile); - inline const char* getAtlasName(){ return _atlasName.c_str(); } - inline void setAtlasName(const char* atlasName) { _atlasName = atlasName; } + inline const std::string& getAtlasName(){ return _atlasName; } + inline void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } std::set* getCharacterSet() const; private: - std::set* parseConfigFile(const char *controlFile); + std::set* parseConfigFile(const std::string& controlFile); void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); void parseInfoArguments(std::string line); void parseCommonArguments(std::string line); - void parseImageFileName(std::string line, const char *fntFile); + void parseImageFileName(std::string line, const std::string& fntFile); void parseKerningEntry(std::string line); void purgeKerningDictionary(); void purgeFontDefDictionary(); @@ -209,13 +209,13 @@ public: static void purgeCachedData(); /** creates a bitmap font atlas with an initial string and the FNT file */ - static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset); + static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment, Point imageOffset); - static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment); + static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment); - static LabelBMFont * create(const char *str, const char *fntFile, float width); + static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width); - static LabelBMFont * create(const char *str, const char *fntFile); + static LabelBMFont * create(const std::string& str, const std::string& fntFile); /** Creates an label. */ @@ -223,15 +223,15 @@ public: bool init(); /** init a bitmap font atlas with an initial string and the FNT file */ - bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO); + bool initWithString(const std::string& str, const std::string& fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO); /** updates the font chars based on the string to render */ void createFontChars(); // super method - virtual void setString(const char *newString); - virtual void setString(const char *newString, bool needUpdateLabel); + virtual void setString(const std::string& newString); + virtual void setString(const std::string& newString, bool needUpdateLabel); - virtual const char* getString(void) const; + virtual const char* getString() const; virtual void setCString(const char *label); virtual void setAnchorPoint(const Point& var); virtual void updateLabel(); @@ -264,7 +264,7 @@ public: virtual void draw(); #endif // CC_LABELBMFONT_DEBUG_DRAW private: - char * atlasNameFromFntFile(const char *fntFile); + char * atlasNameFromFntFile(const std::string& fntFile); int kerningAmountForFirst(unsigned short first, unsigned short second); float getLetterPosXLeft( Sprite* characterSprite ); float getLetterPosXRight( Sprite* characterSprite ); @@ -309,7 +309,7 @@ protected: /** Free function that parses a FNT file a place it on the cache */ -CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file ); +CC_DLL CCBMFontConfiguration * FNTConfigLoadFile(const std::string &file); /** Purges the FNT config cache */ CC_DLL void FNTConfigRemoveCache( void ); diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index bead3ea020..051b07d9b7 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -171,10 +171,8 @@ bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinitio } -void LabelTTF::setString(const char *string) +void LabelTTF::setString(const std::string &string) { - CCASSERT(string != NULL, "Invalid string"); - if (_string.compare(string)) { _string = string; diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 9243a50e1c..1f785028c4 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -144,7 +144,7 @@ public: /** changes the string to render * @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas */ - virtual void setString(const char *label); + virtual void setString(const std::string &label); virtual const char* getString(void) const; TextHAlignment getHorizontalAlignment() const; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 785251ca7a..21c473f2f2 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -136,7 +136,7 @@ ParticleSystem::ParticleSystem() } // implementation ParticleSystem -ParticleSystem * ParticleSystem::create(const char *plistFile) +ParticleSystem * ParticleSystem::create(const std::string& plistFile) { ParticleSystem *pRet = new ParticleSystem(); if (pRet && pRet->initWithFile(plistFile)) @@ -165,7 +165,7 @@ bool ParticleSystem::init() return initWithTotalParticles(150); } -bool ParticleSystem::initWithFile(const char *plistFile) +bool ParticleSystem::initWithFile(const std::string& plistFile) { bool bRet = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); @@ -195,7 +195,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary) return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirname) +bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::string& dirname) { bool bRet = false; unsigned char *buffer = NULL; @@ -353,17 +353,17 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn { string textureDir = textureName.substr(0, rPos + 1); - if (dirname != NULL && textureDir != dirname) + if (dirname.size()>0 && textureDir != dirname) { textureName = textureName.substr(rPos+1); - textureName = string(dirname) + textureName; + textureName = dirname + textureName; } } else { - if (dirname != NULL) + if (dirname.size()>0) { - textureName = string(dirname) + textureName; + textureName = dirname + textureName; } } diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index ae22671c4c..1cd30b56c8 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -167,7 +167,7 @@ public: http://particledesigner.71squared.com/ @since v2.0 */ - static ParticleSystem * create(const char *plistFile); + static ParticleSystem * create(const std::string& plistFile); //! create a system with a fixed number of particles static ParticleSystem* createWithTotalParticles(unsigned int numberOfParticles); @@ -188,7 +188,7 @@ public: http://particledesigner.71squared.com/ @since v0.99.3 */ - bool initWithFile(const char *plistFile); + bool initWithFile(const std::string& plistFile); /** initializes a QuadParticleSystem from a Dictionary. @since v0.99.3 @@ -198,7 +198,7 @@ public: /** initializes a particle system from a NSDictionary and the path from where to load the png @since v2.1 */ - bool initWithDictionary(Dictionary *dictionary, const char *dirname); + bool initWithDictionary(Dictionary *dictionary, const std::string& dirname); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(unsigned int numberOfParticles); diff --git a/cocos/2d/CCProtocols.h b/cocos/2d/CCProtocols.h index 01b7ebc011..17249816c0 100644 --- a/cocos/2d/CCProtocols.h +++ b/cocos/2d/CCProtocols.h @@ -229,7 +229,7 @@ public: * @js NA * @lua NA */ - virtual void setString(const char *label) = 0; + virtual void setString(const std::string &label) = 0; /** * Returns the string that is currently being used in this label diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 676138d9b1..fa6f4878b0 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -82,7 +82,7 @@ Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect) return NULL; } -Sprite* Sprite::create(const char *filename) +Sprite* Sprite::create(const std::string& filename) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename)) @@ -94,7 +94,7 @@ Sprite* Sprite::create(const char *filename) return NULL; } -Sprite* Sprite::create(const char *filename, const Rect& rect) +Sprite* Sprite::create(const std::string& filename, const Rect& rect) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename, rect)) @@ -118,13 +118,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame) return NULL; } -Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) +Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) { SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); + sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); CCASSERT(frame != NULL, msg); #endif @@ -215,9 +215,9 @@ bool Sprite::initWithTexture(Texture2D *texture) return initWithTexture(texture, rect); } -bool Sprite::initWithFile(const char *filename) +bool Sprite::initWithFile(const std::string& filename) { - CCASSERT(filename != NULL, "Invalid filename for sprite"); + CCASSERT(filename.size()>0, "Invalid filename for sprite"); Texture2D *texture = TextureCache::getInstance()->addImage(filename); if (texture) @@ -233,9 +233,9 @@ bool Sprite::initWithFile(const char *filename) return false; } -bool Sprite::initWithFile(const char *filename, const Rect& rect) +bool Sprite::initWithFile(const std::string &filename, const Rect& rect) { - CCASSERT(filename != NULL, ""); + CCASSERT(filename.size()>0, "Invalid filename"); Texture2D *texture = TextureCache::getInstance()->addImage(filename); if (texture) @@ -259,9 +259,9 @@ bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) return bRet; } -bool Sprite::initWithSpriteFrameName(const char *spriteFrameName) +bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) { - CCASSERT(spriteFrameName != NULL, ""); + CCASSERT(spriteFrameName.size() > 0, "Invalid spriteFrameName"); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); return initWithSpriteFrame(frame); @@ -992,9 +992,9 @@ void Sprite::setDisplayFrame(SpriteFrame *pNewFrame) setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize()); } -void Sprite::setDisplayFrameWithAnimationName(const char *animationName, int frameIndex) +void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex) { - CCASSERT(animationName, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); + CCASSERT(animationName.size()>0, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); Animation *a = AnimationCache::getInstance()->getAnimation(animationName); diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index cc6470c7da..7ebf7ff616 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -105,7 +105,7 @@ public: * @param filename The string which indicates a path to image file, e.g., "scene1/monster.png". * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* create(const char *filename); + static Sprite* create(const std::string& filename); /** * Creates a sprite with an image filename and a rect. @@ -114,7 +114,7 @@ public: * @param rect Only the contents inside rect of filename's texture will be applied for this sprite. * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* create(const char *filename, const Rect& rect); + static Sprite* create(const std::string& filename, const Rect& rect); /** * Creates a sprite with an exsiting texture contained in a Texture2D object @@ -154,7 +154,7 @@ public: * @param spriteFrameName A null terminated string which indicates the sprite frame name. * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* createWithSpriteFrameName(const char *spriteFrameName); + static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); /// @} end of creators group @@ -233,7 +233,7 @@ public: * @param spriteFrameName A key string that can fected a volid SpriteFrame from SpriteFrameCache * @return true if the sprite is initialized properly, false otherwise. */ - virtual bool initWithSpriteFrameName(const char *spriteFrameName); + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); /** * Initializes a sprite with an image filename. @@ -247,7 +247,7 @@ public: * @js init * @lua init */ - virtual bool initWithFile(const char *filename); + virtual bool initWithFile(const std::string& filename); /** * Initializes a sprite with an image filename, and a rect. @@ -262,7 +262,7 @@ public: * @js init * @lua init */ - virtual bool initWithFile(const char *filename, const Rect& rect); + virtual bool initWithFile(const std::string& filename, const Rect& rect); /// @} end of initializers @@ -354,7 +354,7 @@ public: * Changes the display frame with animation name and index. * The animation name will be get from the AnimationCache */ - virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex); + virtual void setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex); /// @} diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 8bc0bafa6d..d2fd2c2495 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -31,61 +31,61 @@ NS_CC_BEGIN // implementation of SpriteFrame -SpriteFrame* SpriteFrame::create(const char* filename, const Rect& rect) +SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; + SpriteFrame *pSpriteFrame = new SpriteFrame(); pSpriteFrame->initWithTextureFilename(filename, rect); pSpriteFrame->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::createWithTexture(Texture2D *pobTexture, const Rect& rect) +SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const Rect& rect) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; - pSpriteFrame->initWithTexture(pobTexture, rect); + SpriteFrame *pSpriteFrame = new SpriteFrame(); + pSpriteFrame->initWithTexture(texture, rect); pSpriteFrame->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::createWithTexture(Texture2D* pobTexture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; - pSpriteFrame->initWithTexture(pobTexture, rect, rotated, offset, originalSize); + SpriteFrame *pSpriteFrame = new SpriteFrame(); + pSpriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize); pSpriteFrame->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::create(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; + SpriteFrame *pSpriteFrame = new SpriteFrame(); pSpriteFrame->initWithTextureFilename(filename, rect, rotated, offset, originalSize); pSpriteFrame->autorelease(); return pSpriteFrame; } -bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect) +bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); - return initWithTexture(pobTexture, rectInPixels, false, Point::ZERO, rectInPixels.size); + return initWithTexture(texture, rectInPixels, false, Point::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect) +bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); return initWithTextureFilename(filename, rectInPixels, false, Point::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { - _texture = pobTexture; + _texture = texture; - if (pobTexture) + if (texture) { - pobTexture->retain(); + texture->retain(); } _rectInPixels = rect; @@ -99,7 +99,7 @@ bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool return true; } -bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { _texture = NULL; _textureFilename = filename; diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index f9b2d68c4a..4d205d0f8a 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -58,12 +58,12 @@ public: /** Create a SpriteFrame with a texture filename, rect in points. It is assumed that the frame was not trimmed. */ - static SpriteFrame* create(const char* filename, const Rect& rect); + static SpriteFrame* create(const std::string& filename, const Rect& rect); /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. The originalSize is the size in pixels of the frame before being trimmed. */ - static SpriteFrame* create(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); + static SpriteFrame* create(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); /** Create a SpriteFrame with a texture, rect in points. It is assumed that the frame was not trimmed. @@ -88,7 +88,7 @@ public: /** Initializes a SpriteFrame with a texture filename, rect in points; It is assumed that the frame was not trimmed. */ - bool initWithTextureFilename(const char* filename, const Rect& rect); + bool initWithTextureFilename(const std::string& filename, const Rect& rect); /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. The originalSize is the size in points of the frame before being trimmed. @@ -100,7 +100,7 @@ public: @since v1.1 */ - bool initWithTextureFilename(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); + bool initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); // attributes diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 78fc2f8fa6..7ab33b85fe 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -102,11 +102,11 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex // check the format CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); - DictElement* pElement = NULL; - CCDICT_FOREACH(framesDict, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(framesDict, element) { - Dictionary* frameDict = static_cast(pElement->getObject()); - std::string spriteFrameName = pElement->getStrKey(); + Dictionary* frameDict = static_cast(element->getObject()); + std::string spriteFrameName = element->getStrKey(); SpriteFrame* spriteFrame = static_cast(_spriteFrames->objectForKey(spriteFrameName)); if (spriteFrame) { @@ -203,7 +203,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex } } -void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D *pobTexture) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); @@ -212,9 +212,9 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D * dict->release(); } -void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) { - CCASSERT(textureFileName, "texture name should not be null"); + CCASSERT(textureFileName.size()>0, "texture name should not be null"); Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName); if (texture) @@ -223,13 +223,13 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* te } else { - CCLOG("cocos2d: SpriteFrameCache: couldn't load texture file. File not found %s", textureFileName); + CCLOG("cocos2d: SpriteFrameCache: couldn't load texture file. File not found %s", textureFileName.c_str()); } } -void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) { - CCASSERT(pszPlist, "plist filename should not be NULL"); + CCASSERT(pszPlist.size()>0, "plist filename should not be NULL"); if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end()) { @@ -280,7 +280,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) } } -void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const char *pszFrameName) +void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const std::string& pszFrameName) { _spriteFrames->setObject(pobFrame, pszFrameName); } @@ -295,14 +295,14 @@ void SpriteFrameCache::removeSpriteFrames(void) void SpriteFrameCache::removeUnusedSpriteFrames(void) { bool bRemoved = false; - DictElement* pElement = NULL; - CCDICT_FOREACH(_spriteFrames, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(_spriteFrames, element) { - SpriteFrame* spriteFrame = static_cast(pElement->getObject()); + SpriteFrame* spriteFrame = static_cast(element->getObject()); if( spriteFrame->retainCount() == 1 ) { - CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", pElement->getStrKey()); - _spriteFrames->removeObjectForElememt(pElement); + CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", element->getStrKey()); + _spriteFrames->removeObjectForElememt(element); bRemoved = true; } } @@ -315,16 +315,14 @@ void SpriteFrameCache::removeUnusedSpriteFrames(void) } -void SpriteFrameCache::removeSpriteFrameByName(const char *pszName) +void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) { // explicit nil handling - if( ! pszName ) - { + if( ! name.size()>0 ) return; - } // Is this an alias ? - String* key = (String*)_spriteFramesAliases->objectForKey(pszName); + String* key = (String*)_spriteFramesAliases->objectForKey(name); if (key) { @@ -333,20 +331,20 @@ void SpriteFrameCache::removeSpriteFrameByName(const char *pszName) } else { - _spriteFrames->removeObjectForKey(pszName); + _spriteFrames->removeObjectForKey(name); } // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache _loadedFileNames->clear(); } -void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist) +void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); if (dict == nullptr) { - CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist); + CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str()); return; } removeSpriteFramesFromDictionary((Dictionary*)dict); @@ -365,12 +363,12 @@ void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary) Dictionary* framesDict = static_cast(dictionary->objectForKey("frames")); Array* keysToRemove = Array::create(); - DictElement* pElement = NULL; - CCDICT_FOREACH(framesDict, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(framesDict, element) { - if (_spriteFrames->objectForKey(pElement->getStrKey())) + if (_spriteFrames->objectForKey(element->getStrKey())) { - keysToRemove->addObject(String::create(pElement->getStrKey())); + keysToRemove->addObject(String::create(element->getStrKey())); } } @@ -381,33 +379,33 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) { Array* keysToRemove = Array::create(); - DictElement* pElement = NULL; - CCDICT_FOREACH(_spriteFrames, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(_spriteFrames, element) { - string key = pElement->getStrKey(); + string key = element->getStrKey(); SpriteFrame* frame = static_cast(_spriteFrames->objectForKey(key.c_str())); if (frame && (frame->getTexture() == texture)) { - keysToRemove->addObject(String::create(pElement->getStrKey())); + keysToRemove->addObject(String::create(element->getStrKey())); } } _spriteFrames->removeObjectsForKeys(keysToRemove); } -SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const char *pszName) +SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) { - SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(pszName); + SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(name); if (!frame) { // try alias dictionary - String *key = (String*)_spriteFramesAliases->objectForKey(pszName); + String *key = (String*)_spriteFramesAliases->objectForKey(name); if (key) { frame = (SpriteFrame*)_spriteFrames->objectForKey(key->getCString()); if (! frame) { - CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", pszName); + CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str()); } } } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index c7249d222c..11733fa0ff 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -85,29 +85,29 @@ public: public: /** Adds multiple Sprite Frames from a plist file. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png - * If you want to use another texture, you should use the addSpriteFramesWithFile(const char *plist, const char *textureFileName) method. + * If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) method. * @js addSpriteFrames * @lua addSpriteFrames */ - void addSpriteFramesWithFile(const char *plist); + void addSpriteFramesWithFile(const std::string& plist); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @since v0.99.5 * @js addSpriteFrames * @lua addSpriteFrames */ - void addSpriteFramesWithFile(const char* plist, const char* textureFileName); + void addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. * @js addSpriteFrames * @lua addSpriteFrames */ - void addSpriteFramesWithFile(const char *plist, Texture2D *texture); + void addSpriteFramesWithFile(const std::string&plist, Texture2D *texture); /** Adds an sprite frame with a given name. If the name already exists, then the contents of the old name will be replaced with the new one. */ - void addSpriteFrame(SpriteFrame *frame, const char *frameName); + void addSpriteFrame(SpriteFrame *frame, const std::string& frameName); /** Purges the dictionary of loaded sprite frames. * Call this method if you receive the "Memory Warning". @@ -124,14 +124,14 @@ public: void removeUnusedSpriteFrames(void); /** Deletes an sprite frame from the sprite frame cache. */ - void removeSpriteFrameByName(const char *name); + void removeSpriteFrameByName(const std::string& name); /** Removes multiple Sprite Frames from a plist file. * Sprite Frames stored in this file will be removed. * It is convenient to call this method when a specific texture needs to be removed. * @since v0.99.5 */ - void removeSpriteFramesFromFile(const char* plist); + void removeSpriteFramesFromFile(const std::string& plist); /** Removes all Sprite Frames associated with the specified textures. * It is convenient to call this method when a specific texture needs to be removed. @@ -145,10 +145,10 @@ public: * @js getSpriteFrame * @lua getSpriteFrame */ - SpriteFrame* getSpriteFrameByName(const char *name); + SpriteFrame* getSpriteFrameByName(const std::string& name); /** @deprecated use getSpriteFrameByName() instead */ - CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const char *name) { return getSpriteFrameByName(name); } + CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const std::string&name) { return getSpriteFrameByName(name); } private: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. From f05c1590ae426078dc6af3d1bd1099f6b5f966c2 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 11:20:16 +0800 Subject: [PATCH 080/197] 1.fix particle kCCPositionTypeFree state bug --- cocos/editor-support/cocostudio/CCArmature.h | 2 +- cocos/editor-support/cocostudio/CCDisplayFactory.cpp | 9 +++++++++ cocos/editor-support/cocostudio/CCDisplayManager.cpp | 8 ++++++++ cocos/editor-support/cocostudio/CCProcessBase.h | 2 +- 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 6182072265..e29323ff86 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -94,7 +94,7 @@ public: * @js NA * @lua NA */ - ~Armature(void); + virtual ~Armature(void); /** * Init the empty armature diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 7f329ff3cc..a4f1432727 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -255,6 +255,15 @@ void DisplayFactory::createParticleDisplay(Bone *bone, DecorativeDisplay *decoDi { ParticleDisplayData *displayData = (ParticleDisplayData *)decoDisplay->getDisplayData(); ParticleSystem *system = ParticleSystemQuad::create(displayData->plist.c_str()); + + system->removeFromParent(); + + Armature *armature = bone->getArmature(); + if (armature) + { + system->setParent(armature); + } + decoDisplay->setDisplay(system); } void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt) diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 52af6b2d1d..ce808ca3b9 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -149,6 +149,14 @@ void DisplayManager::addDisplay(Node *display, int index) else if (dynamic_cast(display)) { displayData = ParticleDisplayData::create(); + + display->removeFromParent(); + + Armature *armature = _bone->getArmature(); + if (armature) + { + display->setParent(armature); + } } else if(Armature *armature = dynamic_cast(display)) { diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index c6b62793b4..2b3ef4ab47 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -58,7 +58,7 @@ public: * @js NA * @lua NA */ - ~ProcessBase(void); + virtual ~ProcessBase(void); /** * Play animation by animation name. From c32628e93039f22a833e45ace1996018e62be46a Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 14:19:08 +0800 Subject: [PATCH 081/197] [ci skip] --- CHANGELOG | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 797c52821d..e206d5cea7 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,18 +10,19 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Could not set next animation in CCBAnimationCompleted callback. [FIX] The Node's anchor point was changed after being added to ScrollView. [FIX] Refactored and improved EventDispatcher. - [NEW] Added Mouse Support For Desktop Platforms. [FIX] EventListeners can't be removed sometimes. [FIX] When parsing XML using TinyXML, the data size has to be specified. + [FIX] Parameter type: const char* -> const string& [NEW] Arm64 support. + [NEW] Added Mouse Support For Desktop Platforms. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes - [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [NEW] Added xlargeScreens="true" to supports-screens [NEW] Added build/android-build.py to build all Android samples, and remove all build_native.sh/cmd [NEW] Added build_native.py to build template projects, and remove build_native.sh/cmd + [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] From d7ed908818bc79139685dcbe734680183a6319aa Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 6 Nov 2013 06:20:17 +0000 Subject: [PATCH 082/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c2b42be577..e150a74a02 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c2b42be577425e4dd6c2501e8f0cd1520ca3d059 +Subproject commit e150a74a028e26cff0dac7d2238e2cd16fbaf370 From 75dd32cde932de99e564daf8231eaddc9c241adb Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 6 Nov 2013 14:34:27 +0800 Subject: [PATCH 083/197] issue #2771: fix physics test compile error --- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 88b17e365e..0885218d9a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -382,7 +382,7 @@ Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial materi bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + Array* arr = _scene->getPhysicsWorld()->getShapes(location); PhysicsShape* shape = nullptr; for (Object* obj : *arr) @@ -982,7 +982,7 @@ void PhysicsDemoPump::update(float delta) } } - PhysicsBody* gear = _scene->getPhysicsWorld()->getBodyByTag(1); + PhysicsBody* gear = _scene->getPhysicsWorld()->getBody(1); if (gear != nullptr) { From a01fcc6f368fb17c1a4e089edc9bc4efae5c5097 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 6 Nov 2013 14:51:56 +0800 Subject: [PATCH 084/197] issue #2771: move header definition to first line --- cocos/physics/CCPhysicsBody.h | 9 ++++----- cocos/physics/CCPhysicsContact.h | 8 ++++---- cocos/physics/CCPhysicsJoint.h | 9 ++++----- cocos/physics/CCPhysicsShape.h | 8 ++++---- cocos/physics/CCPhysicsWorld.h | 9 ++++----- cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsContactInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsHelper_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsJointInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h | 8 ++++---- 17 files changed, 68 insertions(+), 71 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 7c0c79002e..4e6f60f038 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" #include "CCArray.h" @@ -300,6 +300,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_BODY_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_BODY_H__ diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 3982f4fdd6..846761d1cb 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_CONTACT_H__ #define __CCPHYSICS_CONTACT_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" #include "CCEventListenerCustom.h" @@ -267,6 +267,6 @@ protected: }; NS_CC_END -#endif //__CCPHYSICS_CONTACT_H__ #endif // CC_USE_PHYSICS +#endif //__CCPHYSICS_CONTACT_H__ diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 2970d992d0..ff5285b819 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_JOINT_H__ #define __CCPHYSICS_JOINT_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" @@ -181,6 +181,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_JOINT_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_JOINT_H__ diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 4aba49d4d7..b9525506d1 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_SHAPE_H__ #define __CCPHYSICS_SHAPE_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" @@ -309,6 +309,6 @@ protected: }; NS_CC_END -#endif // __CCPHYSICS_FIXTURE_H__ #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_FIXTURE_H__ diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index e4cad6e7eb..2e70749f57 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include #include @@ -192,6 +192,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_WORLD_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_WORLD_H__ diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h index ed5135bf36..f04076ffcf 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_BODY_INFO_BOX2D_H__ +#define __CCPHYSICS_BODY_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -40,6 +40,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_BODY_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h index c8d4a262d5..d66ed0e131 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_CONTACT_INFO_BOX2D_H__ +#define __CCPHYSICS_CONTACT_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_CONTACT_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_CONTACT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsHelper_box2d.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h index 01f156628d..f14fcef36f 100644 --- a/cocos/physics/box2d/CCPhysicsHelper_box2d.h +++ b/cocos/physics/box2d/CCPhysicsHelper_box2d.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_HELPER_BOX2D_H__ +#define __CCPHYSICS_HELPER_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -37,6 +37,6 @@ class PhysicsHelper }; NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_HELPER_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h index c8223b6f8c..e1404eec45 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_JOINT_INFO_BOX2D_H__ +#define __CCPHYSICS_JOINT_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_JOINT_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_JOINT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h index cd1fc6abcc..15720797e0 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_SHAPE_INFO_BOX2D_H__ +#define __CCPHYSICS_SHAPE_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_SHAPE_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index 9df3ec46cd..fac9fd5181 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_WORLD_INFO_BOX2D_H__ +#define __CCPHYSICS_WORLD_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_WORLD_INFO_BOX2D_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index dd2d276ac5..143fec843c 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" @@ -51,6 +51,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 4b01ad9d53..6cc0e189c1 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -49,6 +49,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index bf6f6d14db..52d0023b8b 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_HELPER_CHIPMUNK_H__ +#define __CCPHYSICS_HELPER_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -68,6 +68,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_HELPER_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 016cd74d12..bdd3f1e887 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include @@ -60,6 +60,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index b519fd378a..2bdd55a7f9 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include #include #include "chipmunk.h" @@ -70,6 +70,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index b50e1a3240..0c098d3d90 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include @@ -55,6 +55,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ From f3c40a3e7aea34bdd59b42d99dcc2b4f0d934cc9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 14:54:35 +0800 Subject: [PATCH 085/197] issue #3113: 32Bit fix and 13.10 32bit complication is ok. --- cocos/2d/CMakeLists.txt | 2 ++ cocos/audio/CMakeLists.txt | 8 +++++++- cocos/network/CMakeLists.txt | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index f147d233b6..9446d95364 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -134,9 +134,11 @@ target_link_libraries(cocos2d freetype fontconfig png + pthread glfw GLEW GL + X11 rt z ) diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 9e88293ddd..12fde54f25 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -7,8 +7,14 @@ add_library(audio STATIC ${AUDIO_SRC} ) +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + target_link_libraries(audio - fmodex64 + ${FMOD_LIB} ) set_target_properties(audio diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index 3bd130111b..f2deb9b365 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -9,6 +9,10 @@ add_library(network STATIC target_link_libraries(network curl + ldap + lber + idn + rtmp ) set_target_properties(network From 12d6bc1722d9b4cf35f433c5cd706a9c504a6ad0 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 15:25:44 +0800 Subject: [PATCH 086/197] 1. change CCARRAY_FOREACH to range-based loop --- .../editor-support/cocostudio/CCArmature.cpp | 27 +++++++----------- cocos/editor-support/cocostudio/CCArmature.h | 6 ++-- .../cocostudio/CCArmatureAnimation.cpp | 16 ++++------- .../cocostudio/CCArmatureDataManager.cpp | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 10 +++---- cocos/editor-support/cocostudio/CCBone.cpp | 27 ++++++++++-------- cocos/editor-support/cocostudio/CCBone.h | 7 ++++- .../cocostudio/CCColliderDetector.cpp | 28 +++++++------------ .../cocostudio/CCDisplayFactory.cpp | 2 +- .../cocostudio/CCDisplayManager.cpp | 6 ++-- 10 files changed, 58 insertions(+), 73 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 7cd7ad9295..b09922ff70 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -335,7 +335,7 @@ void Armature::changeBoneParent(Bone *bone, const char *parentName) } } -const Dictionary *Armature::getBoneDic() const +Dictionary *Armature::getBoneDic() const { return _boneDic; } @@ -451,8 +451,7 @@ void Armature::update(float dt) { _animation->update(dt); - Object *object = nullptr; - CCARRAY_FOREACH(_topBoneList, object) + for (auto object : *_topBoneList) { static_cast(object)->update(dt); } @@ -468,8 +467,7 @@ void Armature::draw() GL::blendFunc(_blendFunc.src, _blendFunc.dst); } - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for (auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { @@ -642,8 +640,7 @@ Rect Armature::getBoundingBox() const Rect boundingBox = Rect(0, 0, 0, 0); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for(auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { @@ -754,17 +751,15 @@ void Armature::setBody(b2Body *body) _body = body; _body->SetUserData(this); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for(auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = nullptr; - CCARRAY_FOREACH(displayList, displayObject) + for(auto displayObject : displayList) { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); + ColliderDetector *detector = static_cast(displayObject)->getColliderDetector(); if (detector != nullptr) { detector->setBody(_body); @@ -802,17 +797,15 @@ void Armature::setBody(cpBody *body) _body = body; _body->data = this; - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for(auto object: *_children) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = nullptr; - CCARRAY_FOREACH(displayList, displayObject) + for(auto displayObject: *displayList) { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); + ColliderDetector *detector = static_cast(displayObject)->getColliderDetector(); if (detector != nullptr) { detector->setBody(_body); diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index e29323ff86..3ace91b05e 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -140,7 +140,7 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - const cocos2d::Dictionary *getBoneDic() const; + cocos2d::Dictionary *getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time @@ -180,10 +180,10 @@ public: virtual void setArmatureData(ArmatureData *armatureData) { _armatureData = armatureData; } - virtual const ArmatureData *getArmatureData() const { return _armatureData; } + virtual ArmatureData *getArmatureData() const { return _armatureData; } virtual void setBatchNode(BatchNode *batchNode) { _batchNode = batchNode; } - virtual const BatchNode *getBatchNode() const { return _batchNode; } + virtual BatchNode *getBatchNode() const { return _batchNode; } virtual void setName(const std::string &name) { _name = name; } virtual const std::string &getName() const { return _name; } diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 6b234782bd..49aa8e1c6f 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -94,8 +94,7 @@ bool ArmatureAnimation::init(Armature *armature) void ArmatureAnimation:: pause() { - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->pause(); } @@ -104,8 +103,7 @@ void ArmatureAnimation:: pause() void ArmatureAnimation::resume() { - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->resume(); } @@ -114,8 +112,7 @@ void ArmatureAnimation::resume() void ArmatureAnimation::stop() { - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->stop(); } @@ -302,8 +299,7 @@ void ArmatureAnimation::gotoAndPlay(int frameIndex) _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; _currentFrame = _nextFrameIndex * _currentPercent; - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->gotoAndPlay(frameIndex); } @@ -327,8 +323,8 @@ int ArmatureAnimation::getMovementCount() const void ArmatureAnimation::update(float dt) { ProcessBase::update(dt); - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + + for(auto object : *_tweenList) { static_cast(object)->update(dt); } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 0e139ef560..57f9bf5cdc 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -136,7 +136,7 @@ void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) } _relativeDatas.erase(configFilePath); - DataReaderHelper::sharedDataReaderHelper()->removeConfigFile(configFilePath); + DataReaderHelper::getInstance()->removeConfigFile(configFilePath); } } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 36158a12dd..7219969b57 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -90,8 +90,7 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = nullptr; - CCARRAY_FOREACH(displayList, object) + for(auto object : *displayList) { DecorativeDisplay *display = static_cast(object); @@ -118,8 +117,7 @@ void BatchNode::removeChild(Node* child, bool cleanup) Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = nullptr; - CCARRAY_FOREACH(displayList, object) + for(auto object : *displayList) { DecorativeDisplay *display = static_cast(object); @@ -166,8 +164,8 @@ void BatchNode::visit() void BatchNode::draw() { CC_NODE_DRAW_SETUP(); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + + for(auto object : *_children) { Armature *armature = dynamic_cast(object); if (armature) diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 26c5653d58..cbd4544120 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -229,11 +229,13 @@ void Bone::update(float delta) DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + if (_children) { - Bone *childBone = (Bone *)object; - childBone->update(delta); + for(auto object : *_children) + { + Bone *childBone = (Bone *)object; + childBone->update(delta); + } } _boneTransformDirty = false; @@ -322,16 +324,16 @@ void Bone::addChildBone(Bone *child) void Bone::removeChildBone(Bone *bone, bool recursion) { - if ( _children->getIndexOfObject(bone) != UINT_MAX ) + if (_children && _children->getIndexOfObject(bone) != UINT_MAX ) { if(recursion) { - Array *_ccbones = bone->_children; - Object *_object = nullptr; - CCARRAY_FOREACH(_ccbones, _object) + Array *ccbones = bone->_children; + + for(auto object : *ccbones) { - Bone *_ccBone = (Bone *)_object; - bone->removeChildBone(_ccBone, recursion); + Bone *ccBone = (Bone *)object; + bone->removeChildBone(ccBone, recursion); } } @@ -412,6 +414,7 @@ DisplayType Bone::getDisplayRenderNodeType() return _displayManager->getDisplayRenderNodeType(); } + void Bone::addDisplay(DisplayData *displayData, int index) { _displayManager->addDisplay(displayData, index); @@ -449,8 +452,8 @@ Array *Bone::getColliderBodyList() void Bone::setColliderFilter(ColliderFilter *filter) { Array *array = _displayManager->getDecorativeDisplayList(); - Object *object = nullptr; - CCARRAY_FOREACH(array, object) + + for(auto object : *array) { DecorativeDisplay *decoDisplay = static_cast(object); if (ColliderDetector *detector = decoDisplay->getColliderDetector()) diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 9082f1ebb3..4d67c41e2e 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -176,6 +176,11 @@ public: virtual void setIgnoreMovementBoneData(bool ignore) { _ignoreMovementBoneData = ignore; } virtual bool isIgnoreMovementBoneData() const { return _ignoreMovementBoneData; } + /* + * This function is deprecated, please use isIgnoreMovementBoneData() + */ + CC_DEPRECATED_ATTRIBUTE virtual bool getIgnoreMovementBoneData() const { return isIgnoreMovementBoneData(); } + virtual void setBlendType(BlendType type) { _blendType = type; } virtual BlendType getBlendType() const { return _blendType; } @@ -184,7 +189,7 @@ public: virtual void setName(const std::string &name) { _name = name; } virtual const std::string getName() const { return _name; } - virtual const BaseData *getWorldInfo() const { return _worldInfo; } + virtual BaseData *getWorldInfo() const { return _worldInfo; } protected: void applyParentTransform(Bone *parent); diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index adbea59a31..35d1fe95f3 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -198,8 +198,7 @@ void ColliderDetector::addContourData(ContourData *contourData) void ColliderDetector::addContourDataList(Array *contourDataList) { - Object *object = nullptr; - CCARRAY_FOREACH(contourDataList, object) + for(auto object : *contourDataList) { addContourData((ContourData *)object); } @@ -207,8 +206,7 @@ void ColliderDetector::addContourDataList(Array *contourDataList) void ColliderDetector::removeContourData(ContourData *contourData) { - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *body = (ColliderBody*)object; if (body && body->getContourData() == contourData) @@ -242,8 +240,7 @@ void ColliderDetector::setActive(bool active) } else { - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); @@ -256,10 +253,9 @@ void ColliderDetector::setActive(bool active) #elif ENABLE_PHYSICS_CHIPMUNK_DETECT if (_body) { - Object *object = nullptr; if (_active) { - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); @@ -271,7 +267,7 @@ void ColliderDetector::setActive(bool active) } else { - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); @@ -299,8 +295,7 @@ void ColliderDetector::setColliderFilter(ColliderFilter *filter) { *_filter = *filter; - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; colliderBody->setColliderFilter(filter); @@ -333,8 +328,7 @@ void ColliderDetector::updateTransform(AffineTransform &t) return; } - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); @@ -408,8 +402,7 @@ void ColliderDetector::setBody(b2Body *pBody) { _body = pBody; - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; @@ -420,7 +413,7 @@ void ColliderDetector::setBody(b2Body *pBody) b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.count()]; int i = 0; - CCARRAY_FOREACH(array, object) + for(auto object : *array) { ContourVertex2 *v = (ContourVertex2 *)object; b2bv[i].Set(v->x / PT_RATIO, v->y / PT_RATIO); @@ -459,8 +452,7 @@ void ColliderDetector::setBody(cpBody *pBody) { _body = pBody; - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index a4f1432727..46c7750d48 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -245,7 +245,7 @@ void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt) void DisplayFactory::addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { - ParticleDisplayData *adp = ParticleDisplayData::create(); ; + ParticleDisplayData *adp = ParticleDisplayData::create(); adp->copy((ParticleDisplayData *)displayData); decoDisplay->setDisplayData(adp); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index ce808ca3b9..a8c8f5d760 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -318,11 +318,9 @@ void DisplayManager::initDisplayList(BoneData *boneData) CS_RETURN_IF(!boneData); - Object *object = nullptr; - Array *displayDataList = &boneData->displayDataList; - CCARRAY_FOREACH(displayDataList, object) + for(auto object : boneData->displayDataList) { - DisplayData *displayData = (DisplayData *)object; + DisplayData *displayData = static_cast(object); DecorativeDisplay *decoDisplay = DecorativeDisplay::create(); decoDisplay->setDisplayData(displayData); From 2e80e95a37bb424d8cccc87ce7a3697d75b9b2fe Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 15:26:33 +0800 Subject: [PATCH 087/197] [Linux] compilation fix for PR #4099 --- cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp index a3ae0474d8..69967031a8 100644 --- a/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp +++ b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp @@ -46,7 +46,7 @@ extern "C" } filename.append(".lua"); - unsigned long codeBufferSize = 0; + long codeBufferSize = 0; unsigned char* codeBuffer = FileUtils::getInstance()->getFileData(filename.c_str(), "rb", &codeBufferSize); if (codeBuffer) From f6070406cd5ac2389392835fe101443554f4d343 Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Wed, 6 Nov 2013 15:31:58 +0800 Subject: [PATCH 088/197] Missing add "JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET " before calling JS_CallFunctionValue --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 3 +++ cocos/scripting/javascript/bindings/ScriptingCore.h | 2 ++ .../bindings/chipmunk/js_bindings_chipmunk_manual.cpp | 8 ++++++++ .../bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../bindings/cocosbuilder/cocosbuilder_specifics.hpp | 2 ++ .../bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp | 9 +++++++++ 6 files changed, 25 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 5d902c1c23..ab4afd4091 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -96,6 +96,9 @@ static void executeJSFunctionFromReservedSpot(JSContext *cx, JSObject *obj, if (func == JSVAL_VOID) { return; } jsval thisObj = JS_GetReservedSlot(obj, 1); JSAutoCompartment ac(cx, obj); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + if (thisObj == JSVAL_VOID) { JS_CallFunctionValue(cx, obj, func, 1, &dataVal, &retval); } else { diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 8df12fddc6..992569afc9 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -320,6 +320,8 @@ public: JS_RemoveObjectRoot(this->_cx, &this->_jsthis); } JSBool invoke(unsigned int argc, jsval *argv, jsval &rval) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + return JS_CallFunctionValue(this->_cx, this->_jsthis, this->_fval, argc, argv, &rval); } private: diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index 197a270e91..903b777fde 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -638,6 +638,8 @@ static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); @@ -662,6 +664,8 @@ static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); @@ -687,6 +691,8 @@ static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); @@ -705,6 +711,8 @@ static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 39e01fd1ef..60a40d7ff2 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -c93df276adb92b5e076db49c4f9482b8eb37d45c \ No newline at end of file +d922b0cdce5f5f90c7feca934b43c294a9585ab1 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp index f6b3252c57..774c75820b 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp @@ -14,6 +14,8 @@ public: jsval retval = JSVAL_NULL; if(!JSVAL_IS_VOID(_jsCallback) && !JSVAL_IS_VOID(_jsThisObj)) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, JSVAL_TO_OBJECT(_jsThisObj), _jsCallback, 0, NULL, &retval); } } diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp index 34ecbca985..4838fbcab2 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -73,6 +73,9 @@ void JSArmatureWrapper::movementCallbackFunc(cocostudio::Armature *pArmature, co valArr[2] = idVal; JS_AddValueRoot(cx, valArr); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 3, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } @@ -88,6 +91,9 @@ void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) jsval percentVal = DOUBLE_TO_JSVAL(percent); JS_AddValueRoot(cx, &percentVal); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 1, &percentVal, &retval); JS_RemoveValueRoot(cx, &percentVal); } @@ -113,6 +119,9 @@ void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *f valArr[3] = currentIndexVal; JS_AddValueRoot(cx, valArr); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } From efd8f629924e5cc71f2e7efca6ff52a5dd8db24d Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 15:40:06 +0800 Subject: [PATCH 089/197] add virtual --- cocos/editor-support/cocostudio/CCSkin.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 6e62da7d22..3d937a76bb 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,8 +39,8 @@ public: public: Skin(); - bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; - bool initWithFile(const char *pszFilename) override; + virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; + virtual bool initWithFile(const char *pszFilename) override; void updateArmatureTransform(); void updateTransform() override; From f36fd002cdff05a4a95bf0d35b4ba01534329eba Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Wed, 6 Nov 2013 15:40:23 +0800 Subject: [PATCH 090/197] Remove duplicate --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 2 -- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index ab4afd4091..dc3859eba1 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -97,8 +97,6 @@ static void executeJSFunctionFromReservedSpot(JSContext *cx, JSObject *obj, jsval thisObj = JS_GetReservedSlot(obj, 1); JSAutoCompartment ac(cx, obj); - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - if (thisObj == JSVAL_VOID) { JS_CallFunctionValue(cx, obj, func, 1, &dataVal, &retval); } else { diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 60a40d7ff2..4bf97ac9a7 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -d922b0cdce5f5f90c7feca934b43c294a9585ab1 \ No newline at end of file +b29fccdfcc5201f7a53a2c7896310afd9884ed8f \ No newline at end of file From 6c27a0df0b61e1750c34c290cbe72471b19d908d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 6 Nov 2013 15:43:29 +0800 Subject: [PATCH 091/197] issue #2771: make api more friendly --- cocos/physics/CCPhysicsBody.h | 8 ++--- cocos/physics/CCPhysicsContact.cpp | 3 +- cocos/physics/CCPhysicsContact.h | 6 ++-- cocos/physics/CCPhysicsJoint.h | 4 +-- cocos/physics/CCPhysicsShape.cpp | 12 +++---- cocos/physics/CCPhysicsShape.h | 34 +++++++++---------- cocos/physics/CCPhysicsWorld.cpp | 22 ++++++------ .../chipmunk/CCPhysicsHelper_chipmunk.h | 12 +++---- 8 files changed, 51 insertions(+), 50 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 4e6f60f038..6ae92e4b33 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -128,7 +128,7 @@ public: /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + inline PhysicsShape* getFirstShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } PhysicsShape* getShape(int tag) const; /* * @brief remove a shape from body @@ -238,13 +238,13 @@ public: //virtual Clonable* clone() const override; bool isResting() const; - inline bool isEnable() const { return _enable; } + inline bool isEnabled() const { return _enable; } void setEnable(bool enable); - inline bool isRotationEnable() const { return _rotationEnable; } + inline bool isRotationEnabled() const { return _rotationEnable; } void setRotationEnable(bool enable); - inline bool isGravityEnable() const { return _gravityEnable; } + inline bool isGravityEnabled() const { return _gravityEnable; } void setGravityEnable(bool enable); diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 71bdf5a1d0..9d6325c150 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -50,7 +50,7 @@ PhysicsContact::PhysicsContact() , _shapeB(nullptr) , _eventCode(EventCode::NONE) , _info(nullptr) -, _notify(true) +, _notificationEnable(true) , _begin(false) , _data(nullptr) , _contactInfo(nullptr) @@ -216,7 +216,6 @@ void EventListenerPhysicsContact::onEvent(EventCustom* event) bool ret = true; if (onContactBegin != nullptr - && contact.getNotify() && test(contact.getShapeA(), contact.getShapeB())) { contact._begin = true; diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 846761d1cb..7117d746ce 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -94,8 +94,8 @@ private: bool init(PhysicsShape* a, PhysicsShape* b); void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; - inline bool getNotify() const { return _notify; } - inline void setNotify(bool notify) { _notify = notify; } + inline bool isNotificationEnabled() const { return _notificationEnable; } + inline void setNotificationEnable(bool enable) { _notificationEnable = enable; } inline PhysicsWorld* getWorld() const { return _world; } inline void setWorld(PhysicsWorld* world) { _world = world; } inline void setResult(bool result) { _result = result; } @@ -113,7 +113,7 @@ private: PhysicsShape* _shapeB; EventCode _eventCode; PhysicsContactInfo* _info; - bool _notify; + bool _notificationEnable; bool _begin; bool _result; diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index ff5285b819..fea8ba4707 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -51,9 +51,9 @@ public: PhysicsBody* getBodyB() const { return _bodyB; } inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() const { return _enable; } + inline bool isEnabled() const { return _enable; } void setEnable(bool enable); - inline bool isCollisionEnable() const { return _collisionEnable; } + inline bool isCollisionEnabled() const { return _collisionEnable; } void setCollisionEnable(bool enable); protected: diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 89d0551cff..7cc64483cd 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -25,6 +25,8 @@ #include "CCPhysicsShape.h" #ifdef CC_USE_PHYSICS +#include + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) @@ -503,12 +505,10 @@ float PhysicsShapeBox::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapeBox::getPoints(Point* points) const +void PhysicsShapeBox::getPoints(Point* points) const { cpShape* shape = _info->getShapes().front(); - return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); - - return points; + PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } Size PhysicsShapeBox::getSize() const @@ -599,10 +599,10 @@ Point PhysicsShapePolygon::getPoint(int i) const return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->getShapes().front(), i)); } -Point* PhysicsShapePolygon::getPoints(Point* points) const +void PhysicsShapePolygon::getPoints(Point* outPoints) const { cpShape* shape = _info->getShapes().front(); - return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); + PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, outPoints, ((cpPolyShape*)shape)->numVerts); } int PhysicsShapePolygon::getPointsCount() const diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index b9525506d1..8ff31f49df 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -154,17 +154,17 @@ public: static float calculateArea(float radius); static float calculateMoment(float mass, float radius, const Point& offset = Point::ZERO); - float calculateDefaultArea() override; - float calculateDefaultMoment() override; + virtual float calculateDefaultArea() override; + virtual float calculateDefaultMoment() override; float getRadius() const; - Point getOffset() override; + virtual Point getOffset() override; protected: bool init(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeCircle(); - ~PhysicsShapeCircle(); + virtual ~PhysicsShapeCircle(); }; /** A box shape */ @@ -175,12 +175,12 @@ public: static float calculateArea(const Size& size); static float calculateMoment(float mass, const Size& size, const Point& offset = Point::ZERO); - float calculateDefaultArea() override; - float calculateDefaultMoment() override; + virtual float calculateDefaultArea() override; + virtual float calculateDefaultMoment() override; - Point* getPoints(Point* points) const; + void getPoints(Point* outPoints) const; Size getSize() const; - Point getOffset() override { return _offset; } + virtual Point getOffset() override { return _offset; } protected: bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); @@ -205,9 +205,9 @@ public: float calculateDefaultMoment() override; Point getPoint(int i) const; - Point* getPoints(Point* points) const; + void getPoints(Point* outPoints) const; int getPointsCount() const; - Point getCenter() override; + virtual Point getCenter() override; protected: bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); @@ -227,7 +227,7 @@ public: Point getPointA() const; Point getPointB() const; - Point getCenter() override; + virtual Point getCenter() override; protected: bool init(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -247,8 +247,8 @@ class PhysicsShapeEdgeBox : public PhysicsShape { public: static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Point& offset = Point::ZERO); - Point getOffset() override { return _offset; } - Point* getPoints(const Point* points) const; + virtual Point getOffset() override { return _offset; } + void getPoints(const Point* outPoints) const; int getPointsCount() const; protected: @@ -269,8 +269,8 @@ class PhysicsShapeEdgePolygon : public PhysicsShape { public: static PhysicsShapeEdgePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points) const; + virtual Point getCenter() override; + void getPoints(Point* outPoints) const; int getPointsCount() const; protected: @@ -291,8 +291,8 @@ class PhysicsShapeEdgeChain : public PhysicsShape { public: static PhysicsShapeEdgeChain* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points) const; + virtual Point getCenter() override; + void getPoints(Point* outPoints) const; int getPointsCount() const; protected: diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 2a067720c1..3c5956b85c 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -25,6 +25,8 @@ #include "CCPhysicsWorld.h" #ifdef CC_USE_PHYSICS +#include + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) @@ -361,12 +363,12 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) body->removeFromWorld(); } - if (body->isEnable()) + if (body->isEnabled()) { body->_world = this; //is gravity enable - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } @@ -424,7 +426,7 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) } // reset the gravity - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } @@ -707,13 +709,13 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) continue; } - if (!joint->isCollisionEnable()) + if (!joint->isCollisionEnabled()) { PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA(); if (body == bodyB) { - contact.setNotify(false); + contact.setNotificationEnable(false); return false; } } @@ -723,7 +725,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) { - contact.setNotify(false); + contact.setNotificationEnable(false); } if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) @@ -750,7 +752,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { cpArbiterIgnore(static_cast(contact._contactInfo)); return true; @@ -767,7 +769,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { return; } @@ -781,7 +783,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { return; } @@ -802,7 +804,7 @@ void PhysicsWorld::setGravity(Point gravity) PhysicsBody* body = dynamic_cast(child); // reset gravity for body - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); body->applyForce(gravity); diff --git a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index 52d0023b8b..094a6b6c35 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -46,24 +46,24 @@ public: static cpBB rect2cpbb(const Rect& rect) { return cpBBNew(rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); } static Rect cpbb2rect(const cpBB& bb) { return Rect(bb.l, bb.b, bb.r, bb.t); } - static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) + static Point* cpvs2points(const cpVect* cpvs, Point* out, int count) { for (int i = 0; i < count; ++i) { - points[i] = cpv2point(cpvs[i]); + out[i] = cpv2point(cpvs[i]); } - return points; + return out; } - static cpVect* points2cpvs(const Point* points, cpVect* cpvs, int count) + static cpVect* points2cpvs(const Point* points, cpVect* out, int count) { for (int i = 0; i < count; ++i) { - cpvs[i] = point2cpv(points[i]); + out[i] = point2cpv(points[i]); } - return cpvs; + return out; } }; From ba8b4866e289a89fae87b6fb456a7bdfbae820f1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 15:57:57 +0800 Subject: [PATCH 092/197] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 0c11df97d6..37e302de05 100644 --- a/AUTHORS +++ b/AUTHORS @@ -628,6 +628,7 @@ Developers: HoGarfield (garfield_ho) Fixed a bug that CCBReader can't play sequence automatically in JSB. Could not set next animation in CCBAnimationCompleted callback. + Fixed missing to add JSAutoCompartment when invoking JS functions from C++. lite3 Fixed a bug that Node's anchor point was changed after being added to ScrollView. From d990699417ac4a5dee2af27d84e132553a3c8a62 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 6 Nov 2013 08:00:35 +0000 Subject: [PATCH 093/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index e150a74a02..9b0b068f92 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit e150a74a028e26cff0dac7d2238e2cd16fbaf370 +Subproject commit 9b0b068f923249440b8a8c758b1c06d29f6cbdfe From e0aa82da138c7a789e3335eac249143b23f78e91 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 16:04:06 +0800 Subject: [PATCH 094/197] Merge master branch to develop branch --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../cocostudio/CCActionNode.cpp | 2 +- .../cocostudio/CCSGUIReader.cpp | 35 +- .../cocostudio/CCSSceneReader.cpp | 4 +- cocos/gui/CocosGUI.h | 5 +- cocos/gui/Layout.cpp | 785 -------- cocos/gui/UIButton.cpp | 176 +- cocos/gui/UIButton.h | 19 +- cocos/gui/UICheckBox.cpp | 64 +- cocos/gui/UICheckBox.h | 17 +- cocos/gui/UIDragPanel.cpp | 1269 ------------ cocos/gui/UIDragPanel.h | 367 ---- cocos/gui/UIHelper.cpp | 134 +- cocos/gui/UIHelper.h | 65 +- cocos/gui/UIImageView.cpp | 49 +- cocos/gui/UIImageView.h | 16 +- cocos/gui/UIInputManager.cpp | 6 +- cocos/gui/UIInputManager.h | 4 +- cocos/gui/UILabel.cpp | 39 +- cocos/gui/UILabel.h | 13 +- cocos/gui/UILabelAtlas.cpp | 51 +- cocos/gui/UILabelAtlas.h | 19 +- cocos/gui/UILabelBMFont.cpp | 45 +- cocos/gui/UILabelBMFont.h | 9 +- cocos/gui/UILayer.cpp | 4 +- cocos/gui/UILayout.cpp | 1010 ++++++++++ cocos/gui/{Layout.h => UILayout.h} | 47 +- cocos/gui/UILayoutDefine.cpp | 2 +- cocos/gui/UILayoutDefine.h | 28 +- ...outParameter.cpp => UILayoutParameter.cpp} | 39 +- ...{LayoutParameter.h => UILayoutParameter.h} | 42 +- cocos/gui/UIListView.cpp | 1753 ++++------------- cocos/gui/UIListView.h | 294 ++- cocos/gui/UILoadingBar.cpp | 98 +- cocos/gui/UILoadingBar.h | 7 +- cocos/gui/UIPageView.cpp | 151 +- cocos/gui/UIPageView.h | 26 +- cocos/gui/UIRootWidget.cpp | 6 +- cocos/gui/UIRootWidget.h | 10 +- cocos/gui/UIScrollInterface.h | 1 - cocos/gui/UIScrollView.cpp | 1595 +++++++++++---- cocos/gui/UIScrollView.h | 216 +- cocos/gui/UISlider.cpp | 138 +- cocos/gui/UISlider.h | 9 +- cocos/gui/UITextField.cpp | 149 +- cocos/gui/UITextField.h | 46 +- cocos/gui/UIWidget.cpp | 305 +-- cocos/gui/UIWidget.h | 71 +- .../CocoStudioGUITest/CocosGUIScene.cpp | 1 - .../UIDragPanelTest/UIDragPanelTest.cpp | 160 +- .../UIDragPanelTest/UIDragPanelTest.h | 2 - .../UIListViewTest/UIListViewTest.cpp | 202 +- .../UIListViewTest/UIListViewTest.h | 2 - .../UIPageViewTest/UIPageViewTest.cpp | 4 +- .../UIPanelTest/UIPanelTest.cpp | 56 +- .../CocoStudioGUITest/UIScene.cpp | 3 +- .../CocoStudioGUITest/UIScene.h | 2 +- .../UIScrollViewTest/UIScrollViewTest.cpp | 7 +- .../UITextFieldTest/UITextFieldTest.cpp | 10 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 1 - 61 files changed, 4104 insertions(+), 5590 deletions(-) delete mode 100644 cocos/gui/Layout.cpp delete mode 100644 cocos/gui/UIDragPanel.cpp delete mode 100644 cocos/gui/UIDragPanel.h create mode 100644 cocos/gui/UILayout.cpp rename cocos/gui/{Layout.h => UILayout.h} (89%) rename cocos/gui/{LayoutParameter.cpp => UILayoutParameter.cpp} (65%) rename cocos/gui/{LayoutParameter.h => UILayoutParameter.h} (82%) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index ac519a56c8..0d15fff578 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -5a0361664f33af4303065c98da4b8d8e4efe48b4 \ No newline at end of file +12034db6a7c20a09b3e866ab79a536bfc0208d3f \ 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 ba37de5f5d..07c8b22d15 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b473303312be3b69891020b5fb470dd382f31284 \ No newline at end of file +f441e32e09388d5c434035e100e591cf9a6d29fd \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index fceca8816c..c0484a9dd8 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -159,7 +159,7 @@ void ActionNode::initActionNodeFromRoot(Object* root) UIWidget* rootWidget = dynamic_cast(root); if (rootWidget != NULL) { - UIWidget* widget = UIHelper::instance()->seekActionWidgetByActionTag(rootWidget, getActionTag()); + UIWidget* widget = UIHelper::seekActionWidgetByActionTag(rootWidget, getActionTag()); if (widget != NULL) { setObject(widget); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 77cb5d56de..8fd5fba3a1 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -152,7 +152,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "Panel") == 0) { - widget = Layout::create(); + widget = UILayout::create(); setPropsForPanelFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "Slider") == 0) @@ -177,7 +177,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "DragPanel") == 0) { - widget = UIDragPanel::create(); + widget = UIScrollView::create(); setPropsForDragPanelFromJsonDictionary(widget, uiOptions); } @@ -232,20 +232,20 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) const char* file = DICTOOL->getStringValueFromArray_json(jsonDict, "textures", i); std::string tp = m_strFilePath; tp.append(file); - CCUIHELPER->addSpriteFrame(tp.c_str()); +// CCUIHELPER->addSpriteFrame(tp.c_str()); } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); - CCUIHELPER->setFileDesignWidth(winSize.width); - CCUIHELPER->setFileDesignHeight(winSize.height); +// CCUIHELPER->setFileDesignWidth(winSize.width); +// CCUIHELPER->setFileDesignHeight(winSize.height); } else { - CCUIHELPER->setFileDesignWidth(fileDesignWidth); - CCUIHELPER->setFileDesignHeight(fileDesignHeight); +// CCUIHELPER->setFileDesignWidth(fileDesignWidth); +// CCUIHELPER->setFileDesignHeight(fileDesignHeight); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); @@ -253,7 +253,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) /* *********temp********* */ if (widget->getContentSize().equals(Size::ZERO)) { - Layout* rootWidget = dynamic_cast(widget); + UILayout* rootWidget = dynamic_cast(widget); rootWidget->setSize(Size(fileDesignWidth, fileDesignHeight)); } /* ********************** */ @@ -792,7 +792,7 @@ void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictio setPropsForWidgetFromJsonDictionary(widget, options); UILabel* label = (UILabel*)widget; bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, "touchScaleEnable"); - label->setTouchScaleChangeAble(touchScaleChangeAble); + label->setTouchScaleChangeEnabled(touchScaleChangeAble); const char* text = DICTOOL->getStringValue_json(options, "text"); label->setText(text); bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); @@ -877,10 +877,9 @@ void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonD void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { setPropsForWidgetFromJsonDictionary(widget, options); - Layout* containerWidget = (Layout*)widget; + UILayout* containerWidget = (UILayout*)widget; if (!dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget)) + && !dynamic_cast(containerWidget)) { containerWidget->setClippingEnabled(DICTOOL->getBooleanValue_json(options, "clipAble")); } @@ -892,7 +891,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictio if (m_bOlderVersion) { setPropsForContainerWidgetFromJsonDictionary(widget, options); - Layout* panel = (Layout*)widget; + UILayout* panel = (UILayout*)widget; bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); int cr = DICTOOL->getIntValue_json(options, "bgColorR"); @@ -959,7 +958,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictio else { setPropsForContainerWidgetFromJsonDictionary(widget, options); - Layout* panel = (Layout*)widget; + UILayout* panel = (UILayout*)widget; bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); int cr = DICTOOL->getIntValue_json(options, "bgColorR"); @@ -1394,7 +1393,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDi //textField->setSize(CCSizeMake(dw, dh)); } bool maxLengthEnable = DICTOOL->getBooleanValue_json(options, "maxLengthEnable"); - textField->setMaxLengthEnable(maxLengthEnable); + textField->setMaxLengthEnabled(maxLengthEnable); if (maxLengthEnable) { @@ -1402,7 +1401,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDi textField->setMaxLength(maxLength); } bool passwordEnable = DICTOOL->getBooleanValue_json(options, "passwordEnable"); - textField->setPasswordEnable(passwordEnable); + textField->setPasswordEnabled(passwordEnable); if (passwordEnable) { textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, "passwordStyleText")); @@ -1557,10 +1556,10 @@ void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, Json { setPropsForPanelFromJsonDictionary(widget, options); - UIDragPanel* dragPanel = (UIDragPanel*)widget; + UIScrollView* dragPanel = (UIScrollView*)widget; bool bounceEnable = DICTOOL->getBooleanValue_json(options, "bounceEnable"); - dragPanel->setBounceEnable(bounceEnable); + dragPanel->setBounceEnabled(bounceEnable); float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 3d8bc7fd8c..c660b91990 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -320,8 +320,8 @@ namespace cocostudio { { gui::UILayer *pLayer = gui::UILayer::create(); pLayer->scheduleUpdate(); - UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); - pLayer->addWidget(widget); +// UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); +// pLayer->addWidget(widget); ComRender *pRender = ComRender::create(pLayer, "GUIComponent"); if (pComName != NULL) { diff --git a/cocos/gui/CocosGUI.h b/cocos/gui/CocosGUI.h index 497c4f89b6..663aff26e7 100644 --- a/cocos/gui/CocosGUI.h +++ b/cocos/gui/CocosGUI.h @@ -27,7 +27,7 @@ #include "gui/UIWidget.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIRootWidget.h" #include "gui/UIButton.h" #include "gui/UICheckBox.h" @@ -36,10 +36,9 @@ #include "gui/UILabelAtlas.h" #include "gui/UILoadingBar.h" #include "gui/UIScrollView.h" +#include "gui/UIListView.h" #include "gui/UISlider.h" #include "gui/UITextField.h" -#include "gui/UIListView.h" -#include "gui/UIDragPanel.h" #include "gui/UILabelBMFont.h" #include "gui/UIPageView.h" #include "gui/UIHelper.h" diff --git a/cocos/gui/Layout.cpp b/cocos/gui/Layout.cpp deleted file mode 100644 index a9e4f75a30..0000000000 --- a/cocos/gui/Layout.cpp +++ /dev/null @@ -1,785 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "gui/Layout.h" -#include "gui/UILayer.h" -#include "gui/UIHelper.h" -#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - - using namespace cocos2d; - using namespace cocos2d::extension; - -namespace gui { - -#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) - -Layout::Layout(): -_clippingEnabled(false), -_backGroundScale9Enabled(false), -_backGroundImage(NULL), -_backGroundImageFileName(""), -_backGroundImageCapInsets(Rect::ZERO), -_colorType(LAYOUT_COLOR_NONE), -_bgImageTexType(UI_TEX_TYPE_LOCAL), -_colorRender(NULL), -_gradientRender(NULL), -_cColor(Color3B::WHITE), -_gStartColor(Color3B::WHITE), -_gEndColor(Color3B::WHITE), -_alongVector(Point(0.0f, -1.0f)), -_cOpacity(255), -_backGroundImageTextureSize(Size::ZERO), -_layoutType(LAYOUT_ABSOLUTE) -{ - _widgetType = WidgetTypeContainer; -} - -Layout::~Layout() -{ -} - -Layout* Layout::create() -{ - Layout* layout = new Layout(); - if (layout && layout->init()) - { - layout->autorelease(); - return layout; - } - CC_SAFE_DELETE(layout); - return NULL; -} - -bool Layout::init() -{ - _children = CCArray::create(); - _children->retain(); - initRenderer(); - _renderer->retain(); - _renderer->setZOrder(_widgetZOrder); - RGBAProtocol* renderRGBA = dynamic_cast(_renderer); - if (renderRGBA) - { - renderRGBA->setCascadeColorEnabled(false); - renderRGBA->setCascadeOpacityEnabled(false); - } - ignoreContentAdaptWithSize(false); - setSize(Size::ZERO); - setBright(true); - setAnchorPoint(Point(0, 0)); - _scheduler = Director::getInstance()->getScheduler(); - CC_SAFE_RETAIN(_scheduler); - return true; -} - -void Layout::initRenderer() -{ - _renderer = RectClippingNode::create(); -} - -bool Layout::isClippingEnabled() -{ - return _clippingEnabled; -} - -bool Layout::hitTest(const Point &pt) -{ - Point nsp = _renderer->convertToNodeSpace(pt); - Rect bb = Rect(0.0f, 0.0f, _size.width, _size.height); - if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) - { - return true; - } - return false; -} - -void Layout::setClippingEnabled(bool able) -{ - _clippingEnabled = able; - DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); -} - -void Layout::onSizeChanged() -{ - DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); - doLayout(); - if (_backGroundImage) - { - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - } - if (_colorRender) - { - _colorRender->setContentSize(_size); - } - if (_gradientRender) - { - _gradientRender->setContentSize(_size); - } -} - -void Layout::setBackGroundImageScale9Enabled(bool able) -{ - if (_backGroundScale9Enabled == able) - { - return; - } - _renderer->removeChild(_backGroundImage, true); - _backGroundImage = NULL; - _backGroundScale9Enabled = able; - if (_backGroundScale9Enabled) - { - _backGroundImage = Scale9Sprite::create(); - _renderer->addChild(_backGroundImage); - } - else - { - _backGroundImage = Sprite::create(); - _renderer->addChild(_backGroundImage); - } - _backGroundImage->setZOrder(-1); - setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); - setBackGroundImageCapInsets(_backGroundImageCapInsets); -} - -void Layout::setBackGroundImage(const char* fileName,TextureResType texType) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - if (_backGroundImage == NULL) - { - addBackGroundImage(); - } - _backGroundImageFileName = fileName; - _bgImageTexType = texType; - if (_backGroundScale9Enabled) - { - switch (_bgImageTexType) - { - case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); - break; - case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); - break; - default: - break; - } - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - else - { - switch (_bgImageTexType) - { - case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); - break; - case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); - break; - default: - break; - } - } - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setColor(getColor()); - dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); - } - else - { - dynamic_cast(_backGroundImage)->setColor(getColor()); - dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); - } - _backGroundImageTextureSize = _backGroundImage->getContentSize(); - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); -} - -void Layout::setBackGroundImageCapInsets(const Rect &capInsets) -{ - _backGroundImageCapInsets = capInsets; - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setCapInsets(capInsets); - } -} - -void Layout::addBackGroundImage() -{ - if (_backGroundScale9Enabled) - { - _backGroundImage = Scale9Sprite::create(); - _backGroundImage->setZOrder(-1); - _renderer->addChild(_backGroundImage); - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - else - { - _backGroundImage = CCSprite::create(); - _backGroundImage->setZOrder(-1); - _renderer->addChild(_backGroundImage); - } - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); -} - -void Layout::removeBackGroundImage() -{ - if (!_backGroundImage) - { - return; - } - _renderer->removeChild(_backGroundImage, true); - _backGroundImage = NULL; - _backGroundImageFileName = ""; - _backGroundImageTextureSize = Size::ZERO; -} - -void Layout::setBackGroundColorType(LayoutBackGroundColorType type) -{ - if (_colorType == type) - { - return; - } - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - if (_colorRender) - { - _renderer->removeChild(_colorRender, true); - _colorRender = NULL; - } - if (_gradientRender) - { - _renderer->removeChild(_gradientRender, true); - _gradientRender = NULL; - } - break; - case LAYOUT_COLOR_SOLID: - if (_colorRender) - { - _renderer->removeChild(_colorRender, true); - _colorRender = NULL; - } - break; - case LAYOUT_COLOR_GRADIENT: - if (_gradientRender) - { - _renderer->removeChild(_gradientRender, true); - _gradientRender = NULL; - } - break; - default: - break; - } - _colorType = type; - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - break; - case LAYOUT_COLOR_SOLID: - _colorRender = CCLayerColor::create(); - _colorRender->setContentSize(_size); - _colorRender->setOpacity(_cOpacity); - _colorRender->setColor(_cColor); - _renderer->addChild(_colorRender,-2); - break; - case LAYOUT_COLOR_GRADIENT: - _gradientRender = CCLayerGradient::create(); - _gradientRender->setContentSize(_size); - _gradientRender->setOpacity(_cOpacity); - _gradientRender->setStartColor(_gStartColor); - _gradientRender->setEndColor(_gEndColor); - _gradientRender->setVector(_alongVector); - _renderer->addChild(_gradientRender,-2); - break; - default: - break; - } -} - -void Layout::setBackGroundColor(const Color3B &color) -{ - _cColor = color; - if (_colorRender) - { - _colorRender->setColor(color); - } -} - -void Layout::setBackGroundColor(const Color3B &startColor, const Color3B &endColor) -{ - _gStartColor = startColor; - if (_gradientRender) - { - _gradientRender->setStartColor(startColor); - } - _gEndColor = endColor; - if (_gradientRender) - { - _gradientRender->setEndColor(endColor); - } -} - -void Layout::setBackGroundColorOpacity(int opacity) -{ - _cOpacity = opacity; - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - break; - case LAYOUT_COLOR_SOLID: - _colorRender->setOpacity(opacity); - break; - case LAYOUT_COLOR_GRADIENT: - _gradientRender->setOpacity(opacity); - break; - default: - break; - } -} - -void Layout::setBackGroundColorVector(const Point &vector) -{ - _alongVector = vector; - if (_gradientRender) - { - _gradientRender->setVector(vector); - } -} - -void Layout::setColor(const Color3B &color) -{ - UIWidget::setColor(color); - if (_backGroundImage) - { - RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); - if (rgbap) - { - rgbap->setColor(color); - } - } -} - -void Layout::setOpacity(int opacity) -{ - UIWidget::setOpacity(opacity); - if (_backGroundImage) - { - RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); - if (rgbap) - { - rgbap->setOpacity(opacity); - } - } -} - -const Size& Layout::getBackGroundImageTextureSize() const -{ - return _backGroundImageTextureSize; -} - -const Size& Layout::getContentSize() const -{ - return _renderer->getContentSize(); -} - -void Layout::setLayoutType(LayoutType type) -{ - _layoutType = type; -} - -LayoutType Layout::getLayoutType() const -{ - return _layoutType; -} - -void Layout::doLayout() -{ - switch (_layoutType) - { - case LAYOUT_ABSOLUTE: - break; - case LAYOUT_LINEAR_VERTICAL: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - float topBoundary = layoutSize.height; - for (int i=0; i(layoutChildrenArray->arr[i]); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - - if (layoutParameter) - { - WidgetType childType = child->getWidgetType(); - UILinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; - float finalPosY = childType == WidgetTypeWidget ? topBoundary - ((1.0f-ap.y) * cs.height) : topBoundary - cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_LEFT: - break; - case LINEAR_GRAVITY_RIGHT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; - break; - case LINEAR_GRAVITY_CENTER_HORIZONTAL: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width / 2.0f - cs.width * (0.5f-ap.x) : (layoutSize.width - cs.width) * 0.5f; - break; - default: - break; - } - UIMargin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - topBoundary = child->getBottomInParent() - mg.bottom; - } - } - break; - } - case LAYOUT_LINEAR_HORIZONTAL: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - float leftBoundary = 0.0f; - for (int i=0; i(layoutChildrenArray->arr[i]); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - - if (layoutParameter) - { - WidgetType childType = child->getWidgetType(); - UILinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = childType == WidgetTypeWidget ? leftBoundary + (ap.x * cs.width) : leftBoundary; - float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - (1.0f - ap.y) * cs.height : layoutSize.height - cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_TOP: - break; - case LINEAR_GRAVITY_BOTTOM: - finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; - break; - case LINEAR_GRAVITY_CENTER_VERTICAL: - finalPosY = childType == WidgetTypeWidget ? layoutSize.height/2.0f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - default: - break; - } - UIMargin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - leftBoundary = child->getRightInParent() + mg.right; - } - } - break; - } - case LAYOUT_RELATIVE: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - for (int i=0; i(layoutChildrenArray->arr[i]); - WidgetType childType = child->getWidgetType(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - if (layoutParameter) - { - float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; - float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - ((1.0f - ap.y) * cs.height) : layoutSize.height - cs.height; - UIRelativeAlign align = layoutParameter->getAlign(); - const char* relativeName = layoutParameter->getRelativeToWidgetName(); - UIWidget* relativeWidget = NULL; - if (relativeName && strcmp(relativeName, "")) - { - relativeWidget = CCUIHELPER->seekWidgetByRelativeName(this, relativeName); - } - switch (align) - { - case RELATIVE_ALIGN_NONE: - break; - case RELATIVE_ALIGN_PARENT_LEFT: - break; - case RELATIVE_ALIGN_PARENT_TOP: - break; - case RELATIVE_ALIGN_PARENT_RIGHT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; - break; - case RELATIVE_ALIGN_PARENT_BOTTOM: - finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; - break; - case RELATIVE_CENTER_IN_PARENT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; - finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - case RELATIVE_CENTER_HORIZONTAL: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; - break; - case RELATIVE_CENTER_VERTICAL: - finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_LEFT_OF_CENTER: - break; - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - if (relativeWidget) - { - float locationRight = relativeWidget->getLeftInParent(); - float locationBottom = relativeWidget->getBottomInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - break; - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - if (relativeWidget) - { - float locationLeft = relativeWidget->getRightInParent(); - float locationBottom = relativeWidget->getBottomInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - if (relativeWidget) - { - float locationBottom = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_ABOVE_CENTER: - break; - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - if (relativeWidget) - { - float locationBottom = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getBottomInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_BELOW_CENTER: - break; - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getBottomInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - default: - break; - } - UIMargin relativeWidgetMargin; - UIMargin mg; - if (relativeWidget) - { - relativeWidgetMargin = relativeWidget->getLayoutParameter()->getMargin(); - mg = child->getLayoutParameter()->getMargin(); - } - //handle margin - switch (align) - { - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - case RELATIVE_LOCATION_ABOVE_CENTER: - finalPosY += relativeWidgetMargin.top; - finalPosY += mg.bottom; - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - case RELATIVE_LOCATION_BELOW_CENTER: - finalPosY -= relativeWidgetMargin.bottom; - finalPosY -= mg.top; - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - case RELATIVE_LOCATION_LEFT_OF_CENTER: - finalPosX -= relativeWidgetMargin.left; - finalPosX -= mg.right; - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - finalPosX += relativeWidgetMargin.right; - finalPosX += mg.left; - break; - default: - break; - } - child->setPosition(Point(finalPosX, finalPosY)); - } - } - break; - } - default: - break; - } -} - -const char* Layout::getDescription() const -{ - return "Layout"; -} - -RectClippingNode::RectClippingNode(): -m_pInnerStencil(NULL), -_enabled(true), -_clippingSize(Size(50.0f, 50.0f)), -_clippingEnabled(false) -{ - -} - -RectClippingNode::~RectClippingNode() -{ - -} - -RectClippingNode* RectClippingNode::create() -{ - RectClippingNode *pRet = new RectClippingNode(); - if (pRet && pRet->init()) - { - pRet->autorelease(); - } - else - { - CC_SAFE_DELETE(pRet); - } - - return pRet; -} - -bool RectClippingNode::init() -{ - m_pInnerStencil = CCDrawNode::create(); - rect[0] = Point(0, 0); - rect[1] = Point(_clippingSize.width, 0); - rect[2] = Point(_clippingSize.width, _clippingSize.height); - rect[3] = Point(0, _clippingSize.height); - - Color4F green(0, 1, 0, 1); - m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); - if (CCClippingNode::init(m_pInnerStencil)) - { - return true; - } - return false; -} - - -void RectClippingNode::setClippingSize(const Size &size) -{ - setContentSize(size); - _clippingSize = size; - rect[0] = Point(0, 0); - rect[1] = Point(_clippingSize.width, 0); - rect[2] = Point(_clippingSize.width, _clippingSize.height); - rect[3] = Point(0, _clippingSize.height); - Color4F green(0, 1, 0, 1); - m_pInnerStencil->clear(); - m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); -} - -void RectClippingNode::setClippingEnabled(bool enabled) -{ - _clippingEnabled = enabled; -} - -void RectClippingNode::visit() -{ - if (!_enabled) - { - return; - } - if (_clippingEnabled) - { - CCClippingNode::visit(); - } - else - { - CCNode::visit(); - } -} - -void RectClippingNode::setEnabled(bool enabled) -{ - _enabled = enabled; -} - -bool RectClippingNode::isEnabled() const -{ - return _enabled; -} - -} diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 12cc3cc932..b0c0c89630 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -25,9 +25,6 @@ #include "gui/UIButton.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - using namespace cocos2d; - using namespace cocos2d::extension; - namespace gui { #define NORMALRENDERERZ (0) @@ -45,9 +42,9 @@ _clickedFileName(""), _disabledFileName(""), _prevIgnoreSize(true), _scale9Enabled(false), -_capInsetsNormal(Rect::ZERO), -_capInsetsPressed(Rect::ZERO), -_capInsetsDisabled(Rect::ZERO), +_capInsetsNormal(cocos2d::Rect::ZERO), +_capInsetsPressed(cocos2d::Rect::ZERO), +_capInsetsDisabled(cocos2d::Rect::ZERO), _normalTexType(UI_TEX_TYPE_LOCAL), _pressedTexType(UI_TEX_TYPE_LOCAL), _disabledTexType(UI_TEX_TYPE_LOCAL), @@ -55,7 +52,7 @@ _normalTextureSize(_size), _pressedTextureSize(_size), _disabledTextureSize(_size), _pressedActionEnabled(false), -_titleColor(Color3B::WHITE) +_titleColor(cocos2d::Color3B::WHITE) { } @@ -88,10 +85,10 @@ bool UIButton::init() void UIButton::initRenderer() { UIWidget::initRenderer(); - _buttonNormalRenderer = Sprite::create(); - _buttonClickedRenderer = Sprite::create(); - _buttonDisableRenderer = Sprite::create(); - _titleRenderer = LabelTTF::create(); + _buttonNormalRenderer = cocos2d::Sprite::create(); + _buttonClickedRenderer = cocos2d::Sprite::create(); + _buttonDisableRenderer = cocos2d::Sprite::create(); + _titleRenderer = cocos2d::LabelTTF::create(); _renderer->addChild(_buttonNormalRenderer,NORMALRENDERERZ); _renderer->addChild(_buttonClickedRenderer,PRESSEDRENDERERZ); _renderer->addChild(_buttonDisableRenderer,DISABLEDRENDERERZ); @@ -117,15 +114,15 @@ void UIButton::setScale9Enabled(bool able) _buttonDisableRenderer = NULL; if (_scale9Enabled) { - _buttonNormalRenderer = Scale9Sprite::create(); - _buttonClickedRenderer = Scale9Sprite::create(); - _buttonDisableRenderer = Scale9Sprite::create(); + _buttonNormalRenderer = cocos2d::extension::Scale9Sprite::create(); + _buttonClickedRenderer = cocos2d::extension::Scale9Sprite::create(); + _buttonDisableRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _buttonNormalRenderer = CCSprite::create(); - _buttonClickedRenderer = CCSprite::create(); - _buttonDisableRenderer = CCSprite::create(); + _buttonNormalRenderer = cocos2d::Sprite::create(); + _buttonClickedRenderer = cocos2d::Sprite::create(); + _buttonDisableRenderer = cocos2d::Sprite::create(); } loadTextureNormal(_normalFileName.c_str(), _normalTexType); @@ -179,32 +176,33 @@ void UIButton::loadTextureNormal(const char* normal,TextureResType texType) switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); break; default: break; } - dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); - dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); + dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setCapInsets(_capInsetsNormal); } else { switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); break; default: break; } - dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); - dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); + dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); } _normalTextureSize = _buttonNormalRenderer->getContentSize(); updateAnchorPoint(); @@ -224,32 +222,33 @@ void UIButton::loadTexturePressed(const char* selected,TextureResType texType) switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); break; default: break; } - dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); - dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); + dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setCapInsets(_capInsetsPressed); } else { switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); break; default: break; } - dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); - dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); + dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); } _pressedTextureSize = _buttonClickedRenderer->getContentSize(); updateAnchorPoint(); @@ -269,73 +268,74 @@ void UIButton::loadTextureDisabled(const char* disabled,TextureResType texType) switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); break; default: break; } - dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); - dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); + dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setCapInsets(_capInsetsDisabled); } else { switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); break; default: break; } - dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); - dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); + dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); } _disabledTextureSize = _buttonDisableRenderer->getContentSize(); updateAnchorPoint(); disabledTextureScaleChangedWithSize(); } -void UIButton::setCapInsets(const Rect &capInsets) +void UIButton::setCapInsets(const cocos2d::Rect &capInsets) { setCapInsetsNormalRenderer(capInsets); setCapInsetsPressedRenderer(capInsets); setCapInsetsDisabledRenderer(capInsets); } -void UIButton::setCapInsetsNormalRenderer(const Rect &capInsets) +void UIButton::setCapInsetsNormalRenderer(const cocos2d::Rect &capInsets) { _capInsetsNormal = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonNormalRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonNormalRenderer)->setCapInsets(capInsets); } -void UIButton::setCapInsetsPressedRenderer(const Rect &capInsets) +void UIButton::setCapInsetsPressedRenderer(const cocos2d::Rect &capInsets) { _capInsetsPressed = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonClickedRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonClickedRenderer)->setCapInsets(capInsets); } -void UIButton::setCapInsetsDisabledRenderer(const Rect &capInsets) +void UIButton::setCapInsetsDisabledRenderer(const cocos2d::Rect &capInsets) { _capInsetsDisabled = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonDisableRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonDisableRenderer)->setCapInsets(capInsets); } void UIButton::onPressStateChangedToNormal() @@ -348,9 +348,9 @@ void UIButton::onPressStateChangedToNormal() _buttonNormalRenderer->stopAllActions(); _buttonClickedRenderer->stopAllActions(); _buttonDisableRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, 1.0f); - Action *zoomAction1 = ScaleTo::create(0.05f, 1.0f); - Action *zoomAction2 = ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction = cocos2d::ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction1 = cocos2d::ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction2 = cocos2d::ScaleTo::create(0.05f, 1.0f); _buttonNormalRenderer->runAction(zoomAction); _buttonClickedRenderer->runAction(zoomAction1); _buttonDisableRenderer->runAction(zoomAction2); @@ -367,9 +367,9 @@ void UIButton::onPressStateChangedToPressed() _buttonNormalRenderer->stopAllActions(); _buttonClickedRenderer->stopAllActions(); _buttonDisableRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, 1.1f); - Action *zoomAction1 = ScaleTo::create(0.05f, 1.1f); - Action *zoomAction2 = ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction = cocos2d::ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction1 = cocos2d::ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction2 = cocos2d::ScaleTo::create(0.05f, 1.1f); _buttonNormalRenderer->runAction(zoomAction); _buttonClickedRenderer->runAction(zoomAction1); _buttonDisableRenderer->runAction(zoomAction2); @@ -390,9 +390,9 @@ void UIButton::setFlipX(bool flipX) { return; } - dynamic_cast(_buttonNormalRenderer)->setFlippedX(flipX); - dynamic_cast(_buttonClickedRenderer)->setFlippedX(flipX); - dynamic_cast(_buttonDisableRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonNormalRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonClickedRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonDisableRenderer)->setFlippedX(flipX); } void UIButton::setFlipY(bool flipY) @@ -402,9 +402,9 @@ void UIButton::setFlipY(bool flipY) { return; } - dynamic_cast(_buttonNormalRenderer)->setFlippedY(flipY); - dynamic_cast(_buttonClickedRenderer)->setFlippedY(flipY); - dynamic_cast(_buttonDisableRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonNormalRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonClickedRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonDisableRenderer)->setFlippedY(flipY); } bool UIButton::isFlipX() @@ -413,7 +413,7 @@ bool UIButton::isFlipX() { return false; } - return dynamic_cast(_buttonNormalRenderer)->isFlippedX(); + return dynamic_cast(_buttonNormalRenderer)->isFlippedX(); } bool UIButton::isFlipY() @@ -422,16 +422,16 @@ bool UIButton::isFlipY() { return false; } - return dynamic_cast(_buttonNormalRenderer)->isFlippedY(); + return dynamic_cast(_buttonNormalRenderer)->isFlippedY(); } -void UIButton::setAnchorPoint(const Point &pt) +void UIButton::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _buttonNormalRenderer->setAnchorPoint(pt); _buttonClickedRenderer->setAnchorPoint(pt); _buttonDisableRenderer->setAnchorPoint(pt); - _titleRenderer->setPosition(Point(_size.width*(0.5f-_anchorPoint.x), _size.height*(0.5f-_anchorPoint.y))); + _titleRenderer->setPosition(cocos2d::Point(_size.width*(0.5f-_anchorPoint.x), _size.height*(0.5f-_anchorPoint.y))); } void UIButton::onSizeChanged() @@ -441,12 +441,12 @@ void UIButton::onSizeChanged() disabledTextureScaleChangedWithSize(); } -const Size& UIButton::getContentSize() const +const cocos2d::Size& UIButton::getContentSize() const { return _normalTextureSize; } -Node* UIButton::getVirtualRenderer() +cocos2d::Node* UIButton::getVirtualRenderer() { if (_bright) { @@ -480,11 +480,11 @@ void UIButton::normalTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonNormalRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonNormalRenderer)->setPreferredSize(_size); } else { - Size textureSize = _normalTextureSize; + cocos2d::Size textureSize = _normalTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonNormalRenderer->setScale(1.0f); @@ -511,11 +511,11 @@ void UIButton::pressedTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonClickedRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonClickedRenderer)->setPreferredSize(_size); } else { - Size textureSize = _pressedTextureSize; + cocos2d::Size textureSize = _pressedTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonClickedRenderer->setScale(1.0f); @@ -542,11 +542,11 @@ void UIButton::disabledTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonDisableRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonDisableRenderer)->setPreferredSize(_size); } else { - Size textureSize = _disabledTextureSize; + cocos2d::Size textureSize = _disabledTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonDisableRenderer->setScale(1.0f); @@ -575,13 +575,13 @@ const char* UIButton::getTitleText() const return _titleRenderer->getString(); } -void UIButton::setTitleColor(const Color3B& color) +void UIButton::setTitleColor(const cocos2d::Color3B& color) { _titleColor = color; _titleRenderer->setColor(color); } -const Color3B& UIButton::getTitleColor() const +const cocos2d::Color3B& UIButton::getTitleColor() const { return _titleRenderer->getColor(); } @@ -606,7 +606,7 @@ const char* UIButton::getTitleFontName() const return _titleRenderer->getFontName(); } -void UIButton::setColor(const Color3B &color) +void UIButton::setColor(const cocos2d::Color3B &color) { UIWidget::setColor(color); setTitleColor(_titleColor); @@ -617,4 +617,30 @@ const char* UIButton::getDescription() const return "Button"; } +UIWidget* UIButton::createCloneInstance() +{ + return UIButton::create(); +} + +void UIButton::copySpecialProperties(UIWidget *widget) +{ + UIButton* button = dynamic_cast(widget); + if (button) + { + _prevIgnoreSize = button->_prevIgnoreSize; + setScale9Enabled(button->_scale9Enabled); + loadTextureNormal(button->_normalFileName.c_str(), button->_normalTexType); + loadTexturePressed(button->_clickedFileName.c_str(), button->_pressedTexType); + loadTextureDisabled(button->_disabledFileName.c_str(), button->_disabledTexType); + setCapInsetsNormalRenderer(button->_capInsetsNormal); + setCapInsetsPressedRenderer(button->_capInsetsPressed); + setCapInsetsDisabledRenderer(button->_capInsetsDisabled); + setTitleText(button->getTitleText()); + setTitleFontName(button->getTitleFontName()); + setTitleFontSize(button->getTitleFontSize()); + setTitleColor(button->getTitleColor()); + setPressedActionEnabled(button->_pressedActionEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index 94d40ec65f..bc6958c3e4 100644 --- a/cocos/gui/UIButton.h +++ b/cocos/gui/UIButton.h @@ -27,8 +27,12 @@ #include "gui/UIWidget.h" -namespace gui { +namespace gui{ +/** +* @js NA +* @lua NA +*/ class UIButton : public UIWidget { public: @@ -162,6 +166,11 @@ public: */ virtual void setColor(const cocos2d::Color3B &color); + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; + void setTitleText(const char* text); const char* getTitleText() const; void setTitleColor(const cocos2d::Color3B& color); @@ -170,11 +179,7 @@ public: float getTitleFontSize() const; void setTitleFontName(const char* fontName); const char* getTitleFontName() const; - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; + protected: virtual bool init(); virtual void initRenderer(); @@ -186,6 +191,8 @@ protected: void normalTextureScaleChangedWithSize(); void pressedTextureScaleChangedWithSize(); void disabledTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Node* _buttonNormalRenderer; cocos2d::Node* _buttonClickedRenderer; diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index f685d73b11..a826fa40ef 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -24,10 +24,9 @@ #include "gui/UICheckBox.h" - using namespace cocos2d; - namespace gui { + UICheckBox::UICheckBox(): _backGroundBoxRenderer(NULL), _backGroundSelectedBoxRenderer(NULL), @@ -41,7 +40,12 @@ _backGroundTexType(UI_TEX_TYPE_LOCAL), _backGroundSelectedTexType(UI_TEX_TYPE_LOCAL), _frontCrossTexType(UI_TEX_TYPE_LOCAL), _backGroundDisabledTexType(UI_TEX_TYPE_LOCAL), -_frontCrossDisabledTexType(UI_TEX_TYPE_LOCAL) +_frontCrossDisabledTexType(UI_TEX_TYPE_LOCAL), +_backGroundFileName(""), +_backGroundSelectedFileName(""), +_frontCrossFileName(""), +_backGroundDisabledFileName(""), +_frontCrossDisabledFileName("") { } @@ -75,11 +79,11 @@ bool UICheckBox::init() void UICheckBox::initRenderer() { UIWidget::initRenderer(); - _backGroundBoxRenderer = Sprite::create(); - _backGroundSelectedBoxRenderer = Sprite::create(); - _frontCrossRenderer = Sprite::create(); - _backGroundBoxDisabledRenderer = Sprite::create(); - _frontCrossDisabledRenderer = Sprite::create(); + _backGroundBoxRenderer = cocos2d::Sprite::create(); + _backGroundSelectedBoxRenderer = cocos2d::Sprite::create(); + _frontCrossRenderer = cocos2d::Sprite::create(); + _backGroundBoxDisabledRenderer = cocos2d::Sprite::create(); + _frontCrossDisabledRenderer = cocos2d::Sprite::create(); _renderer->addChild(_backGroundBoxRenderer); _renderer->addChild(_backGroundSelectedBoxRenderer); _renderer->addChild(_frontCrossRenderer); @@ -102,6 +106,7 @@ void UICheckBox::loadTextureBackGround(const char *backGround,TextureResType tex { return; } + _backGroundFileName = backGround; _backGroundTexType = texType; switch (_backGroundTexType) { @@ -125,6 +130,7 @@ void UICheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,Te { return; } + _backGroundSelectedFileName = backGroundSelected; _backGroundSelectedTexType = texType; switch (_backGroundSelectedTexType) { @@ -148,6 +154,7 @@ void UICheckBox::loadTextureFrontCross(const char *cross,TextureResType texType) { return; } + _frontCrossFileName = cross; _frontCrossTexType = texType; switch (_frontCrossTexType) { @@ -171,6 +178,7 @@ void UICheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,Te { return; } + _backGroundDisabledFileName = backGroundDisabled; _backGroundDisabledTexType = texType; switch (_backGroundDisabledTexType) { @@ -194,6 +202,7 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te { return; } + _frontCrossDisabledFileName = frontCrossDisabled; _frontCrossDisabledTexType = texType; switch (_frontCrossDisabledTexType) { @@ -211,7 +220,7 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te frontCrossDisabledTextureScaleChangedWithSize(); } -void UICheckBox::onTouchEnded(const Point &touchPoint) +void UICheckBox::onTouchEnded(const cocos2d::Point &touchPoint) { if (_focus) { @@ -289,7 +298,7 @@ void UICheckBox::unSelectedEvent() } } -void UICheckBox::addEventListener(Object *target, SEL_SelectedStateEvent selector) +void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { _selectedStateEventListener = target; _selectedStateEventSelector = selector; @@ -323,7 +332,7 @@ bool UICheckBox::isFlipY() return _backGroundBoxRenderer->isFlippedY(); } -void UICheckBox::setAnchorPoint(const Point &pt) +void UICheckBox::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _backGroundBoxRenderer->setAnchorPoint(pt); @@ -342,12 +351,12 @@ void UICheckBox::onSizeChanged() frontCrossDisabledTextureScaleChangedWithSize(); } -const Size& UICheckBox::getContentSize() const +const cocos2d::Size& UICheckBox::getContentSize() const { return _backGroundBoxRenderer->getContentSize(); } -Node* UICheckBox::getVirtualRenderer() +cocos2d::Node* UICheckBox::getVirtualRenderer() { return _backGroundBoxRenderer; } @@ -361,7 +370,7 @@ void UICheckBox::backGroundTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundBoxRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxRenderer->setScale(1.0f); @@ -382,7 +391,7 @@ void UICheckBox::backGroundSelectedTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundSelectedBoxRenderer->setScale(1.0f); @@ -403,7 +412,7 @@ void UICheckBox::frontCrossTextureScaleChangedWithSize() } else { - Size textureSize = _frontCrossRenderer->getContentSize(); + cocos2d::Size textureSize = _frontCrossRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossRenderer->setScale(1.0f); @@ -424,7 +433,7 @@ void UICheckBox::backGroundDisabledTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxDisabledRenderer->setScale(1.0f); @@ -445,7 +454,7 @@ void UICheckBox::frontCrossDisabledTextureScaleChangedWithSize() } else { - Size textureSize = _frontCrossDisabledRenderer->getContentSize(); + cocos2d::Size textureSize = _frontCrossDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossDisabledRenderer->setScale(1.0f); @@ -463,4 +472,23 @@ const char* UICheckBox::getDescription() const return "CheckBox"; } +UIWidget* UICheckBox::createCloneInstance() +{ + return UICheckBox::create(); +} + +void UICheckBox::copySpecialProperties(UIWidget *widget) +{ + UICheckBox* checkBox = dynamic_cast(widget); + if (checkBox) + { + loadTextureBackGround(checkBox->_backGroundFileName.c_str(), checkBox->_backGroundTexType); + loadTextureBackGroundSelected(checkBox->_backGroundSelectedFileName.c_str(), checkBox->_backGroundSelectedTexType); + loadTextureFrontCross(checkBox->_frontCrossFileName.c_str(), checkBox->_frontCrossTexType); + loadTextureBackGroundDisabled(checkBox->_backGroundDisabledFileName.c_str(), checkBox->_backGroundDisabledTexType); + loadTextureFrontCrossDisabled(checkBox->_frontCrossDisabledFileName.c_str(), checkBox->_frontCrossDisabledTexType); + setSelectedState(checkBox->_isSelected); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UICheckBox.h b/cocos/gui/UICheckBox.h index 46183f04db..5e9c836617 100644 --- a/cocos/gui/UICheckBox.h +++ b/cocos/gui/UICheckBox.h @@ -35,9 +35,13 @@ typedef enum CHECKBOX_STATE_EVENT_UNSELECTED }CheckBoxEventType; -typedef void (cocos2d::CCObject::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); +typedef void (cocos2d::Object::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); #define checkboxselectedeventselector(_SELECTOR) (SEL_SelectedStateEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ class UICheckBox : public UIWidget { public: @@ -156,11 +160,12 @@ public: //override "getVirtualRenderer" method of widget. virtual cocos2d::Node* getVirtualRenderer(); - + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual bool init(); virtual void initRenderer(); @@ -175,6 +180,8 @@ protected: void frontCrossTextureScaleChangedWithSize(); void backGroundDisabledTextureScaleChangedWithSize(); void frontCrossDisabledTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Sprite* _backGroundBoxRenderer; cocos2d::Sprite* _backGroundSelectedBoxRenderer; @@ -191,6 +198,12 @@ protected: TextureResType _frontCrossTexType; TextureResType _backGroundDisabledTexType; TextureResType _frontCrossDisabledTexType; + + std::string _backGroundFileName; + std::string _backGroundSelectedFileName; + std::string _frontCrossFileName; + std::string _backGroundDisabledFileName; + std::string _frontCrossDisabledFileName; }; } diff --git a/cocos/gui/UIDragPanel.cpp b/cocos/gui/UIDragPanel.cpp deleted file mode 100644 index 7c717c0636..0000000000 --- a/cocos/gui/UIDragPanel.cpp +++ /dev/null @@ -1,1269 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "gui/UIDragPanel.h" -#include "gui/UILayer.h" - - using namespace cocos2d; - -namespace gui { - -UIDragPanel::UIDragPanel() -: _innerContainer(NULL) -, _touchPressed(false) -, _touchMoved(false) -, _touchReleased(false) -, _touchCanceld(false) -, _touchStartNodeSpace(Point::ZERO) -, _touchStartWorldSpace(Point::ZERO) -, _touchEndWorldSpace(Point::ZERO) -, _slidTime(0.0f) -, _moveType(DRAGPANEL_MOVE_TYPE_AUTOMOVE) -, _autoMoveDuration(0.5f) -, _autoMoveEaseRate(2.0f) -, _eventLister(NULL) -, _eventSelector(NULL) -, _berthDirection(DRAGPANEL_BERTH_DIR_NONE) -, _bounceEnable(false) -, _bounceDirection(DRAGPANEL_BOUNCE_DIR_NONE) -, _bounceDuration(0.5f) -, _bounceEaseRate(2.0f) -, _runningAction(false) -, _actionType(0) -, _actionWidget(NULL) -, _duration(0.0f) -, _elapsed(0.0f) -, _firstTick(false) -, _positionDelta(Point::ZERO) -, _startPosition(Point::ZERO) -, _previousPosition(Point::ZERO) -, _endPosition(Point::ZERO) -{ - -} - -UIDragPanel::~UIDragPanel() -{ - -} - -UIDragPanel* UIDragPanel::create() -{ - UIDragPanel* widget = new UIDragPanel(); - if (widget && widget->init()) - { - widget->autorelease(); - return widget; - } - CC_SAFE_DELETE(widget); - return NULL; -} - -bool UIDragPanel::init() -{ - if (Layout::init()) - { - setUpdateEnabled(true); - setTouchEnabled(true); - setClippingEnabled(true); - return true; - } - return false; -} - -void UIDragPanel::initRenderer() -{ - Layout::initRenderer(); - - _innerContainer = Layout::create(); - Layout::addChild(_innerContainer); - -} - -void UIDragPanel::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); - - Layout::removeChild(_innerContainer); - - _children->release(); -} - -bool UIDragPanel::onTouchBegan(const Point &touchPoint) -{ - bool pass = Layout::onTouchBegan(touchPoint); - handlePressLogic(touchPoint); - return pass; -} - -void UIDragPanel::onTouchMoved(const Point &touchPoint) -{ - Layout::onTouchMoved(touchPoint); - handleMoveLogic(touchPoint); -} - -void UIDragPanel::onTouchEnded(const Point &touchPoint) -{ - Layout::onTouchEnded(touchPoint); - handleReleaseLogic(touchPoint); -} - -void UIDragPanel::onTouchCancelled(const Point &touchPoint) -{ - Layout::onTouchCancelled(touchPoint); -} - -void UIDragPanel::onTouchLongClicked(const Point &touchPoint) -{ - -} - -void UIDragPanel::update(float dt) -{ - // widget action - if (_runningAction) - { - if (actionIsDone()) - { - actionDone(); - actionStop(); - } - else - { - actionStep(dt); - } - } - - recordSlidTime(dt); -} - -bool UIDragPanel::addChild(UIWidget *widget) -{ - _innerContainer->addChild(widget); - return true; -} - -bool UIDragPanel::removeChild(UIWidget *child) -{ - bool value = false; - if (_innerContainer->removeChild(child)) - { - value = true; - } - - return value; -} - -void UIDragPanel::removeAllChildren() -{ - _innerContainer->removeAllChildren(); -} - -Array* UIDragPanel::getChildren() -{ - return _innerContainer->getChildren(); -} - -void UIDragPanel::onSizeChanged() -{ - Layout::onSizeChanged(); - Size innerSize = _innerContainer->getSize(); - float orginInnerSizeWidth = innerSize.width; - float orginInnerSizeHeight = innerSize.height; - float innerSizeWidth = MAX(orginInnerSizeWidth, _size.width); - float innerSizeHeight = MAX(orginInnerSizeHeight, _size.height); - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); -} - -const Size& UIDragPanel::getInnerContainerSize() const -{ - return _innerContainer->getContentSize(); -} - -void UIDragPanel::setInnerContainerSize(const cocos2d::Size &size) -{ - float innerSizeWidth = _size.width; - float innerSizeHeight = _size.height; - if (size.width < _size.width) - { - CCLOG("Inner width <= scrollview width, it will be force sized!"); - } - else - { - innerSizeWidth = size.width; - } - if (size.height < _size.height) - { - CCLOG("Inner height <= scrollview height, it will be force sized!"); - } - else - { - innerSizeHeight = size.height; - } - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); -} - -const Point& UIDragPanel::getInnerContainerPosition() const -{ - return _innerContainer->getPosition(); -} - -void UIDragPanel::setInnerContainerPosition(const Point &point, bool animated) -{ - Point delta = point - _innerContainer->getPosition(); - -// Point delta = ccpSub(point, _innerContainer->getPosition()); - setInnerContainerOffset(delta, animated); -} - -void UIDragPanel::setInnerContainerOffset(const Point &offset, bool animated) -{ - if (animated) - { - Point delta = offset; - - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - actionStartWithWidget(_innerContainer); - moveByWithDuration(_autoMoveDuration, delta); - } - else - { - setInnerContainerOffset(offset); - } -} - -void UIDragPanel::setInnerContainerOffset(const Point &offset) -{ - Point delta = offset; - - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - moveWithDelta(delta); - if (checkBerth()) - { - berthEvent(); - } -} - - -void UIDragPanel::handlePressLogic(const Point &touchPoint) -{ - // check inner rect < drag panel rect - if (checkContainInnerRect()) - { - _touchPressed = false; - return; - } - - _touchPressed = true; - _touchMoved = false; - _touchReleased = false; - _touchCanceld = false; - - if (_runningAction) - { - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - stopAutoMove(); - actionStop(); - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - _touchPressed = false; - break; - - default: - break; - } - } - - Point nsp = _renderer->convertToNodeSpace(touchPoint); - _touchStartNodeSpace = nsp; - - _touchStartWorldSpace = touchPoint; -} - -void UIDragPanel::handleMoveLogic(const Point &touchPoint) -{ - if (!_touchPressed) - { - return; - } - - // check touch out of drag panel boundary - if (_touchCanceld) - { - return; - } - - _touchMoved = true; - - Point nsp = _renderer->convertToNodeSpace(touchPoint); - Point delta = nsp - _touchStartNodeSpace; -// Point delta = ccpSub(nsp, _touchStartNodeSpace); - _touchStartNodeSpace = nsp; - - // reset berth dir to none - if (!_bounceEnable) - { - _berthDirection = DRAGPANEL_BERTH_DIR_NONE; - } - - // check will berth (bounce disable) - if (!_bounceEnable) - { - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - } - // move - moveWithDelta(delta); - // check bounce or berth - if (_bounceEnable) - { - // bounce - if (!hitTest(touchPoint)) - { - _touchMoved = false; - - if (checkNeedBounce()) - { - _touchCanceld = true; - startBounce(); - } - } - } - else - { - // berth - if (checkBerth()) - { - berthEvent(); - } - } -} - -void UIDragPanel::handleReleaseLogic(const Point &touchPoint) -{ - if (!_touchPressed) - { - return; - } - - _touchPressed = false; - _touchMoved = false; - _touchReleased = true; - _touchCanceld = false; - - // check touch out of drag panel boundary - if (_touchCanceld) - { - return; - } - - if (hitTest(touchPoint)) - { - _touchEndWorldSpace = touchPoint; - startAutoMove(); - } -} - -void UIDragPanel::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) -{ - interceptTouchEvent(handleState, sender, touchPoint); -} - -void UIDragPanel::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) -{ - switch (handleState) - { - case 0: - handlePressLogic(touchPoint); - break; - - case 1: - { -// float offset = ccpDistance(sender->getTouchStartPos(), touchPoint); - float offset = sender->getTouchStartPos().getDistance(touchPoint); - if (offset > 5.0) - { - sender->setFocused(false); - handleMoveLogic(touchPoint); - } - } - break; - - case 2: - handleReleaseLogic(touchPoint); - break; - - case 3: - break; - } -} - -void UIDragPanel::recordSlidTime(float dt) -{ - if (_touchPressed) - { - _slidTime += dt; - } -} - -// check if dragpanel rect contain inner rect -bool UIDragPanel::checkContainInnerRect() -{ - float width = _size.width; - float height = _size.height; - float innerWidth = _innerContainer->getSize().width; - float innerHeight = _innerContainer->getSize().height; - - if (innerWidth <= width && innerHeight <= height) - { - return true; - } - - return false; -} - -// move -void UIDragPanel::moveWithDelta(const Point &delta) -{ - Point newPos = _innerContainer->getPosition() + delta; -// Point newPos = ccpAdd(_innerContainer->getPosition(), delta); - _innerContainer->setPosition(newPos); -} - -// auto move -void UIDragPanel::autoMove() -{ - if (_bounceEnable) - { - if (checkNeedBounce()) - { - stopAutoMove(); - startBounce(); - } - } -} - -void UIDragPanel::autoMoveOver() -{ - stopAutoMove(); - - if (checkBerth()) - { - berthEvent(); - _berthDirection = DRAGPANEL_BERTH_DIR_NONE; - } -} - -void UIDragPanel::startAutoMove() -{ - _moveType = DRAGPANEL_MOVE_TYPE_AUTOMOVE; - - actionStop(); - - Point delta = _touchEndWorldSpace - _touchStartWorldSpace; -// Point delta = ccpSub(m_touchEndWorldSpace, _touchStartWorldSpace); - delta.x /= _slidTime * 60; - delta.y /= _slidTime * 60; - _slidTime = 0.0; - - // bounceEnable is disable - if (!_bounceEnable) - { - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - } - actionStartWithWidget(_innerContainer); - moveByWithDuration(_autoMoveDuration, delta); -} - -void UIDragPanel::stopAutoMove() -{ - _moveType = DRAGPANEL_MOVE_TYPE_NONE; -} - -void UIDragPanel::setAutoMoveDuration(float duration) -{ - _autoMoveDuration = duration; -} - -void UIDragPanel::setAutoMoveEaseRate(float rate) -{ - _autoMoveEaseRate = rate; -} - -// berth - -// check if move to boundary - -bool UIDragPanel::checkToBoundaryWithDeltaPosition(const Point& delta) -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - bool toLeftBottom = false; - bool toLeftTop = false; - bool toRightBottom = false; - bool toRightTop = false; - bool toLeft = false; - bool toRight = false; - bool toTop = false; - bool toBottom = false; - - if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom - { - toLeftBottom = true; - } - else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top - { - toLeftTop = true; - } - else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom - { - toRightBottom = true; - } - else if (innerRight + delta.x < right && innerTop + delta.y < top) // right top - { - toRightTop = true; - } - else if (innerLeft + delta.x > left) // left - { - toLeft = true; - } - else if (innerRight + delta.x < right) // right - { - toRight = true; - } - else if (innerTop + delta.y < top) // top - { - toTop = true; - } - else if (innerBottom + delta.y > bottom) // bottom - { - toBottom = true; - } - - if (toLeft || toTop || toRight || toBottom - || toLeftBottom || toLeftTop || toRightBottom || toRightTop) - { - return true; - } - - return false; -} - -Point UIDragPanel::calculateToBoundaryDeltaPosition(const Point& paramDelta) -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - Point delta = paramDelta; - - if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom - { - delta.x = left - innerLeft; - delta.y = bottom - innerBottom; - } - else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top - { - delta.x = left - innerLeft; - delta.y = top - innerTop; - } - else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom - { - delta.x = right - innerRight; - delta.y = bottom - innerBottom; - } - else if (innerRight + delta.x < right && innerTop + delta.y < top) // right bottom - { - delta.x = right - innerRight; - delta.y = top - innerTop; - } - else if (innerLeft + delta.x > left) // left - { - delta.x = left - innerLeft; - } - else if (innerRight + delta.x < right) // right - { - delta.x = right - innerRight; - } - else if (innerTop + delta.y < top) // top - { - delta.y = top - innerTop; - } - else if (innerBottom + delta.y > bottom) // bottom - { - delta.y = bottom - innerBottom; - } - - return delta; -} - -bool UIDragPanel::isBerth() -{ - return _berthDirection != DRAGPANEL_BERTH_DIR_NONE; -} - -// check berth -bool UIDragPanel::checkBerth() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - if (innerLeft == left && innerBottom == bottom) // left bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_LEFTBOTTOM; - } - else if (innerLeft == left && innerTop == top) // left top - { - _berthDirection = DRAGPANEL_BERTH_DIR_LFETTOP; - } - else if (innerRight == right && innerBottom == bottom) // right bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHTBOTTOM; - } - else if (innerRight == right && innerTop == top) // right top - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHTTOP; - } - else if (innerLeft == left) // left - { - _berthDirection = DRAGPANEL_BERTH_DIR_LEFT; - } - else if (innerRight == right) // right - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHT; - } - else if (innerTop == top) // top - { - _berthDirection = DRAGPANEL_BERTH_DIR_TOP; - } - else if (innerBottom == bottom) // bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_BOTTOM; - } - - if (_berthDirection != DRAGPANEL_BERTH_DIR_NONE) - { - return true; - } - - return false; -} - -void UIDragPanel::berthEvent() -{ - switch (_berthDirection) - { - case DRAGPANEL_BERTH_DIR_LEFTBOTTOM: - berthToLeftBottomEvent(); - break; - - case DRAGPANEL_BERTH_DIR_LFETTOP: - berthToLeftTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHTBOTTOM: - berthToRightBottomEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHTTOP: - berthToRightTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_LEFT: - berthToLeftEvent(); - break; - - case DRAGPANEL_BERTH_DIR_TOP: - berthToTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHT: - berthToRightEvent(); - break; - - case DRAGPANEL_BERTH_DIR_BOTTOM: - berthToBottomEvent(); - break; - - default: - break; - } -} - -void UIDragPanel::berthToLeftBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LEFTBOTTOM); - } -} - -void UIDragPanel::berthToLeftTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LFETTOP); - } -} - -void UIDragPanel::berthToRightBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM); - } -} - -void UIDragPanel::berthToRightTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHTTOP); - } -} - -void UIDragPanel::berthToLeftEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LEFT); - } -} - -void UIDragPanel::berthToTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_TOP); - } -} - -void UIDragPanel::berthToRightEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHT); - } -} - -void UIDragPanel::berthToBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_BOTTOM); - } -} - -void UIDragPanel::addEventListener(Object *target, SEL_DragPanelEvent selector) -{ - _eventLister = target; - _eventSelector = selector; -} - -// bounce -bool UIDragPanel::isBounceEnable() -{ - return _bounceEnable; -} - -void UIDragPanel::setBounceEnable(bool bounce) -{ - _bounceEnable = bounce; -} - -bool UIDragPanel::checkNeedBounce() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - bool need = ((innerLeft > left && innerBottom > bottom) - || (innerLeft > left && innerTop < top) - || (innerRight < right && innerBottom > bottom) - || (innerRight < right && innerTop < top) - || (innerLeft > left) - || (innerTop < top) - || (innerRight < right) - || (innerBottom > bottom)); - return need; -} - -void UIDragPanel::startBounce() -{ - if (_moveType == DRAGPANEL_MOVE_TYPE_BOUNCE) - { - return; - } - - actionStop(); - _moveType = DRAGPANEL_MOVE_TYPE_BOUNCE; - bounceToCorner(); -} - -void UIDragPanel::stopBounce() -{ - _moveType = DRAGPANEL_MOVE_TYPE_NONE; -} - -void UIDragPanel::bounceToCorner() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float width = _size.width; - float height = _size.height; - float left = 0; - float top = height; - float right = width; - float bottom = 0; - - float from_x = 0; - float from_y = 0; - float to_x = 0; - float to_y = 0; - Point delta = Point::ZERO; - - if (innerLeft > left && innerBottom > bottom) // left bottom - { - from_x = innerLeft; - from_y = innerBottom; - to_x = left; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM; - } - else if (innerLeft > left && innerTop < top) // left top - { - from_x = innerLeft; - from_y = innerTop; - to_x = left; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTTOP; - } - else if (innerRight < right && innerBottom > bottom) // right bottom - { - from_x = innerRight; - from_y = innerBottom; - to_x = right; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM; - } - else if (innerRight < right && innerTop < top) // right top - { - from_x = innerRight; - from_y = innerTop; - to_x = right; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTTOP; - } - else if (innerLeft > left) // left - { - from_x = innerLeft; - from_y = innerBottom; - to_x = left; - to_y = from_y; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFT; - } - else if (innerTop < top) // top - { - from_x = innerLeft; - from_y = innerTop; - to_x = from_x; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_TOP; - } - else if (innerRight < right) // right - { - from_x = innerRight; - from_y = innerBottom; - to_x = right; - to_y = from_y; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHT; - } - else if (innerBottom > bottom) // bottom - { - from_x = innerLeft; - from_y = innerBottom; - to_x = from_x; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_BOTTOM; - } - delta = Point(to_x, to_y) - Point(from_x, from_y); -// delta = ccpSub(ccp(to_x, to_y), ccp(from_x, from_y)); - - actionStartWithWidget(_innerContainer); - moveByWithDuration(_bounceDuration, delta); -} - -void UIDragPanel::bounceOver() -{ - stopBounce(); - - switch (_bounceDirection) - { - case DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM: - bounceToLeftBottomEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_LEFTTOP: - bounceToLeftTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM: - bounceToRightBottomEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHTTOP: - bounceToRightTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_LEFT: - bounceToLeftEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_TOP: - bounceToTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHT: - bounceToRightEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_BOTTOM: - bounceToBottomEvent(); - break; - - default: - break; - } - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_NONE; -} - -void UIDragPanel::bounceToLeftBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM); - } -} - -void UIDragPanel::bounceToLeftTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFTTOP); - } -} - -void UIDragPanel::bounceToRightBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM); - } -} - -void UIDragPanel::bounceToRightTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHTTOP); - } -} - -void UIDragPanel::bounceToLeftEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFT); - } -} - -void UIDragPanel::bounceToTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_TOP); - } -} - -void UIDragPanel::bounceToRightEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHT); - } -} - -void UIDragPanel::bounceToBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_BOTTOM); - } -} - -// widget action -void UIDragPanel::actionWithDuration(float duration) -{ - _duration = duration; - - if (_duration == 0) - { - _duration = FLT_EPSILON; - } - - _elapsed = 0; - _firstTick = true; -} - -bool UIDragPanel::actionIsDone() -{ - bool value = (_elapsed >= _duration); - return value; -} - -void UIDragPanel::actionStartWithWidget(UIWidget *widget) -{ - _runningAction = true; - _actionWidget = widget; -} - -void UIDragPanel::actionStep(float dt) -{ - if (_firstTick) - { - _firstTick = false; - _elapsed = 0; - } - else - { - _elapsed += dt; - } - - actionUpdate(MAX (0, - MIN(1, _elapsed / - MAX(_duration, FLT_EPSILON) - ) - ) - ); -} - -void UIDragPanel::actionUpdate(float dt) -{ - switch (_actionType) - { - case 1: // move by - moveByUpdate(dt); - break; - - case 2: // move to - moveToUpdate(dt); - break; - - default: - break; - } -} - -void UIDragPanel::actionStop() -{ - _runningAction = false; -} - -void UIDragPanel::actionDone() -{ - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - autoMoveOver(); - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - bounceOver(); - break; - - default: - break; - } -} - -// move by -void UIDragPanel::moveByWithDuration(float duration, const Point& deltaPosition) -{ - actionWithDuration(duration); - _positionDelta = deltaPosition; - moveByInit(); - _actionType = 1; -} - -void UIDragPanel::moveByInit() -{ - _previousPosition = _startPosition = _actionWidget->getPosition(); -} - -void UIDragPanel::moveByUpdate(float t) -{ - float easeRate = 0.0f; - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - easeRate = _autoMoveEaseRate; - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - easeRate = _bounceEaseRate; - break; - - default: - break; - } - t = powf(t, 1 / easeRate); - - Point currentPos = _actionWidget->getPosition(); - Point diff = currentPos - _previousPosition; - _startPosition = _startPosition + diff; -// Point diff = ccpSub(currentPos, _previousPosition); -// _startPosition = ccpAdd( _startPosition, diff); - -// Point newPos = ccpAdd( _startPosition, ccpMult(_positionDelta, t) ); - Point newPos = _startPosition + (_positionDelta * t); - - _actionWidget->setPosition(newPos); - _previousPosition = newPos; - - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - autoMove(); - break; - - default: - break; - } -} - -// move to -void UIDragPanel::moveToWithDuration(float duration, const Point& position) -{ - actionWithDuration(duration); - _endPosition = position; - moveToInit(); - _actionType = 2; -} - -void UIDragPanel::moveToInit() -{ - moveByInit(); - _positionDelta = _endPosition - _actionWidget->getPosition(); -// _positionDelta = ccpSub( _endPosition, _actionWidget->getPosition() ); -} - -void UIDragPanel::moveToUpdate(float t) -{ - moveByUpdate(t); -} - -Layout* UIDragPanel::getInnerContainer() -{ - return _innerContainer; -} - -void UIDragPanel::setLayoutType(LayoutType type) -{ - _innerContainer->setLayoutType(type); -} - -LayoutType UIDragPanel::getLayoutType() const -{ - return _innerContainer->getLayoutType(); -} - -void UIDragPanel::doLayout() -{ - _innerContainer->doLayout(); -} - -const char* UIDragPanel::getDescription() const -{ - return "DragPanel"; -} - -} \ No newline at end of file diff --git a/cocos/gui/UIDragPanel.h b/cocos/gui/UIDragPanel.h deleted file mode 100644 index d6b4f0b62c..0000000000 --- a/cocos/gui/UIDragPanel.h +++ /dev/null @@ -1,367 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __UIDRAGPANEL_H__ -#define __UIDRAGPANEL_H__ - -#include "gui/Layout.h" -#include "gui/UIScrollInterface.h" - -namespace gui { - -/** - * drag panel move type - */ -enum DRAGPANEL_MOVE_TYPE -{ - DRAGPANEL_MOVE_TYPE_NONE, - DRAGPANEL_MOVE_TYPE_AUTOMOVE, - DRAGPANEL_MOVE_TYPE_BOUNCE, -}; - -/** - * dragpanel berth direction - */ -enum DRAGPANEL_BERTH_DIR -{ - DRAGPANEL_BERTH_DIR_NONE, - DRAGPANEL_BERTH_DIR_LEFTBOTTOM, - DRAGPANEL_BERTH_DIR_LFETTOP, - DRAGPANEL_BERTH_DIR_RIGHTBOTTOM, - DRAGPANEL_BERTH_DIR_RIGHTTOP, - DRAGPANEL_BERTH_DIR_LEFT, - DRAGPANEL_BERTH_DIR_TOP, - DRAGPANEL_BERTH_DIR_RIGHT, - DRAGPANEL_BERTH_DIR_BOTTOM, -}; - -/** - * dragpanel bounce direction - */ -enum DRAGPANEL_BOUNCE_DIR -{ - DRAGPANEL_BOUNCE_DIR_NONE, - DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM, - DRAGPANEL_BOUNCE_DIR_LEFTTOP, - DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM, - DRAGPANEL_BOUNCE_DIR_RIGHTTOP, - DRAGPANEL_BOUNCE_DIR_LEFT, - DRAGPANEL_BOUNCE_DIR_TOP, - DRAGPANEL_BOUNCE_DIR_RIGHT, - DRAGPANEL_BOUNCE_DIR_BOTTOM, -}; - -typedef enum -{ - DRAGPANEL_EVENT_BERTH_LEFTBOTTOM, - DRAGPANEL_EVENT_BERTH_LFETTOP, - DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM, - DRAGPANEL_EVENT_BERTH_RIGHTTOP, - DRAGPANEL_EVENT_BERTH_LEFT, - DRAGPANEL_EVENT_BERTH_TOP, - DRAGPANEL_EVENT_BERTH_RIGHT, - DRAGPANEL_EVENT_BERTH_BOTTOM, - DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM, - DRAGPANEL_EVENT_BOUNCE_LEFTTOP, - DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM, - DRAGPANEL_EVENT_BOUNCE_RIGHTTOP, - DRAGPANEL_EVENT_BOUNCE_LEFT, - DRAGPANEL_EVENT_BOUNCE_TOP, - DRAGPANEL_EVENT_BOUNCE_RIGHT, - DRAGPANEL_EVENT_BOUNCE_BOTTOM, -}DragPanelEventType; - -/** - * dragpanel event - */ -typedef void (cocos2d::Object::*SEL_DragPanelEvent)(cocos2d::Object*, DragPanelEventType); -#define dragpaneleventselector(_SELECTOR)(SEL_DragPanelEvent)(&_SELECTOR) - -class UIDragPanel : public Layout, public UIScrollInterface -{ -public: - UIDragPanel(); - virtual ~UIDragPanel(); - - static UIDragPanel* create(); - - virtual bool onTouchBegan(const cocos2d::Point &touchPoint); - virtual void onTouchMoved(const cocos2d::Point &touchPoint); - virtual void onTouchEnded(const cocos2d::Point &touchPoint); - virtual void onTouchCancelled(const cocos2d::Point &touchPoint); - virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); - - virtual void update(float dt); - - /** - * add widget child override - */ - virtual bool addChild(UIWidget* widget); - /** - * remove widget child override - */ - virtual bool removeChild(UIWidget* child); - /** - * remove all widget children override - */ - virtual void removeAllChildren(); - /** - * get widget children of inner container - */ - virtual cocos2d::Array* getChildren(); - /* gui mark */ - /** - * get and set inner container size - */ - const cocos2d::Size& getInnerContainerSize() const; - void setInnerContainerSize(const cocos2d::Size &size); - /** - * get and set inner container position - */ - const cocos2d::Point& getInnerContainerPosition() const; - void setInnerContainerPosition(const cocos2d::Point& point, bool animated); - /** - * set inner container offset - */ - void setInnerContainerOffset(const cocos2d::Point& offset, bool animated); - /**/ - - // auto move - /** - * set auto move duration - */ - void setAutoMoveDuration(float duration); - /** - * set auto move ease rate - */ - void setAutoMoveEaseRate(float rate); - - // berth - /** - * get berth or not - */ - bool isBerth(); - - /** - * event - */ - void addEventListener(cocos2d::Object* target, SEL_DragPanelEvent selector); - - /** - * get and set bounce enable - */ - bool isBounceEnable(); - void setBounceEnable(bool bounce); - /** - * set bounce duration - */ - void setBounceDuratoin(float duration); - /** - * set bounce ease rate - */ - void setBounceEaseRate(float rate); - - /** - * Gets inner container of dragpanel. - * - * Inner container is the container of dragpanel's children. - * - * @return inner container. - */ - Layout* getInnerContainer(); - - /** - * Sets LayoutType. - * - * @see LayoutType - * - * @param LayoutType - */ - virtual void setLayoutType(LayoutType type); - - /** - * Gets LayoutType. - * - * @see LayoutType - * - * @return LayoutType - */ - virtual LayoutType getLayoutType() const; - - virtual void doLayout(); - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; - -protected: - virtual bool init(); - virtual void initRenderer(); - virtual void releaseResoures(); - - virtual void handlePressLogic(const cocos2d::Point &touchPoint); - virtual void handleMoveLogic(const cocos2d::Point &touchPoint); - virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint); - /* gui mark */ -// virtual bool isInScrollDegreeRange(UIWidget* widget); - /**/ - virtual void checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint); -// void updateWidthAndHeight(); - void recordSlidTime(float dt); - - /* gui mark */ - void setInnerContainerOffset(const cocos2d::Point& offset); - /**/ - - // check if dragpanel rect contain inner rect - bool checkContainInnerRect(); - - // move - void moveWithDelta(const cocos2d::Point& delta); - - // auto move - void autoMove(); - void autoMoveOver(); - void startAutoMove(); - void stopAutoMove(); - - // berth - // check if move to boundary with update - bool checkToBoundaryWithDeltaPosition(const cocos2d::Point& delta); - - // calculate to boundary delta - cocos2d::Point calculateToBoundaryDeltaPosition(const cocos2d::Point& paramDelta); - - // check berth - bool checkBerth(); - - // berth event - void berthEvent(); - void berthToLeftEvent(); - void berthToRightEvent(); - void berthToTopEvent(); - void berthToBottomEvent(); - void berthToLeftBottomEvent(); - void berthToLeftTopEvent(); - void berthToRightBottomEvent(); - void berthToRightTopEvent(); - - // bounce - bool checkNeedBounce(); - void startBounce(); - void stopBounce(); - void bounceToCorner(); - void bounceOver(); - // bounce event - void bounceToLeftBottomEvent(); - void bounceToRightBottomEvent(); - void bounceToLeftTopEvent(); - void bounceToRightTopEvent(); - void bounceToLeftEvent(); - void bounceToTopEvent(); - void bounceToRightEvent(); - void bounceToBottomEvent(); - - void actionWithDuration(float duration); - bool actionIsDone(); - void actionStartWithWidget(UIWidget* widget); - void actionStep(float dt); - void actionUpdate(float dt); - void actionStop(); - void actionDone(); - void moveByWithDuration(float duration, const cocos2d::Point& deltaPosition); - void moveByInit(); - void moveByUpdate(float t); - void moveToWithDuration(float duration, const cocos2d::Point& position); - void moveToInit(); - void moveToUpdate(float t); - virtual void onSizeChanged(); - /*compatible*/ - /** - * These methods will be removed - */ - virtual void setClippingEnable(bool is){setClippingEnabled(is);}; - /************/ - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; -protected: - Layout* _innerContainer; - - /* - DRAGPANEL_DIR m_eDirection; - DRAGPANEL_MOVE_DIR m_eMoveDirection; - */ - - bool _touchPressed; - bool _touchMoved; - bool _touchReleased; - bool _touchCanceld; // check touch out of drag panel boundary - - cocos2d::Point _touchStartNodeSpace; - cocos2d::Point _touchStartWorldSpace; - cocos2d::Point _touchEndWorldSpace; - - float _slidTime; - - // move type - DRAGPANEL_MOVE_TYPE _moveType; - - // auto move - float _autoMoveDuration; - float _autoMoveEaseRate; - - // event - cocos2d::Object* _eventLister; - SEL_DragPanelEvent _eventSelector; - - // berth - DRAGPANEL_BERTH_DIR _berthDirection; - - // bounce - bool _bounceEnable; - DRAGPANEL_BOUNCE_DIR _bounceDirection; - float _bounceDuration; - float _bounceEaseRate; - - - float _runningAction; - int _actionType; - - UIWidget* _actionWidget; - - float _duration; - float _elapsed; - bool _firstTick; - - cocos2d::Point _positionDelta; - cocos2d::Point _startPosition; - cocos2d::Point _previousPosition; - - cocos2d::Point _endPosition; -}; - -} - -#endif /* defined(__TestCpp__UIDragPanel__) */ diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index 409d0f4461..d896a6372c 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -22,111 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/UIHelper.h" -#include "cocos2d.h" -#include "cocostudio/DictionaryHelper.h" -#include "cocostudio/CCSGUIReader.h" - - -using namespace cocos2d; -using namespace cocostudio; +#include "CocosGUI.h" namespace gui { - -static UIHelper* helperInstance = NULL; - -UIHelper* UIHelper::instance() -{ - if (!helperInstance) - { - helperInstance = new UIHelper(); - } - return helperInstance; -} - -void UIHelper::purgeUIHelper() -{ - CC_SAFE_DELETE(helperInstance); -} - -UIHelper::UIHelper(): -_textureFiles(NULL), -_fileDesignHeight(0.0f), -_fileDesignWidth(0.0f) -{ - Size winSize = Director::getInstance()->getWinSize(); - _fileDesignWidth = winSize.width; - _fileDesignHeight = winSize.height; - init(); -} - -UIHelper::~UIHelper() -{ - cocostudio::CCSGUIReader::purgeCCSGUIReader(); -} - -void UIHelper::init() -{ - _textureFiles = CCArray::create(); - _textureFiles->retain(); -} - -UIWidget* UIHelper::createWidgetFromJsonFile(const char *fileName) -{ - return CCSGUIReader::shareReader()->widgetFromJsonFile(fileName); -} - -void UIHelper::addSpriteFrame(const char *fileName) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - if (strcmp(file->_string.c_str(), fileName) == 0) - { - return; - } - } - _textureFiles->addObject(CCString::create(fileName)); - SpriteFrameCache::getInstance()->addSpriteFramesWithFile(fileName); -} - -void UIHelper::removeSpriteFrame(const char *fileName) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - if (strcmp(file->_string.c_str(), fileName) == 0) - { - SpriteFrameCache::getInstance()->removeSpriteFrameByName(fileName); - _textureFiles->removeObject(file); - return; - } - } -} - -void UIHelper::removeAllSpriteFrame() -{ - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - SpriteFrameCache::getInstance()->removeSpriteFrameByName(file->_string.c_str()); - } - _textureFiles->removeAllObjects(); -} UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -138,7 +36,7 @@ UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { return root; } - ccArray* arrayRootChildren = root->getChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;igetChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;igetChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;iarr[i]); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) { return child; @@ -196,26 +94,6 @@ UIWidget* UIHelper::seekWidgetByRelativeName(UIWidget *root, const char *name) return NULL; } -void UIHelper::setFileDesignWidth(float width) -{ - _fileDesignWidth = width; -} - -float UIHelper::getFileDesignWidth() -{ - return _fileDesignWidth; -} - -void UIHelper::setFileDesignHeight(float height) -{ - _fileDesignHeight = height; -} - -float UIHelper::getFileDesignHeight() -{ - return _fileDesignHeight; -} - /*temp action*/ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) { @@ -227,7 +105,7 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) { return root; } - ccArray* arrayRootChildren = root->getChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;i(_imageRenderer) #define DYNAMIC_CAST_SCALE9SPRITE dynamic_cast(_imageRenderer) @@ -41,7 +39,7 @@ _touchRelease(false), _doubleClickEnabled(false), _scale9Enabled(false), _prevIgnoreSize(true), -_capInsets(Rect::ZERO), +_capInsets(cocos2d::Rect::ZERO), _imageRenderer(NULL), _textureFile(""), _imageTexType(UI_TEX_TYPE_LOCAL), @@ -70,7 +68,7 @@ UIImageView* UIImageView::create() void UIImageView::initRenderer() { UIWidget::initRenderer(); - _imageRenderer = Sprite::create(); + _imageRenderer = cocos2d::Sprite::create(); _renderer->addChild(_imageRenderer); } @@ -90,6 +88,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) DYNAMIC_CAST_SCALE9SPRITE->initWithFile(fileName); DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(_capInsets); } else { @@ -104,6 +103,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) DYNAMIC_CAST_SCALE9SPRITE->initWithSpriteFrameName(fileName); DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(_capInsets); } else { @@ -120,7 +120,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) imageTextureScaleChangedWithSize(); } -void UIImageView::setTextureRect(const Rect &rect) +void UIImageView::setTextureRect(const cocos2d::Rect &rect) { if (_scale9Enabled) { @@ -131,7 +131,7 @@ void UIImageView::setTextureRect(const Rect &rect) } } -bool UIImageView::onTouchBegan(const Point &touchPoint) +bool UIImageView::onTouchBegan(const cocos2d::Point &touchPoint) { setFocused(true); _touchStartPos.x = touchPoint.x; @@ -149,7 +149,7 @@ bool UIImageView::onTouchBegan(const Point &touchPoint) return _touchPassedEnabled; } -void UIImageView::onTouchEnded(const Point &touchPoint) +void UIImageView::onTouchEnded(const cocos2d::Point &touchPoint) { if (_doubleClickEnabled) { @@ -278,11 +278,11 @@ void UIImageView::setScale9Enabled(bool able) _imageRenderer = NULL; if (_scale9Enabled) { - _imageRenderer = extension::Scale9Sprite::create(); + _imageRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _imageRenderer = CCSprite::create(); + _imageRenderer = cocos2d::Sprite::create(); } loadTexture(_textureFile.c_str(),_imageTexType); _renderer->addChild(_imageRenderer); @@ -308,7 +308,7 @@ void UIImageView::ignoreContentAdaptWithSize(bool ignore) } } -void UIImageView::setCapInsets(const Rect &capInsets) +void UIImageView::setCapInsets(const cocos2d::Rect &capInsets) { _capInsets = capInsets; if (!_scale9Enabled) @@ -318,7 +318,7 @@ void UIImageView::setCapInsets(const Rect &capInsets) DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(capInsets); } -void UIImageView::setAnchorPoint(const Point &pt) +void UIImageView::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _imageRenderer->setAnchorPoint(pt); @@ -329,12 +329,12 @@ void UIImageView::onSizeChanged() imageTextureScaleChangedWithSize(); } -const Size& UIImageView::getContentSize() const +const cocos2d::Size& UIImageView::getContentSize() const { return _imageTextureSize; } -Node* UIImageView::getVirtualRenderer() +cocos2d::Node* UIImageView::getVirtualRenderer() { return _imageRenderer; } @@ -353,11 +353,11 @@ void UIImageView::imageTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_imageRenderer)->setPreferredSize(_size); + dynamic_cast(_imageRenderer)->setPreferredSize(_size); } else { - Size textureSize = _imageRenderer->getContentSize(); + cocos2d::Size textureSize = _imageRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _imageRenderer->setScale(1.0f); @@ -376,4 +376,21 @@ const char* UIImageView::getDescription() const return "ImageView"; } +UIWidget* UIImageView::createCloneInstance() +{ + return UIImageView::create(); +} + +void UIImageView::copySpecialProperties(UIWidget *widget) +{ + UIImageView* imageView = dynamic_cast(widget); + if (imageView) + { + _prevIgnoreSize = imageView->_prevIgnoreSize; + setScale9Enabled(imageView->_scale9Enabled); + loadTexture(imageView->_textureFile.c_str(), imageView->_imageTexType); + setCapInsets(imageView->_capInsets); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIImageView.h b/cocos/gui/UIImageView.h index 91bd2573ec..16103aa256 100644 --- a/cocos/gui/UIImageView.h +++ b/cocos/gui/UIImageView.h @@ -29,6 +29,10 @@ namespace gui { +/** +* @js NA +* @lua NA +*/ class UIImageView : public UIWidget { public: @@ -100,22 +104,22 @@ public: //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore); - + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; void setDoubleClickEnabled(bool able); void doubleClickEvent(); void checkDoubleClick(float dt); virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; protected: virtual void initRenderer(); virtual void onSizeChanged(); void imageTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: int _clickCount; float _clickTimeInterval; diff --git a/cocos/gui/UIInputManager.cpp b/cocos/gui/UIInputManager.cpp index 0fe2eb153e..bb36043855 100644 --- a/cocos/gui/UIInputManager.cpp +++ b/cocos/gui/UIInputManager.cpp @@ -37,11 +37,11 @@ _longClickRecordTime(0.0), _checkedDoubleClickWidget(NULL), _rootWidget(NULL) { - _manageredWidget = CCArray::create(); + _manageredWidget = Array::create(); _manageredWidget->retain(); - _checkedDoubleClickWidget = CCArray::create(); + _checkedDoubleClickWidget = Array::create(); _checkedDoubleClickWidget->retain(); - _selectedWidgets = CCArray::create(); + _selectedWidgets = Array::create(); _selectedWidgets->retain(); } diff --git a/cocos/gui/UIInputManager.h b/cocos/gui/UIInputManager.h index 9547b091a1..ed5a931f89 100644 --- a/cocos/gui/UIInputManager.h +++ b/cocos/gui/UIInputManager.h @@ -26,7 +26,7 @@ #define __UIINPUTMANAGER_H__ #include "cocos2d.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" namespace gui { @@ -41,7 +41,7 @@ public: /** * Default destructor */ - ~UIInputManager(); + virtual ~UIInputManager(); /** * Regist a widget to input manager. diff --git a/cocos/gui/UILabel.cpp b/cocos/gui/UILabel.cpp index 6ac5d68fdf..4c8779c9eb 100644 --- a/cocos/gui/UILabel.cpp +++ b/cocos/gui/UILabel.cpp @@ -24,10 +24,9 @@ #include "gui/UILabel.h" - using namespace cocos2d; - namespace gui { + UILabel::UILabel(): _touchScaleChangeEnabled(false), _normalScaleValue(1.0f), @@ -67,7 +66,7 @@ bool UILabel::init() void UILabel::initRenderer() { UIWidget::initRenderer(); - _labelRenderer = CCLabelTTF::create(); + _labelRenderer = cocos2d::LabelTTF::create(); _renderer->addChild(_labelRenderer); } @@ -95,29 +94,31 @@ int UILabel::getStringLength() void UILabel::setFontSize(int size) { + _fontSize = size; _labelRenderer->setFontSize(size); labelScaleChangedWithSize(); } void UILabel::setFontName(const char* name) { + _fontName = name; _labelRenderer->setFontName(name); labelScaleChangedWithSize(); } -void UILabel::setTextAreaSize(const Size &size) +void UILabel::setTextAreaSize(const cocos2d::Size &size) { _labelRenderer->setDimensions(size); labelScaleChangedWithSize(); } -void UILabel::setTextHorizontalAlignment(TextHAlignment alignment) +void UILabel::setTextHorizontalAlignment(cocos2d::TextHAlignment alignment) { _labelRenderer->setHorizontalAlignment(alignment); labelScaleChangedWithSize(); } -void UILabel::setTextVerticalAlignment(TextVAlignment alignment) +void UILabel::setTextVerticalAlignment(cocos2d::TextVAlignment alignment) { _labelRenderer->setVerticalAlignment(alignment); labelScaleChangedWithSize(); @@ -182,7 +183,7 @@ bool UILabel::isFlipY() return _labelRenderer->isFlippedY(); } -void UILabel::setAnchorPoint(const Point &pt) +void UILabel::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _labelRenderer->setAnchorPoint(pt); @@ -193,12 +194,12 @@ void UILabel::onSizeChanged() labelScaleChangedWithSize(); } -const Size& UILabel::getContentSize() const +const cocos2d::Size& UILabel::getContentSize() const { return _labelRenderer->getContentSize(); } -Node* UILabel::getVirtualRenderer() +cocos2d::Node* UILabel::getVirtualRenderer() { return _labelRenderer; } @@ -212,7 +213,7 @@ void UILabel::labelScaleChangedWithSize() } else { - Size textureSize = _labelRenderer->getContentSize(); + cocos2d::Size textureSize = _labelRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _labelRenderer->setScale(1.0f); @@ -223,6 +224,7 @@ void UILabel::labelScaleChangedWithSize() _labelRenderer->setScaleX(scaleX); _labelRenderer->setScaleY(scaleY); } + } const char* UILabel::getDescription() const @@ -230,4 +232,21 @@ const char* UILabel::getDescription() const return "Label"; } +UIWidget* UILabel::createCloneInstance() +{ + return UILabel::create(); +} + +void UILabel::copySpecialProperties(UIWidget *widget) +{ + UILabel* label = dynamic_cast(widget); + if (label) + { + setFontName(label->_fontName.c_str()); + setFontSize(label->_labelRenderer->getFontSize()); + setText(label->getStringValue()); + setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILabel.h b/cocos/gui/UILabel.h index 0d9150f17d..5c6a4a105b 100644 --- a/cocos/gui/UILabel.h +++ b/cocos/gui/UILabel.h @@ -27,8 +27,13 @@ #include "gui/UIWidget.h" + namespace gui { +/** +* @js NA +* @lua NA +*/ class UILabel : public UIWidget { public: @@ -124,11 +129,7 @@ public: void setTextAreaSize(const cocos2d::Size &size); void setTextHorizontalAlignment(cocos2d::TextHAlignment alignment); - void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); - - - void setTouchScaleChangeAble(bool able){setTouchScaleChangeEnabled(able);}; - bool getTouchScaleChangeAble(){return isTouchScaleChangeEnabled();}; + void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); protected: virtual bool init(); virtual void initRenderer(); @@ -138,6 +139,8 @@ protected: virtual void onSizeChanged(); void clickScale(float scale); void labelScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: bool _touchScaleChangeEnabled; float _normalScaleValue; diff --git a/cocos/gui/UILabelAtlas.cpp b/cocos/gui/UILabelAtlas.cpp index 72b816e4a6..8e8db6c422 100644 --- a/cocos/gui/UILabelAtlas.cpp +++ b/cocos/gui/UILabelAtlas.cpp @@ -24,10 +24,9 @@ #include "gui/UILabelAtlas.h" - using namespace cocos2d; - namespace gui { + UICCLabelAtlas::UICCLabelAtlas() { @@ -56,7 +55,7 @@ void UICCLabelAtlas::setProperty(const char *string, const char *charMapFile, un initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap); } -void UICCLabelAtlas::setProperty(const char *string, Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, texture, itemWidth, itemHeight, startCharMap); } @@ -68,20 +67,26 @@ void UICCLabelAtlas::draw() return; } - CCAtlasNode::draw(); + cocos2d::AtlasNode::draw(); } void UICCLabelAtlas::updateDisplayedOpacity(GLubyte opacity) { - CCAtlasNode::setOpacity(opacity); + cocos2d::AtlasNode::setOpacity(opacity); } UILabelAtlas::UILabelAtlas(): -_laberAtlasRenderer(NULL) +_laberAtlasRenderer(NULL), +_stringValue(""), +_charMapFileName(""), +_itemWidth(0), +_itemHeight(0), +_startCharMap("") { + } UILabelAtlas::~UILabelAtlas() @@ -108,8 +113,13 @@ void UILabelAtlas::initRenderer() _renderer->addChild(_laberAtlasRenderer); } -void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap,bool useSpriteFrame) +void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap) { + _stringValue = stringValue; + _charMapFileName = charMapFile; + _itemWidth = itemWidth; + _itemHeight = itemHeight; + _startCharMap = startCharMap; _laberAtlasRenderer->setProperty(stringValue, charMapFile, itemWidth, itemHeight, (int)(startCharMap[0])); updateAnchorPoint(); labelAtlasScaleChangedWithSize(); @@ -117,6 +127,7 @@ void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, void UILabelAtlas::setStringValue(const char *value) { + _stringValue = value; _laberAtlasRenderer->setString(value); labelAtlasScaleChangedWithSize(); } @@ -126,10 +137,10 @@ const char* UILabelAtlas::getStringValue() return _laberAtlasRenderer->getString(); } -void UILabelAtlas::setAnchorPoint(const Point &pt) +void UILabelAtlas::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); - _laberAtlasRenderer->setAnchorPoint(Point(pt.x, pt.y)); + _laberAtlasRenderer->setAnchorPoint(cocos2d::Point(pt.x, pt.y)); } void UILabelAtlas::onSizeChanged() @@ -137,12 +148,12 @@ void UILabelAtlas::onSizeChanged() labelAtlasScaleChangedWithSize(); } -const Size& UILabelAtlas::getContentSize() const +const cocos2d::Size& UILabelAtlas::getContentSize() const { return _laberAtlasRenderer->getContentSize(); } -Node* UILabelAtlas::getVirtualRenderer() +cocos2d::Node* UILabelAtlas::getVirtualRenderer() { return _laberAtlasRenderer; } @@ -156,7 +167,7 @@ void UILabelAtlas::labelAtlasScaleChangedWithSize() } else { - Size textureSize = _laberAtlasRenderer->getContentSize(); + cocos2d::Size textureSize = _laberAtlasRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _laberAtlasRenderer->setScale(1.0f); @@ -171,7 +182,21 @@ void UILabelAtlas::labelAtlasScaleChangedWithSize() const char* UILabelAtlas::getDescription() const { - return "LabelAtlase"; + return "LabelAtlas"; } +UIWidget* UILabelAtlas::createCloneInstance() +{ + return UILabelAtlas::create(); +} + +void UILabelAtlas::copySpecialProperties(UIWidget *widget) +{ + UILabelAtlas* labelAtlas = dynamic_cast(widget); + if (labelAtlas) + { + setProperty(labelAtlas->_stringValue.c_str(), labelAtlas->_charMapFileName.c_str(), labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap.c_str()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILabelAtlas.h b/cocos/gui/UILabelAtlas.h index b74ea87644..73b902633f 100644 --- a/cocos/gui/UILabelAtlas.h +++ b/cocos/gui/UILabelAtlas.h @@ -29,6 +29,10 @@ namespace gui { +/** + * @js NA + * @lua NA + */ class UICCLabelAtlas : public cocos2d::LabelAtlas { public: @@ -51,7 +55,10 @@ public: virtual void updateDisplayedOpacity(GLubyte opacity); virtual void draw(void); }; - +/** + * @js NA + * @lua NA + */ class UILabelAtlas : public UIWidget { public: @@ -71,7 +78,7 @@ public: static UILabelAtlas* create(); /** initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap,bool useSpriteFrame = false); + void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap); //set string value for labelatlas. void setStringValue(const char* value); @@ -92,12 +99,20 @@ public: * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual void initRenderer(); virtual void onSizeChanged(); void labelAtlasScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: UICCLabelAtlas* _laberAtlasRenderer; + std::string _stringValue; + std::string _charMapFileName; + int _itemWidth; + int _itemHeight; + std::string _startCharMap; }; } diff --git a/cocos/gui/UILabelBMFont.cpp b/cocos/gui/UILabelBMFont.cpp index b112c06bf4..d8560fd4a8 100644 --- a/cocos/gui/UILabelBMFont.cpp +++ b/cocos/gui/UILabelBMFont.cpp @@ -24,13 +24,13 @@ #include "gui/UILabelBMFont.h" - using namespace cocos2d; - namespace gui { UILabelBMFont::UILabelBMFont(): _labelBMFontRenderer(NULL), -_fntFileHasInit(false) +_fntFileHasInit(false), +_fntFileName(""), +_stringValue("") { } @@ -54,38 +54,45 @@ UILabelBMFont* UILabelBMFont::create() void UILabelBMFont::initRenderer() { UIWidget::initRenderer(); - _labelBMFontRenderer = CCLabelBMFont::create(); + _labelBMFontRenderer = cocos2d::LabelBMFont::create(); _renderer->addChild(_labelBMFontRenderer); } void UILabelBMFont::setFntFile(const char *fileName) { - if (!fileName || strcmp(fileName, "") == 0) + if (!fileName || std::strcmp(fileName, "") == 0) { return; } + _fntFileName = fileName; _labelBMFontRenderer->initWithString("", fileName); updateAnchorPoint(); labelBMFontScaleChangedWithSize(); _fntFileHasInit = true; + setText(_stringValue.c_str()); } void UILabelBMFont::setText(const char* value) { - if (!value || !_fntFileHasInit) + if (!value) { return; } - _labelBMFontRenderer->setString(value); + _stringValue = value; + if (!_fntFileHasInit) + { + return; + } + _labelBMFontRenderer->setString(value); labelBMFontScaleChangedWithSize(); } const char* UILabelBMFont::getStringValue() { - return _labelBMFontRenderer->getString(); + return _stringValue.c_str(); } -void UILabelBMFont::setAnchorPoint(const Point &pt) +void UILabelBMFont::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _labelBMFontRenderer->setAnchorPoint(pt); @@ -96,12 +103,12 @@ void UILabelBMFont::onSizeChanged() labelBMFontScaleChangedWithSize(); } -const Size& UILabelBMFont::getContentSize() const +const cocos2d::Size& UILabelBMFont::getContentSize() const { return _labelBMFontRenderer->getContentSize(); } -Node* UILabelBMFont::getVirtualRenderer() +cocos2d::Node* UILabelBMFont::getVirtualRenderer() { return _labelBMFontRenderer; } @@ -115,7 +122,7 @@ void UILabelBMFont::labelBMFontScaleChangedWithSize() } else { - Size textureSize = _labelBMFontRenderer->getContentSize(); + cocos2d::Size textureSize = _labelBMFontRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _labelBMFontRenderer->setScale(1.0f); @@ -133,5 +140,19 @@ const char* UILabelBMFont::getDescription() const return "LabelBMFont"; } +UIWidget* UILabelBMFont::createCloneInstance() +{ + return UILabelBMFont::create(); +} + +void UILabelBMFont::copySpecialProperties(UIWidget *widget) +{ + UILabelBMFont* labelBMFont = dynamic_cast(widget); + if (labelBMFont) + { + setFntFile(labelBMFont->_fntFileName.c_str()); + setText(labelBMFont->_stringValue.c_str()); + } +} } \ No newline at end of file diff --git a/cocos/gui/UILabelBMFont.h b/cocos/gui/UILabelBMFont.h index ddf4e31728..5c03c1ae75 100644 --- a/cocos/gui/UILabelBMFont.h +++ b/cocos/gui/UILabelBMFont.h @@ -29,6 +29,10 @@ namespace gui { +/** +* @js NA +* @lua NA +*/ class UILabelBMFont : public UIWidget { public: @@ -58,7 +62,6 @@ public: virtual void setAnchorPoint(const cocos2d::Point &pt); virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); - /** * Returns the "class name" of widget. */ @@ -67,9 +70,13 @@ protected: virtual void initRenderer(); virtual void onSizeChanged(); void labelBMFontScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::LabelBMFont* _labelBMFontRenderer; bool _fntFileHasInit; + std::string _fntFileName; + std::string _stringValue; }; } diff --git a/cocos/gui/UILayer.cpp b/cocos/gui/UILayer.cpp index bfdea4094f..a935f9efc5 100644 --- a/cocos/gui/UILayer.cpp +++ b/cocos/gui/UILayer.cpp @@ -119,7 +119,7 @@ UIWidget* UILayer::getWidgetByTag(int tag) { return NULL; } - return CCUIHELPER->seekWidgetByTag(_rootWidget, tag); + return UIHelper::seekWidgetByTag(_rootWidget, tag); } UIWidget* UILayer::getWidgetByName(const char* name) @@ -128,7 +128,7 @@ UIWidget* UILayer::getWidgetByName(const char* name) { return NULL; } - return CCUIHELPER->seekWidgetByName(_rootWidget, name); + return UIHelper::seekWidgetByName(_rootWidget, name); } UIRootWidget* UILayer::getRootWidget() diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp new file mode 100644 index 0000000000..70b66a0b56 --- /dev/null +++ b/cocos/gui/UILayout.cpp @@ -0,0 +1,1010 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "gui/UILayout.h" +#include "gui/UILayer.h" +#include "gui/UIHelper.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" + +namespace gui { + + +#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) + +UILayout::UILayout(): +_clippingEnabled(false), +_backGroundScale9Enabled(false), +_backGroundImage(NULL), +_backGroundImageFileName(""), +_backGroundImageCapInsets(cocos2d::Rect::ZERO), +_colorType(LAYOUT_COLOR_NONE), +_bgImageTexType(UI_TEX_TYPE_LOCAL), +_colorRender(NULL), +_gradientRender(NULL), +_cColor(cocos2d::Color3B::WHITE), +_gStartColor(cocos2d::Color3B::WHITE), +_gEndColor(cocos2d::Color3B::WHITE), +_alongVector(cocos2d::Point(0.0f, -1.0f)), +_cOpacity(255), +_backGroundImageTextureSize(cocos2d::Size::ZERO), +_layoutType(LAYOUT_ABSOLUTE) +{ + _widgetType = WidgetTypeContainer; +} + +UILayout::~UILayout() +{ +} + +UILayout* UILayout::create() +{ + UILayout* layout = new UILayout(); + if (layout && layout->init()) + { + layout->autorelease(); + return layout; + } + CC_SAFE_DELETE(layout); + return NULL; +} + +bool UILayout::init() +{ + _children = cocos2d::Array::create(); + _children->retain(); + _layoutParameterDictionary = cocos2d::Dictionary::create(); + CC_SAFE_RETAIN(_layoutParameterDictionary); + initRenderer(); + _renderer->retain(); + _renderer->setZOrder(_widgetZOrder); + cocos2d::RGBAProtocol* renderRGBA = dynamic_cast(_renderer); + if (renderRGBA) + { + renderRGBA->setCascadeColorEnabled(false); + renderRGBA->setCascadeOpacityEnabled(false); + } + ignoreContentAdaptWithSize(false); + setSize(cocos2d::Size::ZERO); + setBright(true); + setAnchorPoint(cocos2d::Point(0, 0)); + _scheduler = cocos2d::Director::getInstance()->getScheduler(); + CC_SAFE_RETAIN(_scheduler); + return true; +} + +void UILayout::initRenderer() +{ + _renderer = UIRectClippingNode::create(); +} + +bool UILayout::addChild(UIWidget *child) +{ + supplyTheLayoutParameterLackToChild(child); + return UIWidget::addChild(child); +} + +bool UILayout::isClippingEnabled() +{ + return _clippingEnabled; +} + +bool UILayout::hitTest(const cocos2d::Point &pt) +{ + cocos2d::Point nsp = _renderer->convertToNodeSpace(pt); + cocos2d::Rect bb = cocos2d::Rect(0.0f, 0.0f, _size.width, _size.height); + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + { + return true; + } + return false; +} + +void UILayout::setClippingEnabled(bool able) +{ + _clippingEnabled = able; + DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); +} + +void UILayout::onSizeChanged() +{ + DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); + doLayout(); + if (_backGroundImage) + { + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + } + if (_colorRender) + { + _colorRender->setContentSize(_size); + } + if (_gradientRender) + { + _gradientRender->setContentSize(_size); + } +} + +void UILayout::setBackGroundImageScale9Enabled(bool able) +{ + if (_backGroundScale9Enabled == able) + { + return; + } + _renderer->removeChild(_backGroundImage, true); + _backGroundImage = NULL; + _backGroundScale9Enabled = able; + if (_backGroundScale9Enabled) + { + _backGroundImage = cocos2d::extension::Scale9Sprite::create(); + _renderer->addChild(_backGroundImage); + } + else + { + _backGroundImage = cocos2d::Sprite::create(); + _renderer->addChild(_backGroundImage); + } + _backGroundImage->setZOrder(-1); + setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); + setBackGroundImageCapInsets(_backGroundImageCapInsets); +} + +void UILayout::setBackGroundImage(const char* fileName,TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + if (_backGroundImage == NULL) + { + addBackGroundImage(); + } + _backGroundImageFileName = fileName; + _bgImageTexType = texType; + if (_backGroundScale9Enabled) + { + switch (_bgImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(_backGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + else + { + switch (_bgImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(_backGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + } + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setColor(getColor()); + dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(_backGroundImage)->setColor(getColor()); + dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); + } + _backGroundImageTextureSize = _backGroundImage->getContentSize(); + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); +} + +void UILayout::setBackGroundImageCapInsets(const cocos2d::Rect &capInsets) +{ + _backGroundImageCapInsets = capInsets; + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setCapInsets(capInsets); + } +} + +void UILayout::supplyTheLayoutParameterLackToChild(UIWidget *child) +{ + if (!child) + { + return; + } + switch (_layoutType) + { + case LAYOUT_ABSOLUTE: + break; + case LAYOUT_LINEAR_HORIZONTAL: + case LAYOUT_LINEAR_VERTICAL: + { + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!layoutParameter) + { + child->setLayoutParameter(UILinearLayoutParameter::create()); + } + break; + } + case LAYOUT_RELATIVE: + { + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + if (!layoutParameter) + { + child->setLayoutParameter(UIRelativeLayoutParameter::create()); + } + break; + } + default: + break; + } +} + +void UILayout::addBackGroundImage() +{ + if (_backGroundScale9Enabled) + { + _backGroundImage = cocos2d::extension::Scale9Sprite::create(); + _backGroundImage->setZOrder(-1); + _renderer->addChild(_backGroundImage); + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + else + { + _backGroundImage = cocos2d::Sprite::create(); + _backGroundImage->setZOrder(-1); + _renderer->addChild(_backGroundImage); + } + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); +} + +void UILayout::removeBackGroundImage() +{ + if (!_backGroundImage) + { + return; + } + _renderer->removeChild(_backGroundImage, true); + _backGroundImage = NULL; + _backGroundImageFileName = ""; + _backGroundImageTextureSize = cocos2d::Size::ZERO; +} + +void UILayout::setBackGroundColorType(LayoutBackGroundColorType type) +{ + if (_colorType == type) + { + return; + } + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + if (_colorRender) + { + _renderer->removeChild(_colorRender, true); + _colorRender = NULL; + } + if (_gradientRender) + { + _renderer->removeChild(_gradientRender, true); + _gradientRender = NULL; + } + break; + case LAYOUT_COLOR_SOLID: + if (_colorRender) + { + _renderer->removeChild(_colorRender, true); + _colorRender = NULL; + } + break; + case LAYOUT_COLOR_GRADIENT: + if (_gradientRender) + { + _renderer->removeChild(_gradientRender, true); + _gradientRender = NULL; + } + break; + default: + break; + } + _colorType = type; + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + _colorRender = cocos2d::LayerColor::create(); + _colorRender->setContentSize(_size); + _colorRender->setOpacity(_cOpacity); + _colorRender->setColor(_cColor); + _renderer->addChild(_colorRender,-2); + break; + case LAYOUT_COLOR_GRADIENT: + _gradientRender = cocos2d::LayerGradient::create(); + _gradientRender->setContentSize(_size); + _gradientRender->setOpacity(_cOpacity); + _gradientRender->setStartColor(_gStartColor); + _gradientRender->setEndColor(_gEndColor); + _gradientRender->setVector(_alongVector); + _renderer->addChild(_gradientRender,-2); + break; + default: + break; + } +} + +void UILayout::setBackGroundColor(const cocos2d::Color3B &color) +{ + _cColor = color; + if (_colorRender) + { + _colorRender->setColor(color); + } +} + +void UILayout::setBackGroundColor(const cocos2d::Color3B &startColor, const cocos2d::Color3B &endColor) +{ + _gStartColor = startColor; + if (_gradientRender) + { + _gradientRender->setStartColor(startColor); + } + _gEndColor = endColor; + if (_gradientRender) + { + _gradientRender->setEndColor(endColor); + } +} + +void UILayout::setBackGroundColorOpacity(int opacity) +{ + _cOpacity = opacity; + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + _colorRender->setOpacity(opacity); + break; + case LAYOUT_COLOR_GRADIENT: + _gradientRender->setOpacity(opacity); + break; + default: + break; + } +} + +void UILayout::setBackGroundColorVector(const cocos2d::Point &vector) +{ + _alongVector = vector; + if (_gradientRender) + { + _gradientRender->setVector(vector); + } +} + +void UILayout::setColor(const cocos2d::Color3B &color) +{ + UIWidget::setColor(color); + if (_backGroundImage) + { + cocos2d::RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); + if (rgbap) + { + rgbap->setColor(color); + } + } +} + +void UILayout::setOpacity(int opacity) +{ + UIWidget::setOpacity(opacity); + if (_backGroundImage) + { + cocos2d::RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); + if (rgbap) + { + rgbap->setOpacity(opacity); + } + } +} + +const cocos2d::Size& UILayout::getBackGroundImageTextureSize() const +{ + return _backGroundImageTextureSize; +} + +const cocos2d::Size& UILayout::getContentSize() const +{ + return _renderer->getContentSize(); +} + +void UILayout::setLayoutType(LayoutType type) +{ + _layoutType = type; + + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + for (int i=0; i(layoutChildrenArray->arr[i]); + supplyTheLayoutParameterLackToChild(child); + } +} + +LayoutType UILayout::getLayoutType() const +{ + return _layoutType; +} + +void UILayout::doLayout() +{ + switch (_layoutType) + { + case LAYOUT_ABSOLUTE: + break; + case LAYOUT_LINEAR_VERTICAL: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + cocos2d::Size layoutSize = getSize(); + float topBoundary = layoutSize.height; + for (int i=0; i(layoutChildrenArray->arr[i]); + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + UILinearGravity childGravity = layoutParameter->getGravity(); + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + float finalPosX = ap.x * cs.width; + float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_LEFT: + break; + case LINEAR_GRAVITY_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + break; + case LINEAR_GRAVITY_CENTER_HORIZONTAL: + finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + topBoundary = child->getBottomInParent() - mg.bottom; + } + } + break; + } + case LAYOUT_LINEAR_HORIZONTAL: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + cocos2d::Size layoutSize = getSize(); + float leftBoundary = 0.0f; + for (int i=0; i(layoutChildrenArray->arr[i]); + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + UILinearGravity childGravity = layoutParameter->getGravity(); + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + float finalPosX = leftBoundary + (ap.x * cs.width); + float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_TOP: + break; + case LINEAR_GRAVITY_BOTTOM: + finalPosY = ap.y * cs.height; + break; + case LINEAR_GRAVITY_CENTER_VERTICAL: + finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + leftBoundary = child->getRightInParent() + mg.right; + } + } + break; + } + case LAYOUT_RELATIVE: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + int unlayoutChildCount = length; + cocos2d::Size layoutSize = getSize(); + + for (int i=0; i(layoutChildrenArray->arr[i]); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + layoutParameter->_put = false; + } + + while (unlayoutChildCount > 0) + { + for (int i=0; i(layoutChildrenArray->arr[i]); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + + if (layoutParameter) + { + if (layoutParameter->_put) + { + continue; + } + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + UIRelativeAlign align = layoutParameter->getAlign(); + const char* relativeName = layoutParameter->getRelativeToWidgetName(); + UIWidget* relativeWidget = NULL; + UIRelativeLayoutParameter* relativeWidgetLP = NULL; + float finalPosX = 0.0f; + float finalPosY = 0.0f; + if (relativeName && strcmp(relativeName, "")) + { + relativeWidget = UIHelper::seekWidgetByRelativeName(this, relativeName); + if (relativeWidget) + { + relativeWidgetLP = dynamic_cast(relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + } + } + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_CENTER_IN_PARENT: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX = ap.x * cs.width; + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = ap.y * cs.height; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_ABOVE_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationBottom = relativeWidget->getTopInParent(); + + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosX = locationLeft + ap.x * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationTop = relativeWidget->getBottomInParent(); + + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + default: + break; + } + UIMargin relativeWidgetMargin; + UIMargin mg = layoutParameter->getMargin(); + if (relativeWidget) + { + relativeWidgetMargin = relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)->getMargin(); + } + //handle margin + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX += mg.left; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX -= mg.right; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX += mg.left; + break; + case RELATIVE_CENTER_IN_PARENT: + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX -= mg.right; + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX += mg.left; + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX -= mg.right; + finalPosY += mg.bottom; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + case RELATIVE_LOCATION_ABOVE_CENTER: + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + finalPosY += mg.bottom; + finalPosY += relativeWidgetMargin.top; + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + case RELATIVE_LOCATION_LEFT_OF_CENTER: + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + finalPosX -= mg.right; + finalPosX -= relativeWidgetMargin.left; + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + finalPosX += mg.left; + finalPosX += relativeWidgetMargin.right; + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + case RELATIVE_LOCATION_BELOW_CENTER: + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + finalPosY -= mg.top; + finalPosY -= relativeWidgetMargin.bottom; + break; + default: + break; + } + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + layoutParameter->_put = true; + unlayoutChildCount--; + } + } + } + break; + } + default: + break; + } +} + +const char* UILayout::getDescription() const +{ + return "Layout"; +} + +UIWidget* UILayout::createCloneInstance() +{ + return UILayout::create(); +} + +void UILayout::copyClonedWidgetChildren(UIWidget* model) +{ + UIWidget::copyClonedWidgetChildren(model); + doLayout(); +} + +void UILayout::copySpecialProperties(UIWidget *widget) +{ + UILayout* layout = dynamic_cast(widget); + if (layout) + { + setBackGroundImageScale9Enabled(layout->_backGroundScale9Enabled); + setBackGroundImage(layout->_backGroundImageFileName.c_str(),layout->_bgImageTexType); + setBackGroundImageCapInsets(layout->_backGroundImageCapInsets); + setBackGroundColorType(layout->_colorType); + setBackGroundColor(layout->_cColor); + setBackGroundColor(layout->_gStartColor, layout->_gEndColor); + setBackGroundColorOpacity(layout->_cOpacity); + setBackGroundColorVector(layout->_alongVector); + setLayoutType(layout->_layoutType); + setClippingEnabled(layout->_clippingEnabled); + } +} + +UIRectClippingNode::UIRectClippingNode(): +_innerStencil(NULL), +_enabled(true), +_clippingSize(cocos2d::Size(50.0f, 50.0f)), +_clippingEnabled(false) +{ + +} + +UIRectClippingNode::~UIRectClippingNode() +{ + +} + +UIRectClippingNode* UIRectClippingNode::create() +{ + UIRectClippingNode *pRet = new UIRectClippingNode(); + if (pRet && pRet->init()) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + + return pRet; +} + +bool UIRectClippingNode::init() +{ + _innerStencil = cocos2d::DrawNode::create(); + rect[0] = cocos2d::Point(0, 0); + rect[1] = cocos2d::Point(_clippingSize.width, 0); + rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); + rect[3] = cocos2d::Point(0, _clippingSize.height); + + cocos2d::Color4F green = {0, 1, 0, 1}; + _innerStencil->drawPolygon(rect, 4, green, 0, green); + if (cocos2d::ClippingNode::init(_innerStencil)) + { + return true; + } + return false; +} + + +void UIRectClippingNode::setClippingSize(const cocos2d::Size &size) +{ + setContentSize(size); + _clippingSize = size; + rect[0] = cocos2d::Point(0, 0); + rect[1] = cocos2d::Point(_clippingSize.width, 0); + rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); + rect[3] = cocos2d::Point(0, _clippingSize.height); + cocos2d::Color4F green = {0, 1, 0, 1}; + _innerStencil->clear(); + _innerStencil->drawPolygon(rect, 4, green, 0, green); +} + +void UIRectClippingNode::setClippingEnabled(bool enabled) +{ + _clippingEnabled = enabled; +} + +void UIRectClippingNode::visit() +{ + if (!_enabled) + { + return; + } + if (_clippingEnabled) + { + cocos2d::ClippingNode::visit(); + } + else + { + cocos2d::Node::visit(); + } +} + +void UIRectClippingNode::setEnabled(bool enabled) +{ + _enabled = enabled; +} + +bool UIRectClippingNode::isEnabled() const +{ + return _enabled; +} + +} \ No newline at end of file diff --git a/cocos/gui/Layout.h b/cocos/gui/UILayout.h similarity index 89% rename from cocos/gui/Layout.h rename to cocos/gui/UILayout.h index b58b0fbd2b..918bd868af 100644 --- a/cocos/gui/Layout.h +++ b/cocos/gui/UILayout.h @@ -44,23 +44,28 @@ typedef enum LAYOUT_RELATIVE }LayoutType; -class Layout : public UIWidget + +/** + * @js NA + * @lua NA + */ +class UILayout : public UIWidget { public: /** * Default constructor */ - Layout(); + UILayout(); /** * Default destructor */ - virtual ~Layout(); + virtual ~UILayout(); /** * Allocates and initializes a layout. */ - static Layout* create(); + static UILayout* create(); //override "hitTest" method of widget. virtual bool hitTest(const cocos2d::Point &pt); @@ -168,6 +173,11 @@ public: */ virtual const cocos2d::Size& getContentSize() const; + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; + /** * Sets LayoutType. * @@ -187,11 +197,14 @@ public: virtual LayoutType getLayoutType() const; virtual void doLayout(); - + /** - * Returns the "class name" of widget. + * Adds a child to the container. + * + * @param child A child widget */ - virtual const char* getDescription() const; + virtual bool addChild(UIWidget* child); + protected: //override "init" method of widget. virtual bool init(); @@ -204,6 +217,11 @@ protected: //init background image renderer. void addBackGroundImage(); + + void supplyTheLayoutParameterLackToChild(UIWidget* child); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: bool _clippingEnabled; @@ -224,23 +242,26 @@ protected: cocos2d::Size _backGroundImageTextureSize; LayoutType _layoutType; }; - -class RectClippingNode : public cocos2d::ClippingNode +/** + * @js NA + * @lua NA + */ +class UIRectClippingNode : public cocos2d::ClippingNode { public: - virtual ~RectClippingNode(); + virtual ~UIRectClippingNode(); virtual bool init(); - static RectClippingNode* create(); + static UIRectClippingNode* create(); void setClippingSize(const cocos2d::Size& size); void setClippingEnabled(bool enabled); virtual void visit(); void setEnabled(bool enabled); bool isEnabled() const; protected: - cocos2d::DrawNode* m_pInnerStencil; + cocos2d::DrawNode* _innerStencil; bool _enabled; private: - RectClippingNode(); + UIRectClippingNode(); cocos2d::Point rect[4]; cocos2d::Size _clippingSize; bool _clippingEnabled; diff --git a/cocos/gui/UILayoutDefine.cpp b/cocos/gui/UILayoutDefine.cpp index d79444fc75..b6b785a47d 100644 --- a/cocos/gui/UILayoutDefine.cpp +++ b/cocos/gui/UILayoutDefine.cpp @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "gui/UILayoutDefine.h" +#include "UILayoutDefine.h" namespace gui { diff --git a/cocos/gui/UILayoutDefine.h b/cocos/gui/UILayoutDefine.h index 1d0bd716bf..0b772837ca 100644 --- a/cocos/gui/UILayoutDefine.h +++ b/cocos/gui/UILayoutDefine.h @@ -26,9 +26,13 @@ #define __UILAYOUTDEFINE_H__ #include "cocos2d.h" +#include "ExtensionMacros.h" namespace gui { - +/** +* @js NA +* @lua NA +*/ class UIMargin { public: @@ -46,6 +50,7 @@ public: bool equals(const UIMargin& target) const; }; +const UIMargin UIMarginZero = UIMargin(); typedef enum { @@ -61,22 +66,25 @@ typedef enum typedef enum { RELATIVE_ALIGN_NONE, - RELATIVE_ALIGN_PARENT_LEFT, - RELATIVE_ALIGN_PARENT_TOP, - RELATIVE_ALIGN_PARENT_RIGHT, - RELATIVE_ALIGN_PARENT_BOTTOM, + RELATIVE_ALIGN_PARENT_TOP_LEFT, + RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_TOP_RIGHT, + RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL, RELATIVE_CENTER_IN_PARENT, - RELATIVE_CENTER_HORIZONTAL, - RELATIVE_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_LEFT_BOTTOM, + RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM, + + RELATIVE_LOCATION_ABOVE_LEFTALIGN, + RELATIVE_LOCATION_ABOVE_CENTER, + RELATIVE_LOCATION_ABOVE_RIGHTALIGN, RELATIVE_LOCATION_LEFT_OF_TOPALIGN, RELATIVE_LOCATION_LEFT_OF_CENTER, RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN, RELATIVE_LOCATION_RIGHT_OF_TOPALIGN, RELATIVE_LOCATION_RIGHT_OF_CENTER, RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN, - RELATIVE_LOCATION_ABOVE_LEFTALIGN, - RELATIVE_LOCATION_ABOVE_CENTER, - RELATIVE_LOCATION_ABOVE_RIGHTALIGN, RELATIVE_LOCATION_BELOW_LEFTALIGN, RELATIVE_LOCATION_BELOW_CENTER, RELATIVE_LOCATION_BELOW_RIGHTALIGN diff --git a/cocos/gui/LayoutParameter.cpp b/cocos/gui/UILayoutParameter.cpp similarity index 65% rename from cocos/gui/LayoutParameter.cpp rename to cocos/gui/UILayoutParameter.cpp index 01caa33158..c468f69a24 100644 --- a/cocos/gui/LayoutParameter.cpp +++ b/cocos/gui/UILayoutParameter.cpp @@ -22,14 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/LayoutParameter.h" -#include "gui/Layout.h" +#include "gui/UILayoutParameter.h" +#include "gui/UILayout.h" namespace gui { -LayoutParameter* LayoutParameter::create() + +UILayoutParameter* UILayoutParameter::create() { - LayoutParameter* parameter = new LayoutParameter(); + UILayoutParameter* parameter = new UILayoutParameter(); if (parameter) { parameter->autorelease(); @@ -39,24 +40,24 @@ LayoutParameter* LayoutParameter::create() return NULL; } -void LayoutParameter::setMargin(const UIMargin &margin) +void UILayoutParameter::setMargin(const UIMargin &margin) { _margin = margin; } -const UIMargin& LayoutParameter::getMargin() const +const UIMargin& UILayoutParameter::getMargin() const { return _margin; } -LayoutParameterType LayoutParameter::getLayoutType() const +LayoutParameterType UILayoutParameter::getLayoutType() const { return _layoutParameterType; } -LinearLayoutParameter* LinearLayoutParameter::create() +UILinearLayoutParameter* UILinearLayoutParameter::create() { - LinearLayoutParameter* parameter = new LinearLayoutParameter(); + UILinearLayoutParameter* parameter = new UILinearLayoutParameter(); if (parameter) { parameter->autorelease(); @@ -66,19 +67,19 @@ LinearLayoutParameter* LinearLayoutParameter::create() return NULL; } -void LinearLayoutParameter::setGravity(UILinearGravity gravity) +void UILinearLayoutParameter::setGravity(UILinearGravity gravity) { _linearGravity = gravity; } -UILinearGravity LinearLayoutParameter::getGravity() const +UILinearGravity UILinearLayoutParameter::getGravity() const { return _linearGravity; } -RelativeLayoutParameter* RelativeLayoutParameter::create() +UIRelativeLayoutParameter* UIRelativeLayoutParameter::create() { - RelativeLayoutParameter* parameter = new RelativeLayoutParameter(); + UIRelativeLayoutParameter* parameter = new UIRelativeLayoutParameter(); if (parameter) { parameter->autorelease(); @@ -88,32 +89,32 @@ RelativeLayoutParameter* RelativeLayoutParameter::create() return NULL; } -void RelativeLayoutParameter::setAlign(UIRelativeAlign align) +void UIRelativeLayoutParameter::setAlign(UIRelativeAlign align) { _relativeAlign = align; } -UIRelativeAlign RelativeLayoutParameter::getAlign() const +UIRelativeAlign UIRelativeLayoutParameter::getAlign() const { return _relativeAlign; } -void RelativeLayoutParameter::setRelativeToWidgetName(const char *name) +void UIRelativeLayoutParameter::setRelativeToWidgetName(const char *name) { _relativeWidgetName = name; } -const char* RelativeLayoutParameter::getRelativeToWidgetName() const +const char* UIRelativeLayoutParameter::getRelativeToWidgetName() const { return _relativeWidgetName.c_str(); } -void RelativeLayoutParameter::setRelativeName(const char* name) +void UIRelativeLayoutParameter::setRelativeName(const char* name) { _relativeLayoutName = name; } -const char* RelativeLayoutParameter::getRelativeName() const +const char* UIRelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName.c_str(); } diff --git a/cocos/gui/LayoutParameter.h b/cocos/gui/UILayoutParameter.h similarity index 82% rename from cocos/gui/LayoutParameter.h rename to cocos/gui/UILayoutParameter.h index 3c457635d1..60a7e387ad 100644 --- a/cocos/gui/LayoutParameter.h +++ b/cocos/gui/UILayoutParameter.h @@ -35,25 +35,28 @@ typedef enum LAYOUT_PARAMETER_LINEAR, LAYOUT_PARAMETER_RELATIVE }LayoutParameterType; - -class LayoutParameter : public cocos2d::Object +/** +* @js NA +* @lua NA +*/ +class UILayoutParameter : public cocos2d::Object { public: /** * Default constructor */ - LayoutParameter() : _margin(UIMargin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; + UILayoutParameter() : _margin(UIMargin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; /** * Default destructor */ - virtual ~LayoutParameter(){}; + virtual ~UILayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static LayoutParameter* create(); + static UILayoutParameter* create(); /** * Sets Margin parameter for LayoutParameter. @@ -85,25 +88,28 @@ protected: UIMargin _margin; LayoutParameterType _layoutParameterType; }; - -class LinearLayoutParameter : public LayoutParameter +/** +* @js NA +* @lua NA +*/ +class UILinearLayoutParameter : public UILayoutParameter { public: /** * Default constructor */ - LinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; + UILinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; /** * Default destructor */ - virtual ~LinearLayoutParameter(){}; + virtual ~UILinearLayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static LinearLayoutParameter* create(); + static UILinearLayoutParameter* create(); /** * Sets UILinearGravity parameter for LayoutParameter. @@ -125,25 +131,31 @@ public: protected: UILinearGravity _linearGravity; }; +/** +* @js NA +* @lua NA +*/ -class RelativeLayoutParameter : public LayoutParameter +class UILayout; + +class UIRelativeLayoutParameter : public UILayoutParameter { public: /** * Default constructor */ - RelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; + UIRelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""),_put(false){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; /** * Default destructor */ - virtual ~RelativeLayoutParameter(){}; + virtual ~UIRelativeLayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static RelativeLayoutParameter* create(); + static UIRelativeLayoutParameter* create(); /** * Sets UIRelativeAlign parameter for LayoutParameter. @@ -194,6 +206,8 @@ protected: UIRelativeAlign _relativeAlign; std::string _relativeWidgetName; std::string _relativeLayoutName; + bool _put; + friend class UILayout; }; } diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 5ec6e71540..81baaad41d 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -23,55 +23,24 @@ ****************************************************************************/ #include "gui/UIListView.h" - - using namespace cocos2d; +#include "gui/UIHelper.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" namespace gui { -UIListView::UIListView() -: _direction(LISTVIEW_DIR_VERTICAL) -, _moveDirection(LISTVIEW_MOVE_DIR_NONE) -, _touchStartLocation(0.0f) -, _touchEndLocation(0.0f) -, _touchMoveStartLocation(0.0f) -, _topBoundary(0.0f) -, _bottomBoundary(0.0f) -, _leftBoundary(0.0f) -, _rightBoundary(0.0f) -, _autoScroll(false) -, _autoScrollOriginalSpeed(0.0f) -, _autoScrollAcceleration(600.0f) -, _bePressed(false) -, _slidTime(0.0f) -, _childFocusCancelOffset(5.0f) -, _eventListener(NULL) -, _eventSelector(NULL) -, _childPool(NULL) -, _updatePool(NULL) -, _dataLength(0) -, _begin(0) -, _end(0) -, _updateChild(NULL) -, _updateDataIndex(-1) -, _updateSuccess(false) -, _overTopArray(NULL) -, _overBottomArray(NULL) -, _overLeftArray(NULL) -, _overRightArray(NULL) -, _disBoundaryToChild_0(0.0f) -, _disBetweenChild(0.0f) -, _scrollDegreeRange(45.0f) +UIListView::UIListView(): +_model(NULL), +_items(NULL), +_gravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL), +_itemsMargin(0.0f) { + } UIListView::~UIListView() { - CC_SAFE_RELEASE_NULL(_childPool); - CC_SAFE_RELEASE_NULL(_updatePool); - CC_SAFE_RELEASE_NULL(_overTopArray); - CC_SAFE_RELEASE_NULL(_overBottomArray); - CC_SAFE_RELEASE_NULL(_overLeftArray); - CC_SAFE_RELEASE_NULL(_overRightArray); + _items->removeAllObjects(); + CC_SAFE_RELEASE(_items); } UIListView* UIListView::create() @@ -88,1373 +57,365 @@ UIListView* UIListView::create() bool UIListView::init() { - if (Layout::init()) + if (UIScrollView::init()) { - setUpdateEnabled(true); - setTouchEnabled(true); - setClippingEnabled(true); - - _childPool = CCArray::create(); - _updatePool = CCArray::create(); - CC_SAFE_RETAIN(_childPool); - CC_SAFE_RETAIN(_updatePool); - _overTopArray = cocos2d::CCArray::create(); - _overBottomArray = cocos2d::CCArray::create(); - _overLeftArray = cocos2d::CCArray::create(); - _overRightArray = cocos2d::CCArray::create(); - CC_SAFE_RETAIN(_overTopArray); - CC_SAFE_RETAIN(_overBottomArray); - CC_SAFE_RETAIN(_overLeftArray); - CC_SAFE_RETAIN(_overRightArray); - + _items = cocos2d::Array::create(); + CC_SAFE_RETAIN(_items); + setLayoutType(LAYOUT_LINEAR_VERTICAL); return true; } return false; } +void UIListView::setItemModel(UIWidget *model) +{ + if (!model) + { + return; + } + CC_SAFE_RELEASE_NULL(_model); + _model = model; + CC_SAFE_RETAIN(_model); +} + +void UIListView::updateInnerContainerSize() +{ + if (!_model) + { + return; + } + switch (_direction) { + case SCROLLVIEW_DIR_VERTICAL: + { + int childrenCount = _items->count(); + float totalHeight = _model->getSize().height * childrenCount + (childrenCount - 1) * _itemsMargin; + float finalWidth = _size.width; + float finalHeight = totalHeight; + setInnerContainerSize(cocos2d::Size(finalWidth, finalHeight)); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + int childrenCount = _items->count(); + float totalWidth = _model->getSize().width * childrenCount + (childrenCount - 1) * _itemsMargin; + float finalWidth = totalWidth; + float finalHeight = _size.height; + setInnerContainerSize(cocos2d::Size(finalWidth, finalHeight)); + break; + } + default: + break; + } +} + +void UIListView::remedyLayoutParameter(UIWidget *item) +{ + if (!item) + { + return; + } + switch (_direction) { + case SCROLLVIEW_DIR_VERTICAL: + { + UILinearLayoutParameter* llp = (UILinearLayoutParameter*)(item->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!llp) + { + UILinearLayoutParameter* defaultLp = UILinearLayoutParameter::create(); + switch (_gravity) { + case LISTVIEW_GRAVITY_LEFT: + defaultLp->setGravity(LINEAR_GRAVITY_LEFT); + break; + case LISTVIEW_GRAVITY_RIGHT: + defaultLp->setGravity(LINEAR_GRAVITY_RIGHT); + break; + case LISTVIEW_GRAVITY_CENTER_HORIZONTAL: + defaultLp->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); + break; + default: + break; + } + if (getIndex(item) == 0) + { + defaultLp->setMargin(UIMarginZero); + } + else + { + defaultLp->setMargin(UIMargin(0.0f, _itemsMargin, 0.0f, 0.0f)); + } + item->setLayoutParameter(defaultLp); + } + else + { + if (getIndex(item) == 0) + { + llp->setMargin(UIMarginZero); + } + else + { + llp->setMargin(UIMargin(0.0f, _itemsMargin, 0.0f, 0.0f)); + } + switch (_gravity) { + case LISTVIEW_GRAVITY_LEFT: + llp->setGravity(LINEAR_GRAVITY_LEFT); + break; + case LISTVIEW_GRAVITY_RIGHT: + llp->setGravity(LINEAR_GRAVITY_RIGHT); + break; + case LISTVIEW_GRAVITY_CENTER_HORIZONTAL: + llp->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); + break; + default: + break; + } + } + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + UILinearLayoutParameter* llp = (UILinearLayoutParameter*)(item->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!llp) + { + UILinearLayoutParameter* defaultLp = UILinearLayoutParameter::create(); + switch (_gravity) { + case LISTVIEW_GRAVITY_TOP: + defaultLp->setGravity(LINEAR_GRAVITY_TOP); + break; + case LISTVIEW_GRAVITY_BOTTOM: + defaultLp->setGravity(LINEAR_GRAVITY_BOTTOM); + break; + case LISTVIEW_GRAVITY_CENTER_VERTICAL: + defaultLp->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); + break; + default: + break; + } + if (getIndex(item) == 0) + { + defaultLp->setMargin(UIMarginZero); + } + else + { + defaultLp->setMargin(UIMargin(_itemsMargin, 0.0f, 0.0f, 0.0f)); + } + item->setLayoutParameter(defaultLp); + } + else + { + if (getIndex(item) == 0) + { + llp->setMargin(UIMarginZero); + } + else + { + llp->setMargin(UIMargin(_itemsMargin, 0.0f, 0.0f, 0.0f)); + } + switch (_gravity) { + case LISTVIEW_GRAVITY_TOP: + llp->setGravity(LINEAR_GRAVITY_TOP); + break; + case LISTVIEW_GRAVITY_BOTTOM: + llp->setGravity(LINEAR_GRAVITY_BOTTOM); + break; + case LISTVIEW_GRAVITY_CENTER_VERTICAL: + llp->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); + break; + default: + break; + } + } + break; + } + default: + break; + } + +} + +void UIListView::pushBackDefaultItem() +{ + if (!_model) + { + return; + } + UIWidget* newItem = _model->clone(); + _items->addObject(newItem); + remedyLayoutParameter(newItem); + addChild(newItem); +} + +void UIListView::insertDefaultItem(int index) +{ + if (!_items) + { + return; + } + if (!_model) + { + return; + } + UIWidget* newItem = _model->clone(); + _items->insertObject(newItem, index); + remedyLayoutParameter(newItem); + addChild(newItem); +} + +void UIListView::pushBackCustomItem(UIWidget* item) +{ + _items->addObject(item); + remedyLayoutParameter(item); + addChild(item); +} + +void UIListView::insertCustomItem(UIWidget* item, int index) +{ + _items->insertObject(item, index); + remedyLayoutParameter(item); + addChild(item); +} + +void UIListView::removeItem(int index) +{ + if (!_items) + { + return; + } + UIWidget* item = getItem(index); + if (!item) + { + return; + + } + _items->removeObject(item); + removeChild(item); +} + +void UIListView::removeLastItem() +{ + removeItem(_items->count() -1); +} + +UIWidget* UIListView::getItem(unsigned int index) +{ + if ((int)index < 0 || index >= _items->count()) + { + return NULL; + } + return (UIWidget*)(_items->data->arr[index]); +} + +cocos2d::Array* UIListView::getItems() +{ + return _items; +} + +unsigned int UIListView::getIndex(UIWidget *item) const +{ + if (!_items) + { + return -1; + } + if (!item) + { + return -1; + } + return _items->getIndexOfObject(item); +} + +void UIListView::setGravity(ListViewGravity gravity) +{ + if (_gravity == gravity) + { + return; + } + _gravity = gravity; + refreshView(); +} + +void UIListView::setItemsMargin(float margin) +{ + if (_itemsMargin == margin) + { + return; + } + _itemsMargin = margin; + refreshView(); +} + +void UIListView::setDirection(SCROLLVIEW_DIR dir) +{ + switch (dir) + { + case SCROLLVIEW_DIR_VERTICAL: + setLayoutType(LAYOUT_LINEAR_VERTICAL); + break; + case SCROLLVIEW_DIR_HORIZONTAL: + setLayoutType(LAYOUT_LINEAR_HORIZONTAL); + break; + case SCROLLVIEW_DIR_BOTH: + return; + default: + return; + break; + } + UIScrollView::setDirection(dir); + +} + +void UIListView::refreshView() +{ + if (!_items) + { + return; + } + cocos2d::ccArray* arrayItems = _items->data; + int length = arrayItems->num; + for (int i=0; iarr[i]); + item->setZOrder(i); + remedyLayoutParameter(item); + } + updateInnerContainerSize(); + doLayout(); +} + void UIListView::onSizeChanged() { - Layout::onSizeChanged(); - _topBoundary = _size.height; - _rightBoundary = _size.width; -} - -bool UIListView::addChild(UIWidget* widget) -{ - Layout::addChild(widget); - resetProperty(); - return true; -} - -void UIListView::removeAllChildren() -{ - _updatePool->removeAllObjects(); - _childPool->removeAllObjects(); - Layout::removeAllChildren(); -} - -bool UIListView::removeChild(UIWidget* child) -{ - bool value = false; - - if (Layout::removeChild(child)) - { - value = true; - resetProperty(); - } - - return value; -} - -bool UIListView::onTouchBegan(const Point &touchPoint) -{ - bool pass = Layout::onTouchBegan(touchPoint); - handlePressLogic(touchPoint); - return pass; -} - -void UIListView::onTouchMoved(const Point &touchPoint) -{ - Layout::onTouchMoved(touchPoint); - handleMoveLogic(touchPoint); -} - -void UIListView::onTouchEnded(const Point &touchPoint) -{ - Layout::onTouchEnded(touchPoint); - handleReleaseLogic(touchPoint); -} - -void UIListView::onTouchCancelled(const Point &touchPoint) -{ - Layout::onTouchCancelled(touchPoint); -} - -void UIListView::onTouchLongClicked(const Point &touchPoint) -{ - -} - -void UIListView::update(float dt) -{ - if (_autoScroll) - { - autoScrollChildren(dt); - } - recordSlidTime(dt); -} - -void UIListView::setDirection(ListViewDirection dir) -{ - _direction = dir; -} - -ListViewDirection UIListView::getDirection() -{ - return _direction; -} - -void UIListView::resetProperty() -{ - ccArray* arrayChildren = _children->data; - - if (arrayChildren->num <= 0) - { - return; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - if (_topBoundary == 0) - { - return; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - if (_rightBoundary == 0) - { - return; - } - break; - - default: - break; - } - - float scroll_top = _topBoundary; - float scroll_left = _leftBoundary; - - switch (_children->count()) - { - case 1: - { - UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float child_0_top = child_0->getTopInParent(); - _disBoundaryToChild_0 = scroll_top - child_0_top; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float child_0_left = child_0->getLeftInParent(); - _disBoundaryToChild_0 = child_0_left - scroll_left; - } - break; - - default: - break; - } - } - break; - - default: - { - UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); - UIWidget* child_1 = dynamic_cast(arrayChildren->arr[1]); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float child_0_top = child_0->getTopInParent(); - _disBoundaryToChild_0 = scroll_top - child_0_top; - _disBetweenChild = child_0->getPosition().y - child_1->getPosition().y; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float child_0_left = child_0->getLeftInParent(); - _disBoundaryToChild_0 = child_0_left - scroll_left; - _disBetweenChild = child_1->getPosition().x - child_0->getPosition().x; - } - break; - - default: - break; - } - } - break; - } -} - -void UIListView::handlePressLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - _touchMoveStartLocation = nsp.y; - _touchStartLocation = nsp.y; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - _touchMoveStartLocation = nsp.x; - _touchStartLocation = nsp.x; - break; - - default: - break; - } - startRecordSlidAction(); - clearCollectOverArray(); -} - -void UIListView::handleMoveLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - float offset = 0.0f; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float moveY = nsp.y; - offset = moveY - _touchMoveStartLocation; - _touchMoveStartLocation = moveY; - - if (offset < 0.0f) - { - _moveDirection = LISTVIEW_MOVE_DIR_DOWN; // down - } - else if (offset > 0.0f) - { - _moveDirection = LISTVIEW_MOVE_DIR_UP; // up - } - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float moveX = nsp.x; - offset = moveX - _touchMoveStartLocation; - _touchMoveStartLocation = moveX; - - if (offset < 0) - { - _moveDirection = LISTVIEW_MOVE_DIR_LEFT; // left - } - else if (offset > 0) - { - _moveDirection = LISTVIEW_MOVE_DIR_RIGHT; // right - } - } - break; - - default: - break; - } - scrollChildren(offset); -} - -void UIListView::handleReleaseLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - _touchEndLocation = nsp.y; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - _touchEndLocation = nsp.x; - break; - - default: - break; - } - endRecordSlidAction(); -} - -void UIListView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) -{ - switch (handleState) - { - case 0: - handlePressLogic(touchPoint); - break; - - case 1: - { - float offset = 0; - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - offset = fabs(sender->getTouchStartPos().y - touchPoint.y); - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - offset = fabs(sender->getTouchStartPos().x - touchPoint.x); - break; - - default: - break; - } - if (offset > _childFocusCancelOffset) - { - sender->setFocused(false); - handleMoveLogic(touchPoint); - } - } - break; - - case 2: - handleReleaseLogic(touchPoint); - break; - - case 3: - break; - } -} - -void UIListView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) -{ - interceptTouchEvent(handleState, sender, touchPoint); -} - -void UIListView::moveChildren(float offset) -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - ccArray* arrayChildren = _children->data; - int childrenCount = arrayChildren->num; - for (int i = 0; i < childrenCount; i++) - { - UIWidget* child = (UIWidget*)(arrayChildren->arr[i]); - _moveChildPoint.x = child->getPosition().x; - _moveChildPoint.y = child->getPosition().y + offset; - child->setPosition(_moveChildPoint); - } - break; - } - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - ccArray* arrayChildren = _children->data; - int childrenCount = arrayChildren->num; - for (int i=0;iarr[i]); - _moveChildPoint.x = child->getPosition().x + offset; - _moveChildPoint.y = child->getPosition().y; - child->setPosition(_moveChildPoint); - } - break; - } - - default: - break; - } -} - -bool UIListView::scrollChildren(float touchOffset) -{ - float realOffset = touchOffset; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - realOffset = MIN(realOffset, _disBetweenChild); - - UIWidget* child_last = dynamic_cast(_childPool->getLastObject()); - float child_last_bottom = child_last->getBottomInParent(); - float scroll_bottom = _bottomBoundary; - - if (_end == _dataLength - 1) - { - if (realOffset > scroll_bottom + _disBoundaryToChild_0 - child_last_bottom) - { - realOffset = scroll_bottom + _disBoundaryToChild_0 - child_last_bottom; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_end < _dataLength - 1) - { - collectOverTopChild(); - unsigned int count = _overTopArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overTopArray->removeAllObjects(); - } - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - realOffset = MAX(realOffset, -_disBetweenChild); - - UIWidget* child_0 = dynamic_cast(_childPool->getObjectAtIndex(0)); - float child_0_top = child_0->getTopInParent(); - float scroll_top = _topBoundary; - - if (_begin == 0) - { - if (realOffset < scroll_top - _disBoundaryToChild_0 - child_0_top) - { - realOffset = scroll_top - _disBoundaryToChild_0 - child_0_top; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_begin > 0) - { - collectOverBottomChild(); - int count = _overBottomArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overBottomArray->removeAllObjects(); - } - } - } - break; - - default: - break; - } - return true; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - realOffset = MAX(realOffset, -_disBetweenChild); - - UIWidget* child_last = dynamic_cast(_childPool->getLastObject()); - float child_last_right = child_last->getRightInParent(); - float scroll_right = _rightBoundary; - - if (_end == _dataLength - 1) - { - if (realOffset < scroll_right - _disBoundaryToChild_0 - child_last_right) - { - realOffset = scroll_right - _disBoundaryToChild_0 - child_last_right; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_end < _dataLength - 1) - { - collectOverLeftChild(); - int count = _overLeftArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overLeftArray->removeAllObjects(); - } - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - realOffset = MIN(realOffset, _disBetweenChild); - - UIWidget* child_0 = dynamic_cast(_childPool->getObjectAtIndex(0)); - float child_0_left = child_0->getLeftInParent(); - float scroll_left = _leftBoundary; - - if (_begin == 0) - { - if (realOffset > scroll_left + _disBoundaryToChild_0 - child_0_left) - { - realOffset = scroll_left + _disBoundaryToChild_0 - child_0_left; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - collectOverRightChild(); - int count = _overRightArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overRightArray->removeAllObjects(); - } - } - break; - - default: - break; - } - return true; - break; - - default: - break; - } - - return false; -} - -void UIListView::autoScrollChildren(float dt) -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -float UIListView::getCurAutoScrollDistance(float time) -{ - float dt = time; - _autoScrollOriginalSpeed -= _autoScrollAcceleration*dt; - return _autoScrollOriginalSpeed*dt; -} - -void UIListView::startAutoScrollChildren(float v) -{ - _autoScrollOriginalSpeed = v; - _autoScroll = true; -} - -void UIListView::stopAutoScrollChildren() -{ - _autoScroll = false; - _autoScrollOriginalSpeed = 0.0f; -} - -void UIListView::recordSlidTime(float dt) -{ - if (_bePressed) - { - _slidTime += dt; - } -} - -void UIListView::startRecordSlidAction() -{ - if (_children->count() <= 0) - { - return; - } - if (_autoScroll) - { - stopAutoScrollChildren(); - } - _bePressed = true; - _slidTime = 0.0; -} - -void UIListView::endRecordSlidAction() -{ - if (_children->count() <= 0) - { - return; - } - if (_slidTime <= 0.016f) - { - return; - } - float totalDis = 0; - totalDis = _touchEndLocation-_touchStartLocation; - float orSpeed = fabs(totalDis)/(_slidTime); - startAutoScrollChildren(orSpeed / 4); - - _bePressed = false; - _slidTime = 0.0; -} - -UIWidget* UIListView::getCheckPositionChild() -{ - UIWidget* child = NULL; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - child = dynamic_cast(_childPool->getLastObject()); - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - child = dynamic_cast(_childPool->getObjectAtIndex(0)); - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - child = dynamic_cast(_childPool->getLastObject()); - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - child = dynamic_cast(_childPool->getObjectAtIndex(0)); - break; - - default: - break; - } - break; - - default: - break; - } - - return child; -} - -void UIListView::initChildWithDataLength(int length) -{ - _dataLength = length; - _begin = 0; - _end = 0; - - // init child pool - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - setUpdateChild(child); - setUpdateDataIndex(i); - initChildEvent(); - _childPool->addObject(child); - _end = i; - } -} - -UIWidget* UIListView::getChildFromUpdatePool() -{ - UIWidget* child = dynamic_cast(_updatePool->getLastObject()); - _updatePool->removeLastObject(); - return child; -} - -void UIListView::pushChildToPool() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - UIWidget* child = dynamic_cast(_childPool->getObjectAtIndex(0)); - _updatePool->insertObject(child, 0); - _childPool->removeObjectAtIndex(0); - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - UIWidget* child = dynamic_cast(_childPool->getLastObject()); - _updatePool->insertObject(child, 0); - _childPool->removeLastObject(); - - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - UIWidget* child = dynamic_cast(_childPool->getObjectAtIndex(0)); - _updatePool->insertObject(child, 0); - _childPool->removeObjectAtIndex(0); - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - UIWidget* child = dynamic_cast(_childPool->getLastObject()); - _updatePool->insertObject(child, 0); - _childPool->removeLastObject(); - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::getAndCallback() -{ - UIWidget* child = getChildFromUpdatePool(); - - if (child == NULL) - { - return; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - ++_end; - setUpdateChild(child); - setUpdateDataIndex(_end); - updateChildEvent(); - - if (_updateSuccess == false) - { - --_end; - _childPool->insertObject(child, 0); - return; - } - ++_begin; - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - --_begin; - setUpdateChild(child); - setUpdateDataIndex(_begin); - updateChildEvent(); - - if (_updateSuccess == false) - { - ++_begin; - _childPool->addObject(child); - return; - } - --_end; - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - ++_end; - setUpdateChild(child); - setUpdateDataIndex(_end); - updateChildEvent(); - - if (_updateSuccess == false) - { - --_end; - _childPool->insertObject(child, 0); - return; - } - ++_begin; - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - --_begin; - setUpdateChild(child); - setUpdateDataIndex(_begin); - updateChildEvent(); - - if (_updateSuccess == false) - { - ++_begin; - _childPool->addObject(child); - return; - } - --_end; - break; - - default: - break; - } - break; - - default: - break; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - _childPool->addObject(child); - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - _childPool->insertObject(child, 0); - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - _childPool->addObject(child); - break; - case LISTVIEW_MOVE_DIR_RIGHT: // right - _childPool->insertObject(child, 0); - break; - - default: - break; - } - break; - - default: - break; - } -} - -int UIListView::getDataLength() -{ - return _dataLength; -} - -UIWidget* UIListView::getUpdateChild() -{ - return _updateChild; -} - -void UIListView::setUpdateChild(UIWidget* child) -{ - _updateChild = child; -} - -int UIListView::getUpdateDataIndex() -{ - return _updateDataIndex; -} - -void UIListView::setUpdateDataIndex(int index) -{ - _updateDataIndex = index; -} - -bool UIListView::getUpdateSuccess() -{ - return _updateSuccess; -} - -void UIListView::setUpdateSuccess(bool sucess) -{ - _updateSuccess = sucess; -} - -void UIListView::clearCollectOverArray() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: - _overTopArray->removeAllObjects(); - _overBottomArray->removeAllObjects(); - break; - - case LISTVIEW_DIR_HORIZONTAL: - _overLeftArray->removeAllObjects(); - _overRightArray->removeAllObjects(); - break; - - default: - break; - } -} - -void UIListView::collectOverTopChild() -{ - float scroll_top = _topBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_bottom = child->getBottomInParent(); - - if (child_bottom >= scroll_top) - { - _overTopArray->addObject(child); - } - } -} - -void UIListView::collectOverBottomChild() -{ - float scroll_bottom = _bottomBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_top = child->getTopInParent(); - - if (child_top <= scroll_bottom) - { - _overBottomArray->addObject(child); - } - } -} - -void UIListView::collectOverLeftChild() -{ - float scroll_left = _leftBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_right = child->getRightInParent(); - - if (child_right <= scroll_left) - { - _overLeftArray->addObject(child); - } - } -} - -void UIListView::collectOverRightChild() -{ - float scroll_right = _rightBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_left = child->getLeftInParent(); - if (child_left >= scroll_right) - { - _overRightArray->addObject(child); - } - } -} - -void UIListView::setLoopPosition() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overTopArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overTopArray->getObjectAtIndex(i)); - - if (i == 0) - { - float height = child->getSize().height; - float offset = (child->getWidgetType() == WidgetTypeWidget) ? height / 2 : height; - float y = _topBoundary - _disBoundaryToChild_0 - offset; - child->setPosition(Point(child->getPosition().x, y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overTopArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - _disBetweenChild)); - } - } - } - else - { - float scroll_top = _topBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_bottom = child->getBottomInParent(); - - if (child_bottom >= scroll_top) - { - int index = (i == 0) ? (count - 1) : (i - 1); - UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - _disBetweenChild)); - } - } - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overBottomArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overBottomArray->getObjectAtIndex(i)); - - if (i == 0) - { - float y = _bottomBoundary + _disBoundaryToChild_0 - _disBetweenChild; - child->setPosition(Point(child->getPosition().x, y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overBottomArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y + _disBetweenChild)); - } - } - } - else - { - float scroll_bottom = _bottomBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = count - 1; i >= 0; --i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_top = child->getTopInParent(); - - if (child_top <= scroll_bottom) - { - int index = (i == count - 1) ? 0 : (i + 1); - UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(child->getPosition().x, next_child->getPosition().y + _disBetweenChild)); - } - } - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overLeftArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overLeftArray->getObjectAtIndex(i)); - - if (i == 0) - { - float width = child->getSize().width; - float offset = (child->getWidgetType() == WidgetTypeWidget) ? (width / 2) : 0; - float x = _leftBoundary + _disBoundaryToChild_0 + width + offset; - child->setPosition(Point(x, child->getPosition().y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overLeftArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(prev_child->getPosition().x + _disBetweenChild, child->getPosition().y)); - } - } - } - else - { - float scroll_left = _leftBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_right = child->getRightInParent(); - - if (child_right <= scroll_left) - { - int index = (i == 0) ? (count - 1) : (i - 1); - UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(prev_child->getPosition().x + _disBetweenChild, child->getPosition().y)); - } - } - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overRightArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overRightArray->getObjectAtIndex(i)); - - if (i == 0) - { - float x = _rightBoundary - _disBoundaryToChild_0 + _disBetweenChild; - child->setPosition(Point(x, child->getPosition().y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overRightArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(prev_child->getPosition().x - _disBetweenChild, child->getPosition().y)); - } - } - } - else - { - float scroll_right = _rightBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = count - 1; i >= 0; --i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_left = child->getLeftInParent(); - - if (child_left >= scroll_right) - { - int index = (i == count - 1) ? 0 : (i + 1); - UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(next_child->getPosition().x - _disBetweenChild, child->getPosition().y)); - } - } - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::updateChild() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - int count = _overTopArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - int count = _overBottomArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - int count = _overLeftArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - int count = _overRightArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::initChildEvent() -{ - if (_eventListener && _eventSelector) - { - (_eventListener->*_eventSelector)(this, LISTVIEW_EVENT_INIT_CHILD); - } -} - -void UIListView::updateChildEvent() -{ - if (_eventListener && _eventSelector) - { - (_eventListener->*_eventSelector)(this, LISTVIEW_EVENT_UPDATE_CHILD); - } -} - -void UIListView::addEventListenter(Object *target, SEL_ListViewEvent selector) -{ - _eventListener = target; - _eventSelector = selector; + UIScrollView::onSizeChanged(); + refreshView(); } const char* UIListView::getDescription() const { - return "ListView"; + return "ListViewEx"; } +UIWidget* UIListView::createCloneInstance() +{ + return UIListView::create(); +} -} \ No newline at end of file +void UIListView::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayItems = dynamic_cast(model)->getItems()->data; + int length = arrayItems->num; + for (int i=0; iarr[i]); + pushBackCustomItem(item->clone()); + } +} + +void UIListView::copySpecialProperties(UIWidget *widget) +{ + UIListView* listViewEx = dynamic_cast(widget); + if (listViewEx) + { + UIScrollView::copySpecialProperties(widget); + setItemModel(listViewEx->_model); + setItemsMargin(listViewEx->_itemsMargin); + setGravity(listViewEx->_gravity); + } +} + +} diff --git a/cocos/gui/UIListView.h b/cocos/gui/UIListView.h index 8830db6209..c78d06ace2 100644 --- a/cocos/gui/UIListView.h +++ b/cocos/gui/UIListView.h @@ -22,226 +22,156 @@ THE SOFTWARE. ****************************************************************************/ + #ifndef __UILISTVIEW_H__ #define __UILISTVIEW_H__ -/* gui mark */ -#include "gui/Layout.h" -/**/ +#include "gui/UIScrollView.h" -namespace gui { - -/** - * list view direction - */ -typedef enum LISTVIEW_DIR -{ - LISTVIEW_DIR_NONE, - LISTVIEW_DIR_VERTICAL, - LISTVIEW_DIR_HORIZONTAL -}ListViewDirection; - -/** - * list view scroll direction - */ -typedef enum LISTVIEW_MOVE_DIR -{ - LISTVIEW_MOVE_DIR_NONE, - LISTVIEW_MOVE_DIR_UP, - LISTVIEW_MOVE_DIR_DOWN, - LISTVIEW_MOVE_DIR_LEFT, - LISTVIEW_MOVE_DIR_RIGHT, -}ListViewMoveDirection; +namespace gui{ typedef enum { - LISTVIEW_EVENT_INIT_CHILD, - LISTVIEW_EVENT_UPDATE_CHILD, -}ListViewEventType; + LISTVIEW_GRAVITY_LEFT, + LISTVIEW_GRAVITY_RIGHT, + LISTVIEW_GRAVITY_CENTER_HORIZONTAL, + + LISTVIEW_GRAVITY_TOP, + LISTVIEW_GRAVITY_BOTTOM, + LISTVIEW_GRAVITY_CENTER_VERTICAL, +}ListViewGravity; -/** - * list view event - */ -typedef void (cocos2d::Object::*SEL_ListViewEvent)(cocos2d::Object*, ListViewEventType); -#define listvieweventselector(_SELECTOR)(SEL_ListViewEvent)(&_SELECTOR) - -class UIListView : public Layout +class UIListView : public UIScrollView { + public: + + /** + * Default constructor + */ UIListView(); + + /** + * Default destructor + */ virtual ~UIListView(); + + /** + * Allocates and initializes. + */ static UIListView* create(); /** - * add widget child override + * Sets a item model for listview + * + * A model will be cloned for adding default item. + * + * @param model item model for listview */ - virtual bool addChild(UIWidget* widget); - /** - * remove all widget children override - */ - virtual void removeAllChildren(); - /** - * remove widget child override - */ - virtual bool removeChild(UIWidget* child); - - virtual bool onTouchBegan(const cocos2d::Point &touchPoint); - virtual void onTouchMoved(const cocos2d::Point &touchPoint); - virtual void onTouchEnded(const cocos2d::Point &touchPoint); - virtual void onTouchCancelled(const cocos2d::Point &touchPoint); - virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); + void setItemModel(UIWidget* model); /** - * set and get direction + * Push back a default item(create by a cloned model) into listview. */ - void setDirection(ListViewDirection dir); - ListViewDirection getDirection(); + void pushBackDefaultItem(); /** - * initialze data length - * and create children with parameter length + * Insert a default item(create by a cloned model) into listview. */ - void initChildWithDataLength(int length); - /** - * get data length - */ - int getDataLength(); + void insertDefaultItem(int index); /** - * update child function whetn trigger update child event + * Push back custom item into listview. */ - /** - * get update widget child - */ - UIWidget* getUpdateChild(); - /** - * get update data index - */ - int getUpdateDataIndex(); - /** - * get and set update success or not - */ - bool getUpdateSuccess(); - void setUpdateSuccess(bool sucess); + void pushBackCustomItem(UIWidget* item); /** - * add event call-back function + * Insert custom item into listview. */ - /** - * add event - */ - void addEventListenter(cocos2d::Object* target, SEL_ListViewEvent selector); - - /* gui mark */ - /** - * get and set degree range for checking move or not with scrolling - */ - /**/ - virtual void update(float dt); - - virtual void doLayout(){}; + void insertCustomItem(UIWidget* item, int index); /** - * Returns the "class name" of widget. + * Removes the last item of listview. */ + void removeLastItem(); + + /** + * Removes a item whose index is same as the parameter. + * + * @param index of item. + */ + void removeItem(int index); + + /** + * Returns a item whose index is same as the parameter. + * + * @param index of item. + * + * @return the item widget. + */ + UIWidget* getItem(unsigned int index); + + /** + * Returns the item container. + */ + cocos2d::Array* getItems(); + + /** + * Returns the index of item. + * + * @param item the item which need to be checked. + * + * @return the index of item. + */ + unsigned int getIndex(UIWidget* item) const; + + /** + * Changes the gravity of listview. + * @see ListViewGravity + */ + void setGravity(ListViewGravity gravity); + + /** + * Changes the margin between each item. + * + * @param margin + */ + void setItemsMargin(float margin); + + /** + * Refresh the view of list. + * + * If you change the data, you need to call this mathod. + */ + void refreshView(); + + /** + * Changes scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @param SCROLLVIEW_DIR + */ + virtual void setDirection(SCROLLVIEW_DIR dir); + virtual const char* getDescription() const; + protected: virtual bool init(); - + void updateInnerContainerSize(); + void remedyLayoutParameter(UIWidget* item); virtual void onSizeChanged(); - - void setMoveDirection(ListViewMoveDirection dir); - ListViewMoveDirection getMoveDirection(); - - virtual void resetProperty(); - - virtual void handlePressLogic(const cocos2d::Point &touchPoint); - virtual void handleMoveLogic(const cocos2d::Point &touchPoint); - virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); - /* gui mark */ -// virtual bool isInScrollDegreeRange(UIWidget* widget); - /**/ - virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); - - void moveChildren(float offset); - virtual bool scrollChildren(float touchOffset); - void autoScrollChildren(float dt); - float getCurAutoScrollDistance(float time); - void startAutoScrollChildren(float v); - void stopAutoScrollChildren(); - void recordSlidTime(float dt); - void startRecordSlidAction(); - virtual void endRecordSlidAction(); - - UIWidget* getCheckPositionChild(); - UIWidget* getChildFromUpdatePool(); - void pushChildToPool(); - void getAndCallback(); - - void setUpdateChild(UIWidget* child); - void setUpdateDataIndex(int index); - void clearCollectOverArray(); - void collectOverTopChild(); - void collectOverBottomChild(); - void collectOverLeftChild(); - void collectOverRightChild(); - void setLoopPosition(); - void updateChild(); - - void initChildEvent(); - void updateChildEvent(); - - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: - ListViewDirection _direction; - ListViewMoveDirection _moveDirection; - float _touchStartLocation; - float _touchEndLocation; - float _touchMoveStartLocation; - float _topBoundary;//test - float _bottomBoundary;//test - float _leftBoundary; - float _rightBoundary; - - bool _autoScroll; - - float _autoScrollOriginalSpeed; - float _autoScrollAcceleration; - - bool _bePressed; - float _slidTime; - cocos2d::Point _moveChildPoint; - float _childFocusCancelOffset; - - cocos2d::Object* _eventListener; - SEL_ListViewEvent _eventSelector; - - cocos2d::Array* _childPool; - cocos2d::Array* _updatePool; - - int _dataLength; - int _begin; - int _end; - UIWidget* _updateChild; - int _updateDataIndex; - bool _updateSuccess; - - cocos2d::Array* _overTopArray; - cocos2d::Array* _overBottomArray; - cocos2d::Array* _overLeftArray; - cocos2d::Array* _overRightArray; - - float _disBoundaryToChild_0; - float _disBetweenChild; - - /* gui mark */ - float _scrollDegreeRange; - /**/ + UIWidget* _model; + cocos2d::Array* _items; + ListViewGravity _gravity; + float _itemsMargin; }; } - -#endif /* defined(__Test__UIListView__) */ +#endif /* defined(__UIListView__) */ diff --git a/cocos/gui/UILoadingBar.cpp b/cocos/gui/UILoadingBar.cpp index 6d74be86c4..09b78c7b25 100644 --- a/cocos/gui/UILoadingBar.cpp +++ b/cocos/gui/UILoadingBar.cpp @@ -25,11 +25,9 @@ #include "gui/UILoadingBar.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - using namespace cocos2d; - using namespace cocos2d::extension; - namespace gui { + #define DYNAMIC_CAST_CCSPRITE dynamic_cast(_barRenderer) UILoadingBar::UILoadingBar(): @@ -38,10 +36,10 @@ _percent(100), _totalLength(0), _barRenderer(NULL), _renderBarTexType(UI_TEX_TYPE_LOCAL), -_barRendererTextureSize(Size::ZERO), +_barRendererTextureSize(cocos2d::Size::ZERO), _scale9Enabled(false), _prevIgnoreSize(true), -_capInsets(Rect::ZERO), +_capInsets(cocos2d::Rect::ZERO), _textureFile("") { } @@ -66,9 +64,9 @@ UILoadingBar* UILoadingBar::create() void UILoadingBar::initRenderer() { UIWidget::initRenderer(); - _barRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); _renderer->addChild(_barRenderer); - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0,0.5)); } void UILoadingBar::setDirection(LoadingBarType dir) @@ -82,19 +80,19 @@ void UILoadingBar::setDirection(LoadingBarType dir) switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); - _barRenderer->setPosition(Point(-_totalLength*0.5f,0.0f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0f,0.5f)); + _barRenderer->setPosition(cocos2d::Point(-_totalLength*0.5f,0.0f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(false); + dynamic_cast(_barRenderer)->setFlippedX(false); } break; case LoadingBarTypeRight: - _barRenderer->setAnchorPoint(Point(1.0f,0.5f)); - _barRenderer->setPosition(Point(_totalLength*0.5f,0.0f)); + _barRenderer->setAnchorPoint(cocos2d::Point(1.0f,0.5f)); + _barRenderer->setPosition(cocos2d::Point(_totalLength*0.5f,0.0f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(true); + dynamic_cast(_barRenderer)->setFlippedX(true); } break; } @@ -118,21 +116,23 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->setCapInsets(_capInsets); } else { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->initWithFile(texture); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->setCapInsets(_capInsets); } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); } break; default: @@ -140,31 +140,31 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) } if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + } else { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } - _barRendererTextureSize.width = _barRenderer->getContentSize().width; - _barRendererTextureSize.height = _barRenderer->getContentSize().height; + _barRendererTextureSize = _barRenderer->getContentSize(); switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0f,0.5f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(false); + dynamic_cast(_barRenderer)->setFlippedX(false); } break; case LoadingBarTypeRight: - _barRenderer->setAnchorPoint(Point(1.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(1.0f,0.5f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(true); + dynamic_cast(_barRenderer)->setFlippedX(true); } break; } @@ -182,11 +182,11 @@ void UILoadingBar::setScale9Enabled(bool enabled) _barRenderer = NULL; if (_scale9Enabled) { - _barRenderer = Scale9Sprite::create(); + _barRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _barRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); } loadTexture(_textureFile.c_str(),_renderBarTexType); _renderer->addChild(_barRenderer); @@ -203,14 +203,14 @@ void UILoadingBar::setScale9Enabled(bool enabled) setCapInsets(_capInsets); } -void UILoadingBar::setCapInsets(const Rect &capInsets) +void UILoadingBar::setCapInsets(const cocos2d::Rect &capInsets) { _capInsets = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_barRenderer)->setCapInsets(capInsets); + dynamic_cast(_barRenderer)->setCapInsets(capInsets); } void UILoadingBar::setPercent(int percent) @@ -231,10 +231,10 @@ void UILoadingBar::setPercent(int percent) { case UI_TEX_TYPE_PLIST: { - Sprite* barNode = DYNAMIC_CAST_CCSPRITE; + cocos2d::Sprite* barNode = DYNAMIC_CAST_CCSPRITE; if (barNode) { - Point to = barNode->getTextureRect().origin; + cocos2d::Point to = barNode->getTextureRect().origin; x = to.x; y = to.y; } @@ -249,7 +249,7 @@ void UILoadingBar::setPercent(int percent) } else { - dynamic_cast(_barRenderer)->setTextureRect(Rect(x, y, _barRendererTextureSize.width * res, _barRendererTextureSize.height)); + dynamic_cast(_barRenderer)->setTextureRect(cocos2d::Rect(x, y, _barRendererTextureSize.width * res, _barRendererTextureSize.height)); } } @@ -272,12 +272,12 @@ void UILoadingBar::ignoreContentAdaptWithSize(bool ignore) } } -const Size& UILoadingBar::getContentSize() const +const cocos2d::Size& UILoadingBar::getContentSize() const { return _barRendererTextureSize; } -Node* UILoadingBar::getVirtualRenderer() +cocos2d::Node* UILoadingBar::getVirtualRenderer() { return _barRenderer; } @@ -303,7 +303,7 @@ void UILoadingBar::barRendererScaleChangedWithSize() else { - Size textureSize = _barRenderer->getContentSize(); + cocos2d::Size textureSize = _barRendererTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); @@ -318,10 +318,10 @@ void UILoadingBar::barRendererScaleChangedWithSize() switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setPosition(Point(-_totalLength * 0.5f, 0.0f)); + _barRenderer->setPosition(cocos2d::Point(-_totalLength * 0.5f, 0.0f)); break; case LoadingBarTypeRight: - _barRenderer->setPosition(Point(_totalLength * 0.5f, 0.0f)); + _barRenderer->setPosition(cocos2d::Point(_totalLength * 0.5f, 0.0f)); break; default: break; @@ -331,7 +331,7 @@ void UILoadingBar::barRendererScaleChangedWithSize() void UILoadingBar::setScale9Scale() { float width = (float)(_percent) / 100 * _totalLength; - dynamic_cast(_barRenderer)->setPreferredSize(Size(width, _barRendererTextureSize.height)); + dynamic_cast(_barRenderer)->setPreferredSize(cocos2d::Size(width, _size.height)); } const char* UILoadingBar::getDescription() const @@ -339,4 +339,22 @@ const char* UILoadingBar::getDescription() const return "LoadingBar"; } +UIWidget* UILoadingBar::createCloneInstance() +{ + return UILoadingBar::create(); +} + +void UILoadingBar::copySpecialProperties(UIWidget *widget) +{ + UILoadingBar* loadingBar = dynamic_cast(widget); + if (loadingBar) + { + _prevIgnoreSize = loadingBar->_prevIgnoreSize; + setScale9Enabled(loadingBar->_scale9Enabled); + loadTexture(loadingBar->_textureFile.c_str(), loadingBar->_renderBarTexType); + setCapInsets(loadingBar->_capInsets); + setPercent(loadingBar->_percent); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILoadingBar.h b/cocos/gui/UILoadingBar.h index b67e7314f5..81c5722b4b 100644 --- a/cocos/gui/UILoadingBar.h +++ b/cocos/gui/UILoadingBar.h @@ -34,7 +34,10 @@ typedef enum LoadingBarTypeLeft, LoadingBarTypeRight }LoadingBarType; - +/** +* @js NA +* @lua NA +*/ class UILoadingBar : public UIWidget { public: @@ -126,6 +129,8 @@ protected: virtual void onSizeChanged(); void setScale9Scale(); void barRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: LoadingBarType _barType; int _percent; diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 0fc6558975..8498e79d88 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -24,8 +24,6 @@ #include "gui/UIPageView.h" - using namespace cocos2d; - namespace gui { UIPageView::UIPageView(): @@ -33,9 +31,8 @@ _curPageIdx(0), _pages(NULL), _touchMoveDir(PAGEVIEW_TOUCHLEFT), _touchStartLocation(0.0f), -_touchEndLocation(0.0f), _touchMoveStartLocation(0.0f), -_movePagePoint(Point::ZERO), +_movePagePoint(cocos2d::Point::ZERO), _leftChild(NULL), _rightChild(NULL), _leftBoundary(0.0f), @@ -52,7 +49,8 @@ _eventSelector(NULL) UIPageView::~UIPageView() { - _pages->release(); + _pages->removeAllObjects(); + CC_SAFE_RELEASE(_pages); } UIPageView* UIPageView::create() @@ -69,12 +67,13 @@ UIPageView* UIPageView::create() bool UIPageView::init() { - if (Layout::init()) + if (UILayout::init()) { - _pages = CCArray::create(); + _pages = cocos2d::Array::create(); _pages->retain(); setClippingEnabled(true); setUpdateEnabled(true); + setTouchEnabled(true); return true; } return false; @@ -86,6 +85,10 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate { return; } + if (pageIdx < 0) + { + return; + } int pageCount = _pages->count(); if (pageIdx < 0 || pageIdx >= pageCount) { @@ -95,30 +98,29 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate { CCLOG("pageIdx is %d, it will be added as page id [%d]",pageIdx,pageCount); } - Layout* newPage = createPage(); + UILayout* newPage = createPage(); newPage->addChild(widget); addPage(newPage); } } else { - Layout * page = dynamic_cast(_pages->getObjectAtIndex(pageIdx)); + UILayout * page = dynamic_cast(_pages->getObjectAtIndex(pageIdx)); if (page) { page->addChild(widget); } } - } -Layout* UIPageView::createPage() +UILayout* UIPageView::createPage() { - Layout* newPage = Layout::create(); + UILayout* newPage = UILayout::create(); newPage->setSize(getSize()); return newPage; } -void UIPageView::addPage(Layout* page) +void UIPageView::addPage(UILayout* page) { if (!page) { @@ -132,20 +134,20 @@ void UIPageView::addPage(Layout* page) { return; } - Size pSize = page->getSize(); - Size pvSize = getSize(); + cocos2d::Size pSize = page->getSize(); + cocos2d::Size pvSize = getSize(); if (!pSize.equals(pvSize)) { CCLOG("page size does not match pageview size, it will be force sized!"); page->setSize(pvSize); } - page->setPosition(Point(getPositionXByIndex(_pages->count()), 0)); + page->setPosition(cocos2d::Point(getPositionXByIndex(_pages->count()), 0)); _pages->addObject(page); addChild(page); updateBoundaryPages(); } -void UIPageView::insertPage(Layout* page, int idx) +void UIPageView::insertPage(UILayout* page, int idx) { if (idx < 0) { @@ -172,27 +174,27 @@ void UIPageView::insertPage(Layout* page, int idx) else { _pages->insertObject(page, idx); - page->setPosition(Point(getPositionXByIndex(idx), 0)); + page->setPosition(cocos2d::Point(getPositionXByIndex(idx), 0)); addChild(page); - Size pSize = page->getSize(); - Size pvSize = getSize(); + cocos2d::Size pSize = page->getSize(); + cocos2d::Size pvSize = getSize(); if (!pSize.equals(pvSize)) { CCLOG("page size does not match pageview size, it will be force sized!"); page->setSize(pvSize); } - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; int length = arrayPages->num; for (int i=(idx+1); i(arrayPages->arr[i]); - Point formerPos = behindPage->getPosition(); - behindPage->setPosition(Point(formerPos.x+getSize().width, 0)); + cocos2d::Point formerPos = behindPage->getPosition(); + behindPage->setPosition(cocos2d::Point(formerPos.x+getSize().width, 0)); } updateBoundaryPages(); } } -void UIPageView::removePage(Layout* page) +void UIPageView::removePage(UILayout* page) { if (!page) { @@ -209,7 +211,7 @@ void UIPageView::removePageAtIndex(int index) { return; } - Layout* page = dynamic_cast(_pages->getObjectAtIndex(index)); + UILayout* page = dynamic_cast(_pages->getObjectAtIndex(index)); if (page) { removePage(page); @@ -222,6 +224,7 @@ void UIPageView::updateBoundaryPages() { _leftChild = NULL; _rightChild = NULL; + return; } _leftChild = dynamic_cast(_pages->getObjectAtIndex(0)); _rightChild = dynamic_cast(_pages->getLastObject()); @@ -234,7 +237,7 @@ float UIPageView::getPositionXByIndex(int idx) bool UIPageView::addChild(UIWidget* widget) { - return Layout::addChild(widget); + return UILayout::addChild(widget); } bool UIPageView::removeChild(UIWidget* widget) @@ -242,14 +245,14 @@ bool UIPageView::removeChild(UIWidget* widget) if (_pages->containsObject(widget)) { _pages->removeObject(widget); - return Layout::removeChild(widget); + return UILayout::removeChild(widget); } return false; } void UIPageView::onSizeChanged() { - Layout::onSizeChanged(); + UILayout::onSizeChanged(); _rightBoundary = getSize().width; updateChildrenSize(); updateChildrenPosition(); @@ -262,10 +265,10 @@ void UIPageView::updateChildrenSize() return; } - Size selfSize = getSize(); - for (int i = 0; i < _pages->count(); i++) + cocos2d::Size selfSize = getSize(); + for (unsigned int i=0; i<_pages->count(); i++) { - Layout* page = dynamic_cast(_pages->getObjectAtIndex(i)); + UILayout* page = dynamic_cast(_pages->getObjectAtIndex(i)); page->setSize(selfSize); } } @@ -288,18 +291,18 @@ void UIPageView::updateChildrenPosition() _curPageIdx = pageCount-1; } float pageWidth = getSize().width; - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; for (int i=0; i(arrayPages->arr[i]); - page->setPosition(Point((i-_curPageIdx)*pageWidth, 0)); + UILayout* page = dynamic_cast(arrayPages->arr[i]); + page->setPosition(cocos2d::Point((i-_curPageIdx)*pageWidth, 0)); } } void UIPageView::removeAllChildren() { _pages->removeAllObjects(); - Layout::removeAllChildren(); + UILayout::removeAllChildren(); } void UIPageView::scrollToPage(int idx) @@ -330,13 +333,16 @@ void UIPageView::update(float dt) step = -_autoScrollDistance; _autoScrollDistance = 0.0f; _isAutoScrolling = false; - pageTurningEvent(); } else { _autoScrollDistance += step; } scrollPages(-step); + if (!_isAutoScrolling) + { + pageTurningEvent(); + } break; } break; @@ -348,13 +354,16 @@ void UIPageView::update(float dt) step = _autoScrollDistance; _autoScrollDistance = 0.0f; _isAutoScrolling = false; - pageTurningEvent(); } else { _autoScrollDistance -= step; } scrollPages(step); + if (!_isAutoScrolling) + { + pageTurningEvent(); + } break; } default: @@ -363,14 +372,14 @@ void UIPageView::update(float dt) } } -bool UIPageView::onTouchBegan(const Point &touchPoint) +bool UIPageView::onTouchBegan(const cocos2d::Point &touchPoint) { - bool pass = Layout::onTouchBegan(touchPoint); + bool pass = UILayout::onTouchBegan(touchPoint); handlePressLogic(touchPoint); return pass; } -void UIPageView::onTouchMoved(const Point &touchPoint) +void UIPageView::onTouchMoved(const cocos2d::Point &touchPoint) { _touchMovePos.x = touchPoint.x; _touchMovePos.y = touchPoint.y; @@ -387,15 +396,15 @@ void UIPageView::onTouchMoved(const Point &touchPoint) } } -void UIPageView::onTouchEnded(const Point &touchPoint) +void UIPageView::onTouchEnded(const cocos2d::Point &touchPoint) { - Layout::onTouchEnded(touchPoint); + UILayout::onTouchEnded(touchPoint); handleReleaseLogic(touchPoint); } void UIPageView::movePages(float offset) { - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; int length = arrayPages->num; for (int i = 0; i < length; i++) { @@ -447,21 +456,21 @@ bool UIPageView::scrollPages(float touchOffset) return true; } -void UIPageView::onTouchCancelled(const Point &touchPoint) +void UIPageView::onTouchCancelled(const cocos2d::Point &touchPoint) { - Layout::onTouchCancelled(touchPoint); + UILayout::onTouchCancelled(touchPoint); } -void UIPageView::handlePressLogic(const Point &touchPoint) +void UIPageView::handlePressLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); _touchMoveStartLocation = nsp.x; _touchStartLocation = nsp.x; } -void UIPageView::handleMoveLogic(const Point &touchPoint) +void UIPageView::handleMoveLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); float offset = 0.0; float moveX = nsp.x; offset = moveX - _touchMoveStartLocation; @@ -477,12 +486,16 @@ void UIPageView::handleMoveLogic(const Point &touchPoint) scrollPages(offset); } -void UIPageView::handleReleaseLogic(const Point &touchPoint) +void UIPageView::handleReleaseLogic(const cocos2d::Point &touchPoint) { + if (_pages->count() <= 0) + { + return; + } UIWidget* curPage = dynamic_cast(_pages->getObjectAtIndex(_curPageIdx)); if (curPage) { - Point curPagePos = curPage->getPosition(); + cocos2d::Point curPagePos = curPage->getPosition(); int pageCount = _pages->count(); float curPageLocation = curPagePos.x; float pageWidth = getSize().width; @@ -516,12 +529,12 @@ void UIPageView::handleReleaseLogic(const Point &touchPoint) } } -void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const Point &touchPoint) +void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint) { interceptTouchEvent(handleState, sender, touchPoint); } -void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { switch (handleState) { @@ -556,7 +569,7 @@ void UIPageView::pageTurningEvent() } } -void UIPageView::addEventListener(Object *target, SEL_PageViewEvent selector) +void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { _eventListener = target; _eventSelector = selector; @@ -567,9 +580,39 @@ int UIPageView::getCurPageIndex() const return _curPageIdx; } +cocos2d::Array* UIPageView::getPages() +{ + return _pages; +} + const char* UIPageView::getDescription() const { return "PageView"; } +UIWidget* UIPageView::createCloneInstance() +{ + return UIPageView::create(); +} + +void UIPageView::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayPages = dynamic_cast(model)->getPages()->data; + int length = arrayPages->num; + for (int i=0; iarr[i]); + addPage(dynamic_cast(page->clone())); + } +} + +void UIPageView::copySpecialProperties(UIWidget *widget) +{ + UIPageView* pageView = dynamic_cast(widget); + if (pageView) + { + UILayout::copySpecialProperties(widget); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIPageView.h b/cocos/gui/UIPageView.h index e8d3d5192d..ec78df8bbd 100644 --- a/cocos/gui/UIPageView.h +++ b/cocos/gui/UIPageView.h @@ -25,7 +25,7 @@ #ifndef __UIPAGEVIEW_H__ #define __UIPAGEVIEW_H__ -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIScrollInterface.h" namespace gui { @@ -43,7 +43,7 @@ typedef enum { PAGEVIEW_TOUCHRIGHT }PVTouchDir; -class UIPageView : public Layout , public UIScrollInterface +class UIPageView : public UILayout , public UIScrollInterface { public: @@ -78,21 +78,21 @@ public: * * @param page page to be added to pageview. */ - void addPage(Layout* page); + void addPage(UILayout* page); /** * Inert a page to pageview. * * @param page page to be added to pageview. */ - void insertPage(Layout* page, int idx); + void insertPage(UILayout* page, int idx); /** * Remove a page of pageview. * * @param page page which will be removed. */ - void removePage(Layout* page); + void removePage(UILayout* page); /** * Remove a page at index of pageview. @@ -115,8 +115,11 @@ public: */ int getCurPageIndex() const; + cocos2d::Array* getPages(); + // event void addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector); + //override "removeChild" method of widget. virtual bool removeChild(UIWidget* widget); @@ -140,15 +143,16 @@ public: virtual void update(float dt); virtual void doLayout(){}; - + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual bool addChild(UIWidget* widget); virtual bool init(); - Layout* createPage(); + UILayout* createPage(); float getPositionXByIndex(int idx); void updateBoundaryPages(); virtual void handlePressLogic(const cocos2d::Point &touchPoint); @@ -162,14 +166,15 @@ protected: void updateChildrenSize(); void updateChildrenPosition(); virtual void onSizeChanged(); - - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); + virtual void setClippingEnabled(bool able){UILayout::setClippingEnabled(able);}; protected: int _curPageIdx; cocos2d::Array* _pages; PVTouchDir _touchMoveDir; float _touchStartLocation; - float _touchEndLocation; float _touchMoveStartLocation; cocos2d::Point _movePagePoint; UIWidget* _leftChild; @@ -183,6 +188,7 @@ protected: float _childFocusCancelOffset; cocos2d::Object* _eventListener; SEL_PageViewEvent _eventSelector; + }; } diff --git a/cocos/gui/UIRootWidget.cpp b/cocos/gui/UIRootWidget.cpp index f6bf7359f0..0b7581287f 100644 --- a/cocos/gui/UIRootWidget.cpp +++ b/cocos/gui/UIRootWidget.cpp @@ -24,8 +24,6 @@ #include "gui/UIRootWidget.h" - using namespace cocos2d; - namespace gui { UIRootWidget::UIRootWidget() @@ -50,9 +48,9 @@ UIRootWidget* UIRootWidget::create() bool UIRootWidget::init() { - if (Layout::init()) + if (UILayout::init()) { - setSize(Director::getInstance()->getWinSize()); + setSize(cocos2d::Director::getInstance()->getWinSize()); return true; } return false; diff --git a/cocos/gui/UIRootWidget.h b/cocos/gui/UIRootWidget.h index f4bff4955f..dc93ac4645 100644 --- a/cocos/gui/UIRootWidget.h +++ b/cocos/gui/UIRootWidget.h @@ -25,11 +25,15 @@ #ifndef __UIROOTWIDGET_H__ #define __UIROOTWIDGET_H__ -#include "gui/Layout.h" +#include "gui/UILayout.h" namespace gui { - -class UIRootWidget : public Layout + +/** +* @js NA +* @lua NA +*/ +class UIRootWidget : public UILayout { public: /** diff --git a/cocos/gui/UIScrollInterface.h b/cocos/gui/UIScrollInterface.h index 2e835982fd..dfff4cd66c 100644 --- a/cocos/gui/UIScrollInterface.h +++ b/cocos/gui/UIScrollInterface.h @@ -36,7 +36,6 @@ protected: virtual void handleMoveLogic(const cocos2d::Point &touchPoint) = 0; virtual void handleReleaseLogic(const cocos2d::Point &touchPoint) = 0; virtual void interceptTouchEvent(int handleState, UIWidget* sender, const cocos2d::Point &touchPoint) = 0; -// virtual bool isInScrollDegreeRange(UIWidget* widget) = 0; }; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index bdb3d45a21..1270c78682 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -23,34 +23,52 @@ ****************************************************************************/ #include "gui/UIScrollView.h" -#include "gui/UILayer.h" - - using namespace cocos2d; namespace gui { +#define AUTOSCROLLMAXSPEED 1000.0f + +const cocos2d::Point SCROLLDIR_UP = cocos2d::Point(0.0f, 1.0f); +const cocos2d::Point SCROLLDIR_DOWN = cocos2d::Point(0.0f, -1.0f); +const cocos2d::Point SCROLLDIR_LEFT = cocos2d::Point(-1.0f, 0.0f); +const cocos2d::Point SCROLLDIR_RIGHT = cocos2d::Point(1.0f, 0.0f); + UIScrollView::UIScrollView(): _innerContainer(NULL), _direction(SCROLLVIEW_DIR_VERTICAL), -_moveDirection(SCROLLVIEW_MOVE_DIR_NONE), -_touchStartLocation(0.0f), -_touchEndLocation(0.0f), -_touchMoveStartLocation(0.0f), +_touchBeganPoint(cocos2d::Point::ZERO), +_touchMovedPoint(cocos2d::Point::ZERO), +_touchEndedPoint(cocos2d::Point::ZERO), +_touchMovingPoint(cocos2d::Point::ZERO), +_autoScrollDir(cocos2d::Point::ZERO), _topBoundary(0.0f), _bottomBoundary(0.0f), _leftBoundary(0.0f), _rightBoundary(0.0f), -_topEnd(false), -_bottomEnd(false), -_leftEnd(false), -_rightEnd(false), +_bounceTopBoundary(0.0f), +_bounceBottomBoundary(0.0f), +_bounceLeftBoundary(0.0f), +_bounceRightBoundary(0.0f), _autoScroll(false), +_autoScrollAddUpTime(0.0f), _autoScrollOriginalSpeed(0.0f), -_autoScrollAcceleration(600.0f), +_autoScrollAcceleration(-1000.0f), +_isAutoScrollSpeedAttenuated(false), +_needCheckAutoScrollDestination(false), +_autoScrollDestination(cocos2d::Point::ZERO), _bePressed(false), _slidTime(0.0f), -_moveChildPoint(Point::ZERO), +_moveChildPoint(cocos2d::Point::ZERO), _childFocusCancelOffset(5.0f), +_leftBounceNeeded(false), +_topBounceNeeded(false), +_rightBounceNeeded(false), +_bottomBounceNeeded(false), +_bounceEnabled(false), +_bouncing(false), +_bounceDir(cocos2d::Point::ZERO), +_bounceOriginalSpeed(0.0f), +_inertiaScrollEnabled(true), _eventListener(NULL), _eventSelector(NULL) { @@ -73,22 +91,9 @@ UIScrollView* UIScrollView::create() return NULL; } -void UIScrollView::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); - - Layout::removeChild(_innerContainer); - - _children->release(); -} - bool UIScrollView::init() { - if (Layout::init()) + if (UILayout::init()) { setUpdateEnabled(true); setTouchEnabled(true); @@ -101,29 +106,36 @@ bool UIScrollView::init() void UIScrollView::initRenderer() { - Layout::initRenderer(); - _innerContainer = Layout::create(); - Layout::addChild(_innerContainer); + UILayout::initRenderer(); + _innerContainer = UILayout::create(); + UILayout::addChild(_innerContainer); } void UIScrollView::onSizeChanged() { - Layout::onSizeChanged(); + UILayout::onSizeChanged(); _topBoundary = _size.height; _rightBoundary = _size.width; - Size innerSize = _innerContainer->getSize(); + float bounceBoundaryParameterX = _size.width / 3.0f; + float bounceBoundaryParameterY = _size.height / 3.0f; + _bounceTopBoundary = _size.height - bounceBoundaryParameterY; + _bounceBottomBoundary = bounceBoundaryParameterY; + _bounceLeftBoundary = bounceBoundaryParameterX; + _bounceRightBoundary = _size.width - bounceBoundaryParameterX; + cocos2d::Size innerSize = _innerContainer->getSize(); float orginInnerSizeWidth = innerSize.width; float orginInnerSizeHeight = innerSize.height; float innerSizeWidth = MAX(orginInnerSizeWidth, _size.width); float innerSizeHeight = MAX(orginInnerSizeHeight, _size.height); - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); + _innerContainer->setSize(cocos2d::Size(innerSizeWidth, innerSizeHeight)); + _innerContainer->setPosition(cocos2d::Point(0, _size.height - _innerContainer->getSize().height)); } -void UIScrollView::setInnerContainerSize(const Size &size) +void UIScrollView::setInnerContainerSize(const cocos2d::Size &size) { float innerSizeWidth = _size.width; float innerSizeHeight = _size.height; + cocos2d::Size originalInnerSize = _innerContainer->getSize(); if (size.width < _size.width) { CCLOG("Inner width <= scrollview width, it will be force sized!"); @@ -140,11 +152,45 @@ void UIScrollView::setInnerContainerSize(const Size &size) { innerSizeHeight = size.height; } - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); + _innerContainer->setSize(cocos2d::Size(innerSizeWidth, innerSizeHeight)); + + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offset = originalInnerSize.height - newInnerSize.height; + scrollChildren(0.0f, offset); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + if (_innerContainer->getRightInParent() <= _size.width) + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offset = originalInnerSize.width - newInnerSize.width; + scrollChildren(offset, 0.0f); + } + break; + } + case SCROLLVIEW_DIR_BOTH: + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offsetY = originalInnerSize.height - newInnerSize.height; + float offsetX = 0.0f; + if (_innerContainer->getRightInParent() <= _size.width) + { + offsetX = originalInnerSize.width - newInnerSize.width; + } + scrollChildren(offsetX, offsetY); + break; + } + default: + break; + } } -const Size& UIScrollView::getInnerContainerSize() const +const cocos2d::Size& UIScrollView::getInnerContainerSize() const { return _innerContainer->getSize(); } @@ -164,378 +210,1192 @@ bool UIScrollView::removeChild(UIWidget* child) return _innerContainer->removeChild(child); } -Array* UIScrollView::getChildren() +cocos2d::Array* UIScrollView::getChildren() { return _innerContainer->getChildren(); } -void UIScrollView::moveChildren(float offset) +void UIScrollView::moveChildren(float offsetX, float offsetY) { - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - { - _moveChildPoint.x = _innerContainer->getPosition().x; - _moveChildPoint.y = _innerContainer->getPosition().y + offset; - _innerContainer->setPosition(_moveChildPoint); - break; - } - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - { - _moveChildPoint.x = _innerContainer->getPosition().x + offset; - _moveChildPoint.y = _innerContainer->getPosition().y; - _innerContainer->setPosition(_moveChildPoint); - break; - } - default: - break; - } + _moveChildPoint = _innerContainer->getPosition() + cocos2d::Point(offsetX, offsetY); + _innerContainer->setPosition(_moveChildPoint); } void UIScrollView::autoScrollChildren(float dt) { - switch (_direction) + float lastTime = _autoScrollAddUpTime; + _autoScrollAddUpTime += dt; + if (_isAutoScrollSpeedAttenuated) { - case SCROLLVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case SCROLLVIEW_MOVE_DIR_UP: // up - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - case SCROLLVIEW_MOVE_DIR_DOWN: // down - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - default: - break; - } - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) + float nowSpeed = _autoScrollOriginalSpeed + _autoScrollAcceleration * _autoScrollAddUpTime; + if (nowSpeed <= 0.0f) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + else + { + float timeParam = lastTime * 2 + dt; + float offset = (_autoScrollOriginalSpeed + _autoScrollAcceleration * timeParam * 0.5f) * dt; + float offsetX = offset * _autoScrollDir.x; + float offsetY = offset * _autoScrollDir.y; + if (!scrollChildren(offsetX, offsetY)) { - case SCROLLVIEW_MOVE_DIR_LEFT: // left - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case SCROLLVIEW_MOVE_DIR_RIGHT: // right - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; + stopAutoScrollChildren(); + checkNeedBounce(); } - break; - - default: - break; + } + } + else + { + if (_needCheckAutoScrollDestination) + { + float xOffset = _autoScrollDir.x * dt * _autoScrollOriginalSpeed; + float yOffset = _autoScrollDir.y * dt * _autoScrollOriginalSpeed; + bool notDone = checkCustomScrollDestination(&xOffset, &yOffset); + bool scrollCheck = scrollChildren(xOffset, yOffset); + if (!notDone || !scrollCheck) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + } + else + { + if (!scrollChildren(_autoScrollDir.x * dt * _autoScrollOriginalSpeed, _autoScrollDir.y * dt * _autoScrollOriginalSpeed)) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + } } } -void UIScrollView::startAutoScrollChildren(float v) +void UIScrollView::bounceChildren(float dt) { + if (_bounceOriginalSpeed <= 0.0f) + { + stopBounceChildren(); + } + if (!bounceScrollChildren(_bounceDir.x * dt * _bounceOriginalSpeed, _bounceDir.y * dt * _bounceOriginalSpeed)) + { + stopBounceChildren(); + } +} + +bool UIScrollView::checkNeedBounce() +{ + if (!_bounceEnabled) + { + return false; + } + checkBounceBoundary(); + if (_topBounceNeeded || _bottomBounceNeeded || _leftBounceNeeded || _rightBounceNeeded) + { + if (_topBounceNeeded && _leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(0.0f, _size.height) - cocos2d::Point(_innerContainer->getLeftInParent(), _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_topBounceNeeded && _rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, _size.height) - cocos2d::Point(_innerContainer->getRightInParent(), _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded && _leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(_innerContainer->getLeftInParent(), _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded && _rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, 0.0f) - cocos2d::Point(_innerContainer->getRightInParent(), _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_topBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(0.0f, _size.height) - cocos2d::Point(0.0f, _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(0.0f, _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(_innerContainer->getLeftInParent(), 0.0f); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, 0.0f) - cocos2d::Point(_innerContainer->getRightInParent(), 0.0f); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + return true; + } + return false; +} + +void UIScrollView::checkBounceBoundary() +{ + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos > _bottomBoundary) + { + scrollToBottomEvent(); + _bottomBounceNeeded = true; + } + else + { + _bottomBounceNeeded = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos < _topBoundary) + { + scrollToTopEvent(); + _topBounceNeeded = true; + } + else + { + _topBounceNeeded = false; + } + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos < _rightBoundary) + { + scrollToRightEvent(); + _rightBounceNeeded = true; + } + else + { + _rightBounceNeeded = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos > _leftBoundary) + { + scrollToLeftEvent(); + _leftBounceNeeded = true; + } + else + { + _leftBounceNeeded = false; + } +} + +void UIScrollView::startBounceChildren(float v) +{ + _bounceOriginalSpeed = v; + _bouncing = true; +} + +void UIScrollView::stopBounceChildren() +{ + _bouncing = false; + _bounceOriginalSpeed = 0.0f; + _leftBounceNeeded = false; + _rightBounceNeeded = false; + _topBounceNeeded = false; + _bottomBounceNeeded = false; +} + +void UIScrollView::startAutoScrollChildrenWithOriginalSpeed(const cocos2d::Point& dir, float v, bool attenuated, float acceleration) +{ + stopAutoScrollChildren(); + _autoScrollDir = dir; + _isAutoScrollSpeedAttenuated = attenuated; _autoScrollOriginalSpeed = v; _autoScroll = true; + _autoScrollAcceleration = acceleration; +} + +void UIScrollView::startAutoScrollChildrenWithDestination(const cocos2d::Point& des, float time, bool attenuated) +{ + _needCheckAutoScrollDestination = false; + _autoScrollDestination = des; + cocos2d::Point dis = des - _innerContainer->getPosition(); + cocos2d::Point dir = dis.normalize(); + float orSpeed = 0.0f; + float acceleration = -1000.0f; + if (attenuated) + { + acceleration = (-(2 * dis.getLength())) / (time * time); + orSpeed = 2 * dis.getLength() / time; + } + else + { + _needCheckAutoScrollDestination = true; + orSpeed = dis.getLength() / time; + } + startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, attenuated, acceleration); +} + +void UIScrollView::jumpToDestination(const cocos2d::Point &des) +{ + float finalOffsetX = des.x; + float finalOffsetY = des.y; + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + if (des.y <= 0) + { + finalOffsetY = MAX(des.y, _size.height - _innerContainer->getSize().height); + } + break; + case SCROLLVIEW_DIR_HORIZONTAL: + if (des.x <= 0) + { + finalOffsetX = MAX(des.x, _size.width - _innerContainer->getSize().width); + } + break; + case SCROLLVIEW_DIR_BOTH: + if (des.y <= 0) + { + finalOffsetY = MAX(des.y, _size.height - _innerContainer->getSize().height); + } + if (des.x <= 0) + { + finalOffsetX = MAX(des.x, _size.width - _innerContainer->getSize().width); + } + break; + default: + break; + } + _innerContainer->setPosition(cocos2d::Point(finalOffsetX, finalOffsetY)); } void UIScrollView::stopAutoScrollChildren() { _autoScroll = false; _autoScrollOriginalSpeed = 0.0f; + _autoScrollAddUpTime = 0.0f; } -float UIScrollView::getCurAutoScrollDistance(float time) +bool UIScrollView::bounceScrollChildren(float touchOffsetX, float touchOffsetY) { - float dt = time; - _autoScrollOriginalSpeed -= _autoScrollAcceleration*dt; - return _autoScrollOriginalSpeed*dt; + bool scrollenabled = true; + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) //first quadrant //bounce to top-right + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if(touchOffsetX < 0.0f && touchOffsetY > 0.0f) //second quadrant //bounce to top-left + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icLefrPos = _innerContainer->getLeftInParent(); + if (icLefrPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLefrPos; + bounceLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) //third quadrant //bounce to bottom-left + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icLefrPos = _innerContainer->getLeftInParent(); + if (icLefrPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLefrPos; + bounceLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) //forth quadrant //bounce to bottom-right + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // bounce to top + { + float realOffsetY = touchOffsetY; + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(0.0f, realOffsetY); + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) //bounce to bottom + { + float realOffsetY = touchOffsetY; + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(0.0f, realOffsetY); + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) //bounce to right + { + float realOffsetX = touchOffsetX; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, 0.0f); + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) //bounce to left + { + float realOffsetX = touchOffsetX; + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + bounceLeftEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, 0.0f); + } + return scrollenabled; } -bool UIScrollView::scrollChildren(float touchOffset) -{ - float realOffset = touchOffset; - +bool UIScrollView::checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY) +{ + bool scrollenabled = true; switch (_direction) { case SCROLLVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case SCROLLVIEW_MOVE_DIR_UP: // up - { - float icBottomPos = _innerContainer->getBottomInParent(); - if (icBottomPos + touchOffset >= _bottomBoundary) - { - realOffset = _bottomBoundary - icBottomPos; - moveChildren(realOffset); - _bottomEnd = true; - scrollToBottomEvent(); - return false; - } - break; - } - case SCROLLVIEW_MOVE_DIR_DOWN: // down - { - float icTopPos = _innerContainer->getTopInParent(); - if (icTopPos + touchOffset <= _topBoundary) - { - realOffset = _topBoundary - icTopPos; - moveChildren(realOffset); - _topEnd = true; - scrollToTopEvent(); - return false; - } - break; - } - default: - break; - } - moveChildren(realOffset); - _topEnd = false; - _bottomEnd = false; - return true; - break; - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) + { + if (_autoScrollDir.y > 0) { - case SCROLLVIEW_MOVE_DIR_LEFT: // left + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) { - float icRightPos = _innerContainer->getRightInParent(); - if (icRightPos + touchOffset <= _rightBoundary) - { - realOffset = _rightBoundary - icRightPos; - moveChildren(realOffset); - _rightEnd = true; - scrollToRightEvent(); - return false; - } - break; + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; } - case SCROLLVIEW_MOVE_DIR_RIGHT: // right - { - float icLeftPos = _innerContainer->getLeftInParent(); - if (icLeftPos + touchOffset >= _leftBoundary) - { - realOffset = _leftBoundary - icLeftPos; - moveChildren(realOffset); - _leftEnd = true; - scrollToLeftEvent(); - return false; - } - break; - } - default: - break; } - moveChildren(realOffset); - _leftEnd = false; - _rightEnd = false; - return true; break; - + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + if (_autoScrollDir.x > 0) + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + else + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + break; + } + case SCROLLVIEW_DIR_BOTH: + { + if (*touchOffsetX > 0.0f && *touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX > 0.0f && *touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX == 0.0f && *touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + } + else if (*touchOffsetX == 0.0f && *touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX > 0.0f && *touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + break; + } default: break; } - - return false; + return scrollenabled; } -void UIScrollView::scrollToBottom() +bool UIScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { - _moveDirection = SCROLLVIEW_MOVE_DIR_UP; // up - scrollChildren(_innerContainer->getSize().height); + bool scrollenabled = true; + scrollingEvent(); + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + { + float realOffset = touchOffsetY; + if (_bounceEnabled) + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffset = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffset = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffset = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffset = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + moveChildren(0.0f, realOffset); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + float realOffset = touchOffsetX; + if (_bounceEnabled) + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffset = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffset = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + else + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffset = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffset = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + moveChildren(realOffset, 0.0f); + break; + } + case SCROLLVIEW_DIR_BOTH: + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + if (_bounceEnabled) + { + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + } + else + { + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + } + moveChildren(realOffsetX, realOffsetY); + break; + } + default: + break; + } + return scrollenabled; } -void UIScrollView::scrollToTop() +void UIScrollView::scrollToBottom(float time, bool attenuated) { - _moveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down - scrollChildren(-_innerContainer->getSize().height); + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, 0.0f), time, attenuated); +} + +void UIScrollView::scrollToTop(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToLeft(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(0.0f, _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToRight(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToTopLeft(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(0.0f, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToTopRight(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToBottomLeft(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point::ZERO, time, attenuated); +} + +void UIScrollView::scrollToBottomRight(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, 0.0f), time, attenuated); +} + +void UIScrollView::scrollToPercentVertical(float percent, float time, bool attenuated) +{ + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, minY + percent * h / 100.0f), time, attenuated); +} + +void UIScrollView::scrollToPercentHorizontal(float percent, float time, bool attenuated) +{ + float w = _innerContainer->getSize().width - _size.width; + startAutoScrollChildrenWithDestination(cocos2d::Point(-(percent * w / 100.0f), _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToPercentBothDirection(const cocos2d::Point& percent, float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + return; + } + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + float w = _innerContainer->getSize().width - _size.width; + startAutoScrollChildrenWithDestination(cocos2d::Point(-(percent.x * w / 100.0f), minY + percent.y * h / 100.0f), time, attenuated); +} + +void UIScrollView::jumpToBottom() +{ + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, 0.0f)); +} + +void UIScrollView::jumpToTop() +{ + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToLeft() +{ + jumpToDestination(cocos2d::Point(0.0f, _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToRight() +{ + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToTopLeft() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(0.0f, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToTopRight() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToBottomLeft() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point::ZERO); +} + +void UIScrollView::jumpToBottomRight() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, 0.0f)); +} + +void UIScrollView::jumpToPercentVertical(float percent) +{ + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, minY + percent * h / 100.0f)); +} + +void UIScrollView::jumpToPercentHorizontal(float percent) +{ + float w = _innerContainer->getSize().width - _size.width; + jumpToDestination(cocos2d::Point(-(percent * w / 100.0f), _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToPercentBothDirection(const cocos2d::Point& percent) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + return; + } + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + float w = _innerContainer->getSize().width - _size.width; + jumpToDestination(cocos2d::Point(-(percent.x * w / 100.0f), minY + percent.y * h / 100.0f)); } void UIScrollView::startRecordSlidAction() { - if (_children->count() <= 0) + if (_autoScroll) { - return; - } - if (_autoScroll){ stopAutoScrollChildren(); } - _bePressed = true; - _slidTime = 0.0; + if (_bouncing) + { + stopBounceChildren(); + } + _slidTime = 0.0f; } void UIScrollView::endRecordSlidAction() { - if (_children->count() <= 0) + if (!checkNeedBounce() && _inertiaScrollEnabled) { - return; + if (_slidTime <= 0.016f) + { + return; + } + float totalDis = 0.0f; + cocos2d::Point dir; + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + totalDis = _touchEndedPoint.y - _touchBeganPoint.y; + if (totalDis < 0.0f) + { + dir = SCROLLDIR_DOWN; + } + else + { + dir = SCROLLDIR_UP; + } + break; + case SCROLLVIEW_DIR_HORIZONTAL: + totalDis = _touchEndedPoint.x - _touchBeganPoint.x; + if (totalDis < 0.0f) + { + dir = SCROLLDIR_LEFT; + } + else + { + dir = SCROLLDIR_RIGHT; + } + break; + case SCROLLVIEW_DIR_BOTH: + { + cocos2d::Point subVector = _touchEndedPoint - _touchBeganPoint; + totalDis = subVector.getLength(); + dir = subVector.normalize(); + break; + } + default: + break; + } + float orSpeed = MIN(fabs(totalDis)/(_slidTime), AUTOSCROLLMAXSPEED); + startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, true, -1000); + _slidTime = 0.0f; } - if (_slidTime <= 0.016f) - { - return; - } - float totalDis = 0; - totalDis = _touchEndLocation-_touchStartLocation; - float orSpeed = fabs(totalDis)/(_slidTime); - startAutoScrollChildren(orSpeed); - - _bePressed = false; - _slidTime = 0.0; } -void UIScrollView::handlePressLogic(const Point &touchPoint) +void UIScrollView::handlePressLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - _touchMoveStartLocation = nsp.y; - _touchStartLocation = nsp.y; - break; - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - _touchMoveStartLocation = nsp.x; - _touchStartLocation = nsp.x; - break; - default: - break; - } + _touchBeganPoint = _renderer->convertToNodeSpace(touchPoint); + _touchMovingPoint = _touchBeganPoint; startRecordSlidAction(); + _bePressed = true; } -void UIScrollView::handleMoveLogic(const Point &touchPoint) +void UIScrollView::handleMoveLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - float offset = 0.0f; - + _touchMovedPoint = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point delta = _touchMovedPoint - _touchMovingPoint; + _touchMovingPoint = _touchMovedPoint; switch (_direction) { case SCROLLVIEW_DIR_VERTICAL: // vertical - { - float moveY = nsp.y; - offset = moveY - _touchMoveStartLocation; - _touchMoveStartLocation = moveY; - - if (offset < 0.0f) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down - } - else if (offset > 0.0f) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_UP; // up - } - } + { + scrollChildren(0.0f, delta.y); break; - + } case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - { - float moveX = nsp.x; - offset = moveX - _touchMoveStartLocation; - _touchMoveStartLocation = moveX; - - if (offset < 0) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_LEFT; // left - } - else if (offset > 0) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_RIGHT; // right - } - } + { + scrollChildren(delta.x, 0.0f); break; - + } + case SCROLLVIEW_DIR_BOTH: // both + { + scrollChildren(delta.x, delta.y); + break; + } default: break; } - scrollChildren(offset); } -void UIScrollView::handleReleaseLogic(const Point &touchPoint) +void UIScrollView::handleReleaseLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - _touchEndLocation = nsp.y; - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - _touchEndLocation = nsp.x; - break; - - default: - break; - } + _touchEndedPoint = _renderer->convertToNodeSpace(touchPoint); endRecordSlidAction(); + _bePressed = false; } -bool UIScrollView::onTouchBegan(const Point &touchPoint) +bool UIScrollView::onTouchBegan(const cocos2d::Point &touchPoint) { - bool pass = Layout::onTouchBegan(touchPoint); + bool pass = UILayout::onTouchBegan(touchPoint); handlePressLogic(touchPoint); return pass; } -void UIScrollView::onTouchMoved(const Point &touchPoint) +void UIScrollView::onTouchMoved(const cocos2d::Point &touchPoint) { - Layout::onTouchMoved(touchPoint); + UILayout::onTouchMoved(touchPoint); handleMoveLogic(touchPoint); } -void UIScrollView::onTouchEnded(const Point &touchPoint) +void UIScrollView::onTouchEnded(const cocos2d::Point &touchPoint) { - Layout::onTouchEnded(touchPoint); + UILayout::onTouchEnded(touchPoint); handleReleaseLogic(touchPoint); } -void UIScrollView::onTouchCancelled(const Point &touchPoint) +void UIScrollView::onTouchCancelled(const cocos2d::Point &touchPoint) { - Layout::onTouchCancelled(touchPoint); + UILayout::onTouchCancelled(touchPoint); + handleReleaseLogic(touchPoint); } -void UIScrollView::onTouchLongClicked(const Point &touchPoint) +void UIScrollView::onTouchLongClicked(const cocos2d::Point &touchPoint) { } @@ -546,6 +1406,10 @@ void UIScrollView::update(float dt) { autoScrollChildren(dt); } + if (_bouncing) + { + bounceChildren(dt); + } recordSlidTime(dt); } @@ -557,7 +1421,7 @@ void UIScrollView::recordSlidTime(float dt) } } -void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { switch (handleState) { @@ -567,20 +1431,7 @@ void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const case 1: { - float offset = 0; - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - offset = fabs(sender->getTouchStartPos().y - touchPoint.y); - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - offset = fabs(sender->getTouchStartPos().x - touchPoint.x); - break; - - default: - break; - } + float offset = (sender->getTouchStartPos() - touchPoint).getLength(); if (offset > _childFocusCancelOffset) { sender->setFocused(false); @@ -594,11 +1445,12 @@ void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const break; case 3: + handleReleaseLogic(touchPoint); break; } } -void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) +void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint) { interceptTouchEvent(handleState, sender, touchPoint); } @@ -635,7 +1487,47 @@ void UIScrollView::scrollToRightEvent() } } -void UIScrollView::addEventListener(Object *target, SEL_ScrollViewEvent selector) +void UIScrollView::scrollingEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLLING); + } +} + +void UIScrollView::bounceTopEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_TOP); + } +} + +void UIScrollView::bounceBottomEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_BOTTOM); + } +} + +void UIScrollView::bounceLeftEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_LEFT); + } +} + +void UIScrollView::bounceRightEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_RIGHT); + } +} + +void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { _eventListener = target; _eventSelector = selector; @@ -651,17 +1543,27 @@ SCROLLVIEW_DIR UIScrollView::getDirection() return _direction; } -void UIScrollView::setMoveDirection(SCROLLVIEW_MOVE_DIR dir) +void UIScrollView::setBounceEnabled(bool enabled) { - _moveDirection = dir; + _bounceEnabled = enabled; } -SCROLLVIEW_MOVE_DIR UIScrollView::getMoveDirection() +bool UIScrollView::isBounceEnabled() const { - return _moveDirection; + return _bounceEnabled; } -Layout* UIScrollView::getInnerContainer() +void UIScrollView::setInertiaScrollEnabled(bool enabled) +{ + _inertiaScrollEnabled = enabled; +} + +bool UIScrollView::isInertiaScrollEnabled() const +{ + return _inertiaScrollEnabled; +} + +UILayout* UIScrollView::getInnerContainer() { return _innerContainer; } @@ -686,4 +1588,27 @@ const char* UIScrollView::getDescription() const return "ScrollView"; } +UIWidget* UIScrollView::createCloneInstance() +{ + return UIScrollView::create(); +} + +void UIScrollView::copyClonedWidgetChildren(UIWidget* model) +{ + UILayout::copyClonedWidgetChildren(model); +} + +void UIScrollView::copySpecialProperties(UIWidget *widget) +{ + UIScrollView* scrollView = dynamic_cast(widget); + if (scrollView) + { + UILayout::copySpecialProperties(widget); + setInnerContainerSize(scrollView->getInnerContainerSize()); + setDirection(scrollView->_direction); + setBounceEnabled(scrollView->_bounceEnabled); + setInertiaScrollEnabled(scrollView->_inertiaScrollEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 1a6cf31f99..4d762930f8 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -25,7 +25,7 @@ #ifndef __UISCROLLVIEW_H__ #define __UISCROLLVIEW_H__ -#include "gui//Layout.h" +#include "gui/UILayout.h" #include "gui/UIScrollInterface.h" namespace gui { @@ -34,16 +34,8 @@ enum SCROLLVIEW_DIR { SCROLLVIEW_DIR_NONE, SCROLLVIEW_DIR_VERTICAL, - SCROLLVIEW_DIR_HORIZONTAL -}; - -enum SCROLLVIEW_MOVE_DIR -{ - SCROLLVIEW_MOVE_DIR_NONE, - SCROLLVIEW_MOVE_DIR_UP, - SCROLLVIEW_MOVE_DIR_DOWN, - SCROLLVIEW_MOVE_DIR_LEFT, - SCROLLVIEW_MOVE_DIR_RIGHT, + SCROLLVIEW_DIR_HORIZONTAL, + SCROLLVIEW_DIR_BOTH }; typedef enum @@ -52,13 +44,18 @@ typedef enum SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM, SCROLLVIEW_EVENT_SCROLL_TO_LEFT, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT, + SCROLLVIEW_EVENT_SCROLLING, + SCROLLVIEW_EVENT_BOUNCE_TOP, + SCROLLVIEW_EVENT_BOUNCE_BOTTOM, + SCROLLVIEW_EVENT_BOUNCE_LEFT, + SCROLLVIEW_EVENT_BOUNCE_RIGHT }ScrollviewEventType; -typedef void (cocos2d::Object::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); +typedef void (cocos2d::CCObject::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); #define scrollvieweventselector(_SELECTOR) (SEL_ScrollViewEvent)(&_SELECTOR) -class UIScrollView : public Layout , public UIScrollInterface +class UIScrollView : public UILayout , public UIScrollInterface { public: /** @@ -83,7 +80,7 @@ public: * * @param SCROLLVIEW_DIR */ - void setDirection(SCROLLVIEW_DIR dir); + virtual void setDirection(SCROLLVIEW_DIR dir); /** * Gets scroll direction of scrollview. @@ -101,17 +98,117 @@ public: * * @return inner container. */ - Layout* getInnerContainer(); + UILayout* getInnerContainer(); /** * Scroll inner container to bottom boundary of scrollview. */ - void scrollToBottom(); + void scrollToBottom(float time, bool attenuated); /** * Scroll inner container to top boundary of scrollview. */ - void scrollToTop(); + void scrollToTop(float time, bool attenuated); + + /** + * Scroll inner container to left boundary of scrollview. + */ + void scrollToLeft(float time, bool attenuated); + + /** + * Scroll inner container to right boundary of scrollview. + */ + void scrollToRight(float time, bool attenuated); + + /** + * Scroll inner container to top and left boundary of scrollview. + */ + void scrollToTopLeft(float time, bool attenuated); + + /** + * Scroll inner container to top and right boundary of scrollview. + */ + void scrollToTopRight(float time, bool attenuated); + + /** + * Scroll inner container to bottom and left boundary of scrollview. + */ + void scrollToBottomLeft(float time, bool attenuated); + + /** + * Scroll inner container to bottom and right boundary of scrollview. + */ + void scrollToBottomRight(float time, bool attenuated); + + /** + * Scroll inner container to vertical percent position of scrollview. + */ + void scrollToPercentVertical(float percent, float time, bool attenuated); + + /** + * Scroll inner container to horizontal percent position of scrollview. + */ + void scrollToPercentHorizontal(float percent, float time, bool attenuated); + + /** + * Scroll inner container to both direction percent position of scrollview. + */ + void scrollToPercentBothDirection(const cocos2d::Point& percent, float time, bool attenuated); + + /** + * Move inner container to bottom boundary of scrollview. + */ + void jumpToBottom(); + + /** + * Move inner container to top boundary of scrollview. + */ + void jumpToTop(); + + /** + * Move inner container to left boundary of scrollview. + */ + void jumpToLeft(); + + /** + * Move inner container to right boundary of scrollview. + */ + void jumpToRight(); + + /** + * Move inner container to top and left boundary of scrollview. + */ + void jumpToTopLeft(); + + /** + * Move inner container to top and right boundary of scrollview. + */ + void jumpToTopRight(); + + /** + * Move inner container to bottom and left boundary of scrollview. + */ + void jumpToBottomLeft(); + + /** + * Move inner container to bottom and right boundary of scrollview. + */ + void jumpToBottomRight(); + + /** + * Move inner container to vertical percent position of scrollview. + */ + void jumpToPercentVertical(float percent); + + /** + * Move inner container to horizontal percent position of scrollview. + */ + void jumpToPercentHorizontal(float percent); + + /** + * Move inner container to both direction percent position of scrollview. + */ + void jumpToPercentBothDirection(const cocos2d::Point& percent); /** * Changes inner container size of scrollview. @@ -134,7 +231,7 @@ public: /** * Add call back function called scrollview event triggered */ - void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); + void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); //override "addChild" method of widget. virtual bool addChild(UIWidget* widget); @@ -165,6 +262,14 @@ public: virtual void update(float dt); + void setBounceEnabled(bool enabled); + + bool isBounceEnabled() const; + + void setInertiaScrollEnabled(bool enabled); + + bool isInertiaScrollEnabled() const; + /** * Sets LayoutType. * @@ -192,12 +297,20 @@ public: protected: virtual bool init(); virtual void initRenderer(); - void moveChildren(float offset); + void moveChildren(float offsetX, float offsetY); void autoScrollChildren(float dt); - void startAutoScrollChildren(float v); + void bounceChildren(float dt); + void checkBounceBoundary(); + bool checkNeedBounce(); + void startAutoScrollChildrenWithOriginalSpeed(const cocos2d::Point& dir, float v, bool attenuated, float acceleration); + void startAutoScrollChildrenWithDestination(const cocos2d::Point& des, float time, bool attenuated); + void jumpToDestination(const cocos2d::Point& des); void stopAutoScrollChildren(); - float getCurAutoScrollDistance(float time); - virtual bool scrollChildren(float touchOffset); + void startBounceChildren(float v); + void stopBounceChildren(); + bool checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY); + virtual bool scrollChildren(float touchOffsetX, float touchOffsetY); + bool bounceScrollChildren(float touchOffsetX, float touchOffsetY); void startRecordSlidAction(); virtual void endRecordSlidAction(); virtual void handlePressLogic(const cocos2d::Point &touchPoint); @@ -206,48 +319,71 @@ protected: virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); void recordSlidTime(float dt); - //override "releaseResoures" method of widget. - virtual void releaseResoures(); - void scrollToTopEvent(); void scrollToBottomEvent(); void scrollToLeftEvent(); void scrollToRightEvent(); - void setMoveDirection(SCROLLVIEW_MOVE_DIR dir); - SCROLLVIEW_MOVE_DIR getMoveDirection(); + void scrollingEvent(); + void bounceTopEvent(); + void bounceBottomEvent(); + void bounceLeftEvent(); + void bounceRightEvent(); virtual void onSizeChanged(); - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); + virtual void setClippingEnabled(bool able){UILayout::setClippingEnabled(able);}; protected: - Layout* _innerContainer; + UILayout* _innerContainer; SCROLLVIEW_DIR _direction; - SCROLLVIEW_MOVE_DIR _moveDirection; - float _touchStartLocation; - float _touchEndLocation; - float _touchMoveStartLocation; - float _topBoundary;//test - float _bottomBoundary;//test + + cocos2d::Point _touchBeganPoint; + cocos2d::Point _touchMovedPoint; + cocos2d::Point _touchEndedPoint; + cocos2d::Point _touchMovingPoint; + cocos2d::Point _autoScrollDir; + + float _topBoundary; + float _bottomBoundary; float _leftBoundary; float _rightBoundary; - bool _topEnd; - bool _bottomEnd; - bool _leftEnd; - bool _rightEnd; + float _bounceTopBoundary; + float _bounceBottomBoundary; + float _bounceLeftBoundary; + float _bounceRightBoundary; + bool _autoScroll; + float _autoScrollAddUpTime; float _autoScrollOriginalSpeed; float _autoScrollAcceleration; + bool _isAutoScrollSpeedAttenuated; + bool _needCheckAutoScrollDestination; + cocos2d::Point _autoScrollDestination; bool _bePressed; float _slidTime; cocos2d::Point _moveChildPoint; float _childFocusCancelOffset; + bool _leftBounceNeeded; + bool _topBounceNeeded; + bool _rightBounceNeeded; + bool _bottomBounceNeeded; + + bool _bounceEnabled; + bool _bouncing; + cocos2d::Point _bounceDir; + float _bounceOriginalSpeed; + bool _inertiaScrollEnabled; + + + cocos2d::Object* _eventListener; SEL_ScrollViewEvent _eventSelector; - }; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index 425fc581e0..f3c0a90b97 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -25,15 +25,12 @@ #include "gui/UISlider.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" -using namespace cocos2d; -using namespace cocos2d::extension; - namespace gui { UISlider::UISlider(): _barRenderer(NULL), _progressBarRenderer(NULL), -_progressBarTextureSize(Size::ZERO), +_progressBarTextureSize(cocos2d::Size::ZERO), _slidBallNormalRenderer(NULL), _slidBallPressedRenderer(NULL), _slidBallDisabledRenderer(NULL), @@ -47,8 +44,8 @@ _progressBarTextureFile(""), _slidBallNormalTextureFile(""), _slidBallPressedTextureFile(""), _slidBallDisabledTextureFile(""), -_capInsetsBarRenderer(Rect::ZERO), -_capInsetsProgressBarRenderer(Rect::ZERO), +_capInsetsBarRenderer(cocos2d::Rect::ZERO), +_capInsetsProgressBarRenderer(cocos2d::Rect::ZERO), _slidPercentListener(NULL), _slidPercentSelector(NULL), _barTexType(UI_TEX_TYPE_LOCAL), @@ -79,17 +76,17 @@ UISlider* UISlider::create() void UISlider::initRenderer() { UIWidget::initRenderer(); - _barRenderer = CCSprite::create(); - _progressBarRenderer = CCSprite::create(); - _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + _barRenderer = cocos2d::Sprite::create(); + _progressBarRenderer = cocos2d::Sprite::create(); + _progressBarRenderer->setAnchorPoint(cocos2d::Point(0.0f, 0.5f)); _renderer->addChild(_barRenderer, -1); _renderer->addChild(_progressBarRenderer, -1); - _slidBallNormalRenderer = CCSprite::create(); - _slidBallPressedRenderer = CCSprite::create(); + _slidBallNormalRenderer = cocos2d::Sprite::create(); + _slidBallPressedRenderer = cocos2d::Sprite::create(); _slidBallPressedRenderer->setVisible(false); - _slidBallDisabledRenderer = CCSprite::create(); + _slidBallDisabledRenderer = cocos2d::Sprite::create(); _slidBallDisabledRenderer->setVisible(false); - _slidBallRenderer = CCNode::create(); + _slidBallRenderer = cocos2d::Node::create(); _slidBallRenderer->addChild(_slidBallNormalRenderer); _slidBallRenderer->addChild(_slidBallPressedRenderer); _slidBallRenderer->addChild(_slidBallDisabledRenderer); @@ -109,21 +106,21 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->initWithFile(fileName); } else { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->initWithFile(fileName); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); } break; default: @@ -131,13 +128,13 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) } if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } else { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } barRendererScaleChangedWithSize(); } @@ -155,21 +152,21 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->initWithFile(fileName); } else { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->initWithFile(fileName); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); } else { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); } break; default: @@ -177,15 +174,15 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy } if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setColor(getColor()); - dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); + dynamic_cast(_progressBarRenderer)->setColor(getColor()); + dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); } else { - dynamic_cast(_progressBarRenderer)->setColor(getColor()); - dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); + dynamic_cast(_progressBarRenderer)->setColor(getColor()); + dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); } - _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + _progressBarRenderer->setAnchorPoint(cocos2d::Point(0.0f, 0.5f)); _progressBarTextureSize = _progressBarRenderer->getContentSize(); progressBarRendererScaleChangedWithSize(); } @@ -204,13 +201,13 @@ void UISlider::setScale9Enabled(bool able) _progressBarRenderer = NULL; if (_scale9Enabled) { - _barRenderer = Scale9Sprite::create(); - _progressBarRenderer = Scale9Sprite::create(); + _barRenderer = cocos2d::extension::Scale9Sprite::create(); + _progressBarRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _barRenderer = CCSprite::create(); - _progressBarRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); + _progressBarRenderer = cocos2d::Sprite::create(); } loadBarTexture(_textureFile.c_str(), _barTexType); loadProgressBarTexture(_progressBarTextureFile.c_str(), _progressBarTexType); @@ -239,30 +236,30 @@ void UISlider::ignoreContentAdaptWithSize(bool ignore) } } -void UISlider::setCapInsets(const Rect &capInsets) +void UISlider::setCapInsets(const cocos2d::Rect &capInsets) { setCapInsetsBarRenderer(capInsets); setCapInsetProgressBarRebderer(capInsets); } -void UISlider::setCapInsetsBarRenderer(const Rect &capInsets) +void UISlider::setCapInsetsBarRenderer(const cocos2d::Rect &capInsets) { _capInsetsBarRenderer = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_barRenderer)->setCapInsets(capInsets); + dynamic_cast(_barRenderer)->setCapInsets(capInsets); } -void UISlider::setCapInsetProgressBarRebderer(const Rect &capInsets) +void UISlider::setCapInsetProgressBarRebderer(const cocos2d::Rect &capInsets) { _capInsetsProgressBarRenderer = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_progressBarRenderer)->setCapInsets(capInsets); + dynamic_cast(_progressBarRenderer)->setCapInsets(capInsets); } void UISlider::loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType) @@ -353,10 +350,10 @@ void UISlider::setPercent(int percent) } _percent = percent; float dis = _barLength*(percent/100.0f); - _slidBallRenderer->setPosition(Point(-_barLength/2.0f + dis, 0.0f)); + _slidBallRenderer->setPosition(cocos2d::Point(-_barLength/2.0f + dis, 0.0f)); if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setPreferredSize(Size(dis,_progressBarTextureSize.height)); + dynamic_cast(_progressBarRenderer)->setPreferredSize(cocos2d::Size(dis,_progressBarTextureSize.height)); } else { @@ -365,10 +362,10 @@ void UISlider::setPercent(int percent) { case UI_TEX_TYPE_PLIST: { - Sprite* barNode = dynamic_cast(_progressBarRenderer); + cocos2d::Sprite* barNode = dynamic_cast(_progressBarRenderer); if (barNode) { - Point to = barNode->getTextureRect().origin; + cocos2d::Point to = barNode->getTextureRect().origin; x = to.x; y = to.y; } @@ -377,33 +374,33 @@ void UISlider::setPercent(int percent) default: break; } - dynamic_cast(_progressBarRenderer)->setTextureRect(Rect(x, y, _progressBarTextureSize.width * (percent/100.0f), _progressBarTextureSize.height)); + dynamic_cast(_progressBarRenderer)->setTextureRect(cocos2d::Rect(x, y, _progressBarTextureSize.width * (percent/100.0f), _progressBarTextureSize.height)); } } -bool UISlider::onTouchBegan(const Point &touchPoint) +bool UISlider::onTouchBegan(const cocos2d::Point &touchPoint) { bool pass = UIWidget::onTouchBegan(touchPoint); - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); setPercent(getPercentWithBallPos(nsp.x)); percentChangedEvent(); return pass; } -void UISlider::onTouchMoved(const Point &touchPoint) +void UISlider::onTouchMoved(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - _slidBallRenderer->setPosition(Point(nsp.x,0)); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); + _slidBallRenderer->setPosition(cocos2d::Point(nsp.x,0)); setPercent(getPercentWithBallPos(nsp.x)); percentChangedEvent(); } -void UISlider::onTouchEnded(const Point &touchPoint) +void UISlider::onTouchEnded(const cocos2d::Point &touchPoint) { UIWidget::onTouchEnded(touchPoint); } -void UISlider::onTouchCancelled(const Point &touchPoint) +void UISlider::onTouchCancelled(const cocos2d::Point &touchPoint) { UIWidget::onTouchCancelled(touchPoint); } @@ -413,7 +410,7 @@ float UISlider::getPercentWithBallPos(float px) return (((px-(-_barLength/2.0f))/_barLength)*100.0f); } -void UISlider::addEventListener(Object *target, SEL_SlidPercentChangedEvent selector) +void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { _slidPercentListener = target; _slidPercentSelector = selector; @@ -438,12 +435,12 @@ void UISlider::onSizeChanged() progressBarRendererScaleChangedWithSize(); } -const Size& UISlider::getContentSize() const +const cocos2d::Size& UISlider::getContentSize() const { return _barRenderer->getContentSize(); } -Node* UISlider::getVirtualRenderer() +cocos2d::Node* UISlider::getVirtualRenderer() { return _barRenderer; } @@ -462,11 +459,11 @@ void UISlider::barRendererScaleChangedWithSize() _barLength = _size.width; if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setPreferredSize(_size); + dynamic_cast(_barRenderer)->setPreferredSize(_size); } else { - Size btextureSize = _barRenderer->getContentSize(); + cocos2d::Size btextureSize = _barRenderer->getContentSize(); if (btextureSize.width <= 0.0f || btextureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); @@ -487,7 +484,7 @@ void UISlider::progressBarRendererScaleChangedWithSize() { if (!_scale9Enabled) { - Size ptextureSize = _progressBarTextureSize; + cocos2d::Size ptextureSize = _progressBarTextureSize; float pscaleX = _size.width / ptextureSize.width; float pscaleY = _size.height / ptextureSize.height; _progressBarRenderer->setScaleX(pscaleX); @@ -498,11 +495,11 @@ void UISlider::progressBarRendererScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setPreferredSize(_size); + dynamic_cast(_progressBarRenderer)->setPreferredSize(_size); } else { - Size ptextureSize = _progressBarTextureSize; + cocos2d::Size ptextureSize = _progressBarTextureSize; if (ptextureSize.width <= 0.0f || ptextureSize.height <= 0.0f) { _progressBarRenderer->setScale(1.0f); @@ -514,7 +511,7 @@ void UISlider::progressBarRendererScaleChangedWithSize() _progressBarRenderer->setScaleY(pscaleY); } } - _progressBarRenderer->setPosition(Point(-_barLength * 0.5f, 0.0f)); + _progressBarRenderer->setPosition(cocos2d::Point(-_barLength * 0.5f, 0.0f)); setPercent(_percent); } @@ -544,4 +541,25 @@ const char* UISlider::getDescription() const return "Slider"; } +UIWidget* UISlider::createCloneInstance() +{ + return UISlider::create(); +} + +void UISlider::copySpecialProperties(UIWidget *widget) +{ + UISlider* slider = dynamic_cast(widget); + if (slider) + { + _prevIgnoreSize = slider->_prevIgnoreSize; + setScale9Enabled(slider->_scale9Enabled); + loadBarTexture(slider->_textureFile.c_str(), slider->_barTexType); + loadProgressBarTexture(slider->_progressBarTextureFile.c_str(), slider->_progressBarTexType); + loadSlidBallTextureNormal(slider->_slidBallNormalTextureFile.c_str(), slider->_ballNTexType); + loadSlidBallTexturePressed(slider->_slidBallPressedTextureFile.c_str(), slider->_ballPTexType); + loadSlidBallTextureDisabled(slider->_slidBallDisabledTextureFile.c_str(), slider->_ballDTexType); + setPercent(slider->getPercent()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UISlider.h b/cocos/gui/UISlider.h index 0654336600..186af44d45 100644 --- a/cocos/gui/UISlider.h +++ b/cocos/gui/UISlider.h @@ -34,9 +34,13 @@ typedef enum SLIDER_PERCENTCHANGED }SliderEventType; -typedef void (cocos2d::CCObject::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); +typedef void (cocos2d::Object::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); #define sliderpercentchangedselector(_SELECTOR) (SEL_SlidPercentChangedEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ class UISlider : public UIWidget { public: @@ -185,6 +189,7 @@ public: * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual void initRenderer(); float getPercentWithBallPos(float location); @@ -195,6 +200,8 @@ protected: virtual void onSizeChanged(); void barRendererScaleChangedWithSize(); void progressBarRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Node* _barRenderer; cocos2d::Node* _progressBarRenderer; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 4e1365592d..2eabd208b2 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -24,19 +24,17 @@ #include "gui/UITextField.h" - using namespace cocos2d; - namespace gui { UICCTextField::UICCTextField() -: m_bMaxLengthEnabled(false) -, m_nMaxLength(0) -, m_bPasswordEnabled(false) -, m_strPasswordStyleText("*") -, m_bAttachWithIME(false) -, m_bDetachWithIME(false) -, m_bInsertText(false) -, m_bDeleteBackward(false) +: _maxLengthEnabled(false) +, _maxLength(0) +, _passwordEnabled(false) +, _passwordStyleText("*") +, _attachWithIME(false) +, _detachWithIME(false) +, _insertText(false) +, _deleteBackward(false) { } @@ -64,26 +62,26 @@ UICCTextField * UICCTextField::create(const char *placeholder, const char *fontN void UICCTextField::onEnter() { - CCTextFieldTTF::setDelegate(this); + cocos2d::TextFieldTTF::setDelegate(this); } -bool UICCTextField::onTextFieldAttachWithIME(TextFieldTTF *pSender) +bool UICCTextField::onTextFieldAttachWithIME(cocos2d::TextFieldTTF *pSender) { setAttachWithIME(true); return false; } -bool UICCTextField::onTextFieldInsertText(TextFieldTTF *pSender, const char *text, int nLen) +bool UICCTextField::onTextFieldInsertText(cocos2d::TextFieldTTF *pSender, const char *text, int nLen) { if (nLen == 1 && strcmp(text, "\n") == 0) { return false; } setInsertText(true); - if (m_bMaxLengthEnabled) + if (_maxLengthEnabled) { - if (CCTextFieldTTF::getCharCount() >= m_nMaxLength) + if (cocos2d::TextFieldTTF::getCharCount() >= _maxLength) { return true; } @@ -92,13 +90,13 @@ bool UICCTextField::onTextFieldInsertText(TextFieldTTF *pSender, const char *tex return false; } -bool UICCTextField::onTextFieldDeleteBackward(TextFieldTTF *pSender, const char *delText, int nLen) +bool UICCTextField::onTextFieldDeleteBackward(cocos2d::TextFieldTTF *pSender, const char *delText, int nLen) { setDeleteBackward(true); return false; } -bool UICCTextField::onTextFieldDetachWithIME(TextFieldTTF *pSender) +bool UICCTextField::onTextFieldDetachWithIME(cocos2d::TextFieldTTF *pSender) { setDetachWithIME(true); return false; @@ -107,11 +105,11 @@ bool UICCTextField::onTextFieldDetachWithIME(TextFieldTTF *pSender) void UICCTextField::insertText(const char * text, int len) { std::string str_text = text; - int str_len = strlen(CCTextFieldTTF::getString()); + int str_len = strlen(cocos2d::TextFieldTTF::getString()); if (strcmp(text, "\n") != 0) { - if (m_bMaxLengthEnabled) + if (_maxLengthEnabled) { int multiple = 1; char value = text[0]; @@ -120,26 +118,26 @@ void UICCTextField::insertText(const char * text, int len) multiple = 3; } - if (str_len + len > m_nMaxLength * multiple) + if (str_len + len > _maxLength * multiple) { - str_text = str_text.substr(0, m_nMaxLength * multiple); - len = m_nMaxLength * multiple; + str_text = str_text.substr(0, _maxLength * multiple); + len = _maxLength * multiple; /* int mod = str_len % 3; int offset = (mod == 0) ? 0 : (3 - mod); int amount = str_len + offset; - str_text = str_text.substr(0, m_nMaxLength - amount); + str_text = str_text.substr(0, _maxLength - amount); // CCLOG("str_test = %s", str_text.c_str()); */ } } } - CCTextFieldTTF::insertText(str_text.c_str(), len); + cocos2d::TextFieldTTF::insertText(str_text.c_str(), len); // password - if (m_bPasswordEnabled) + if (_passwordEnabled) { - if (CCTextFieldTTF::getCharCount() > 0) + if (cocos2d::TextFieldTTF::getCharCount() > 0) { setPasswordText(_inputText->c_str()); } @@ -148,12 +146,12 @@ void UICCTextField::insertText(const char * text, int len) void UICCTextField::deleteBackward() { - CCTextFieldTTF::deleteBackward(); + cocos2d::TextFieldTTF::deleteBackward(); - if (CCTextFieldTTF::getCharCount() > 0) + if (cocos2d::TextFieldTTF::getCharCount() > 0) { // password - if (m_bPasswordEnabled) + if (_passwordEnabled) { setPasswordText(_inputText->c_str()); } @@ -162,47 +160,47 @@ void UICCTextField::deleteBackward() void UICCTextField::openIME() { - CCTextFieldTTF::attachWithIME(); + cocos2d::TextFieldTTF::attachWithIME(); } void UICCTextField::closeIME() { - CCTextFieldTTF::detachWithIME(); + cocos2d::TextFieldTTF::detachWithIME(); } void UICCTextField::setMaxLengthEnabled(bool enable) { - m_bMaxLengthEnabled = enable; + _maxLengthEnabled = enable; } bool UICCTextField::isMaxLengthEnabled() { - return m_bMaxLengthEnabled; + return _maxLengthEnabled; } void UICCTextField::setMaxLength(int length) { - m_nMaxLength = length; + _maxLength = length; } int UICCTextField::getMaxLength() { - return m_nMaxLength; + return _maxLength; } int UICCTextField::getCharCount() { - return CCTextFieldTTF::getCharCount(); + return cocos2d::TextFieldTTF::getCharCount(); } void UICCTextField::setPasswordEnabled(bool enable) { - m_bPasswordEnabled = enable; + _passwordEnabled = enable; } bool UICCTextField::isPasswordEnabled() { - return m_bPasswordEnabled; + return _passwordEnabled; } void UICCTextField::setPasswordStyleText(const char* styleText) @@ -216,7 +214,7 @@ void UICCTextField::setPasswordStyleText(const char* styleText) { return; } - m_strPasswordStyleText = styleText; + _passwordStyleText = styleText; } void UICCTextField::setPasswordText(const char *text) @@ -224,49 +222,49 @@ void UICCTextField::setPasswordText(const char *text) std::string tempStr; for (size_t i = 0; i < strlen(text); ++i) { - tempStr.append(m_strPasswordStyleText); + tempStr.append(_passwordStyleText); } - CCLabelTTF::setString(tempStr.c_str()); + cocos2d::LabelTTF::setString(tempStr.c_str()); } void UICCTextField::setAttachWithIME(bool attach) { - m_bAttachWithIME = attach; + _attachWithIME = attach; } bool UICCTextField::getAttachWithIME() { - return m_bAttachWithIME; + return _attachWithIME; } void UICCTextField::setDetachWithIME(bool detach) { - m_bDetachWithIME = detach; + _detachWithIME = detach; } bool UICCTextField::getDetachWithIME() { - return m_bDetachWithIME; + return _detachWithIME; } void UICCTextField::setInsertText(bool insert) { - m_bInsertText = insert; + _insertText = insert; } bool UICCTextField::getInsertText() { - return m_bInsertText; + return _insertText; } void UICCTextField::setDeleteBackward(bool deleteBackward) { - m_bDeleteBackward = deleteBackward; + _deleteBackward = deleteBackward; } bool UICCTextField::getDeleteBackward() { - return m_bDeleteBackward; + return _deleteBackward; } @@ -278,7 +276,8 @@ _touchWidth(0.0f), _touchHeight(0.0f), _useTouchArea(false), _eventListener(NULL), -_eventSelector(NULL) +_eventSelector(NULL), +_passwordStyleText("") { } @@ -315,7 +314,7 @@ void UITextField::initRenderer() _renderer->addChild(_textFieldRenderer); } -void UITextField::setTouchSize(const Size &size) +void UITextField::setTouchSize(const cocos2d::Size &size) { _useTouchArea = true; _touchWidth = size.width; @@ -361,7 +360,7 @@ const char* UITextField::getStringValue() return _textFieldRenderer->getString(); } -bool UITextField::onTouchBegan(const Point &touchPoint) +bool UITextField::onTouchBegan(const cocos2d::Point &touchPoint) { bool pass = UIWidget::onTouchBegan(touchPoint); _textFieldRenderer->attachWithIME(); @@ -401,6 +400,8 @@ bool UITextField::isPasswordEnabled() void UITextField::setPasswordStyleText(const char *styleText) { _textFieldRenderer->setPasswordStyleText(styleText); + + _passwordStyleText = styleText; } void UITextField::update(float dt) @@ -489,7 +490,7 @@ void UITextField::insertTextEvent() { if (_eventListener && _eventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INDERT_TEXT); + (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INSERT_TEXT); } } @@ -501,19 +502,19 @@ void UITextField::deleteBackwardEvent() } } -void UITextField::addEventListener(Object *target, SEL_TextFieldEvent selecor) +void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { _eventListener = target; _eventSelector = selecor; } -void UITextField::setAnchorPoint(const Point &pt) +void UITextField::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _textFieldRenderer->setAnchorPoint(pt); } -void UITextField::setColor(const Color3B &color) +void UITextField::setColor(const cocos2d::Color3B &color) { UIWidget::setColor(color); _textFieldRenderer->setColor(color); @@ -539,7 +540,7 @@ void UITextField::textfieldRendererScaleChangedWithSize() } else { - Size textureSize = getContentSize(); + cocos2d::Size textureSize = getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _textFieldRenderer->setScale(1.0f); @@ -552,12 +553,12 @@ void UITextField::textfieldRendererScaleChangedWithSize() } } -const Size& UITextField::getContentSize() const +const cocos2d::Size& UITextField::getContentSize() const { return _textFieldRenderer->getContentSize(); } -Node* UITextField::getVirtualRenderer() +cocos2d::Node* UITextField::getVirtualRenderer() { return _textFieldRenderer; } @@ -567,4 +568,34 @@ const char* UITextField::getDescription() const return "TextField"; } +void UITextField::attachWithIME() +{ + _textFieldRenderer->attachWithIME(); +} + +UIWidget* UITextField::createCloneInstance() +{ + return UITextField::create(); +} + +void UITextField::copySpecialProperties(UIWidget *widget) +{ + UITextField* textField = dynamic_cast(widget); + if (textField) + { + setText(textField->_textFieldRenderer->getString()); + setPlaceHolder(textField->getStringValue()); + setFontSize(textField->_textFieldRenderer->getFontSize()); + setFontName(textField->_textFieldRenderer->getFontName()); + setMaxLengthEnabled(textField->isMaxLengthEnabled()); + setMaxLength(textField->getMaxLength()); + setPasswordEnabled(textField->isPasswordEnabled()); + setPasswordStyleText(textField->_passwordStyleText.c_str()); + setAttachWithIME(textField->getAttachWithIME()); + setDetachWithIME(textField->getDetachWithIME()); + setInsertText(textField->getInsertText()); + setDeleteBackward(textField->getDeleteBackward()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index 31b7052443..ac5641114f 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -30,6 +30,10 @@ namespace gui { +/** + * @js NA + * @lua NA + */ class UICCTextField: public cocos2d::TextFieldTTF, public cocos2d::TextFieldDelegate { public: @@ -70,32 +74,32 @@ public: bool getInsertText(); void setDeleteBackward(bool deleteBackward); bool getDeleteBackward(); - - protected: - bool m_bMaxLengthEnabled; - int m_nMaxLength; - bool m_bPasswordEnabled; - std::string m_strPasswordStyleText; - bool m_bAttachWithIME; - bool m_bDetachWithIME; - bool m_bInsertText; - bool m_bDeleteBackward; + bool _maxLengthEnabled; + int _maxLength; + bool _passwordEnabled; + std::string _passwordStyleText; + bool _attachWithIME; + bool _detachWithIME; + bool _insertText; + bool _deleteBackward; }; - typedef enum { TEXTFIELD_EVENT_ATTACH_WITH_IME, TEXTFIELD_EVENT_DETACH_WITH_IME, - TEXTFIELD_EVENT_INDERT_TEXT, + TEXTFIELD_EVENT_INSERT_TEXT, TEXTFIELD_EVENT_DELETE_BACKWARD, }TextFiledEventType; typedef void (cocos2d::Object::*SEL_TextFieldEvent)(cocos2d::Object*, TextFiledEventType); #define textfieldeventselector(_SELECTOR) (SEL_TextFieldEvent)(&_SELECTOR) -//class UITextField : public UIWidget +/** class UITextField : public UIWidget +* @js NA +* @lua NA +*/ class UITextField : public UIWidget { public: @@ -129,22 +133,19 @@ public: bool getDeleteBackward(); void setDeleteBackward(bool deleteBackward); void addEventListener(cocos2d::Object* target, SEL_TextFieldEvent selecor); + virtual void setAnchorPoint(const cocos2d::Point &pt); virtual void setColor(const cocos2d::Color3B &color); virtual void setOpacity(int opacity); + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; - /*compatibel*/ - /** - * These methods will be removed - */ - void setMaxLengthEnable(bool is){setMaxLengthEnabled(is);}; - void setPasswordEnable(bool is){setPasswordEnabled(is);}; - /************/ + virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); + void attachWithIME(); protected: // event void attachWithIMEEvent(); @@ -153,9 +154,11 @@ protected: void deleteBackwardEvent(); virtual void onSizeChanged(); void textfieldRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: UICCTextField* _textFieldRenderer; - + float _touchWidth; float _touchHeight; bool _useTouchArea; @@ -163,6 +166,7 @@ protected: cocos2d::Object* _eventListener; SEL_TextFieldEvent _eventSelector; + std::string _passwordStyleText; }; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index ea9651582b..00ee50680c 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -24,11 +24,9 @@ #include "gui/UIWidget.h" #include "gui/UILayer.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIHelper.h" - using namespace cocos2d; - namespace gui { #define DYNAMIC_CAST_CCBLENDPROTOCOL dynamic_cast(_renderer) @@ -45,31 +43,31 @@ _touchEnabled(false), _touchPassedEnabled(false), _focus(false), _widgetZOrder(0), -_anchorPoint(Point(0.5f, 0.5f)), +_anchorPoint(cocos2d::Point(0.5f, 0.5f)), _widgetParent(NULL), _brightStyle(BRIGHT_NONE), _updateEnabled(false), _renderer(NULL), -_touchStartPos(Point::ZERO), -_touchMovePos(Point::ZERO), -_touchEndPos(Point::ZERO), +_touchStartPos(cocos2d::Point::ZERO), +_touchMovePos(cocos2d::Point::ZERO), +_touchEndPos(cocos2d::Point::ZERO), _touchEventListener(NULL), _touchEventSelector(NULL), _widgetTag(-1), _name("default"), _widgetType(WidgetTypeWidget), _actionTag(0), -_size(Size::ZERO), -_customSize(Size::ZERO), -_layoutParameter(NULL), +_size(cocos2d::Size::ZERO), +_customSize(cocos2d::Size::ZERO), +_layoutParameterDictionary(NULL), _ignoreSize(false), _children(NULL), _affectByClipping(false), _scheduler(NULL), _sizeType(SIZE_ABSOLUTE), -_sizePercent(Point::ZERO), +_sizePercent(cocos2d::Point::ZERO), _positionType(POSITION_ABSOLUTE), -_positionPercent(Point::ZERO), +_positionPercent(cocos2d::Point::ZERO), _isRunning(false) { @@ -79,7 +77,8 @@ UIWidget::~UIWidget() { releaseResoures(); setParent(NULL); - CC_SAFE_RELEASE_NULL(_layoutParameter); + _layoutParameterDictionary->removeAllObjects(); + CC_SAFE_RELEASE(_layoutParameterDictionary); CC_SAFE_RELEASE(_scheduler); } @@ -97,12 +96,14 @@ UIWidget* UIWidget::create() bool UIWidget::init() { - _children = Array::create(); + _children = cocos2d::Array::create(); _children->retain(); + _layoutParameterDictionary = cocos2d::Dictionary::create(); + CC_SAFE_RETAIN(_layoutParameterDictionary); initRenderer(); _renderer->retain(); _renderer->setZOrder(_widgetZOrder); - RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; if (renderRGBA) { renderRGBA->setCascadeColorEnabled(true); @@ -110,14 +111,13 @@ bool UIWidget::init() } setBright(true); ignoreContentAdaptWithSize(true); - _scheduler = Director::getInstance()->getScheduler(); + _scheduler = cocos2d::Director::getInstance()->getScheduler(); CC_SAFE_RETAIN(_scheduler); return true; } void UIWidget::releaseResoures() { - setUpdateEnabled(false); removeAllChildren(); _children->release(); _renderer->removeAllChildrenWithCleanup(true); @@ -157,7 +157,7 @@ bool UIWidget::addChild(UIWidget *child) else { bool seekSucceed = false; - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; for (int i=childrenCount-1; i>=0; --i) { UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); @@ -203,7 +203,7 @@ bool UIWidget::removeChild(UIWidget *child) { child->onExit(); } - child->disableUpdate(); + child->setUpdateEnabled(false); child->setParent(NULL); _renderer->removeChild(child->getRenderer()); _children->removeObject(child); @@ -246,7 +246,7 @@ void UIWidget::reorderChild(UIWidget* child) else { bool seekSucceed = false; - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; for (int i=childrenCount-1; i>=0; --i) { UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); @@ -274,21 +274,6 @@ void UIWidget::reorderChild(UIWidget* child) CC_SAFE_RELEASE(child); } -void UIWidget::disableUpdate() -{ - if (_scheduler) - { - _scheduler->unscheduleUpdateForTarget(this); - } - int childrenCount = _children->data->num; - ccArray* arrayChildren = _children->data; - for (int i=0; iarr[i]); - child->disableUpdate(); - } -} - void UIWidget::setEnabled(bool enabled) { _enabled = enabled; @@ -299,9 +284,9 @@ void UIWidget::setEnabled(bool enabled) } else { - dynamic_cast(_renderer)->setEnabled(enabled); + dynamic_cast(_renderer)->setEnabled(enabled); } - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; int childrenCount = arrayChildren->num; for (int i = 0; i < childrenCount; i++) { @@ -312,15 +297,15 @@ void UIWidget::setEnabled(bool enabled) UIWidget* UIWidget::getChildByName(const char *name) { - return CCUIHELPER->seekWidgetByName(this, name); + return UIHelper::seekWidgetByName(this, name); } UIWidget* UIWidget::getChildByTag(int tag) { - return CCUIHELPER->seekWidgetByTag(this, tag); + return UIHelper::seekWidgetByTag(this, tag); } -Array* UIWidget::getChildren() +cocos2d::Array* UIWidget::getChildren() { return _children; } @@ -330,7 +315,7 @@ void UIWidget::initRenderer() _renderer = GUIRenderer::create(); } -void UIWidget::setSize(const Size &size) +void UIWidget::setSize(const cocos2d::Size &size) { _customSize = size; if (_ignoreSize) @@ -343,19 +328,19 @@ void UIWidget::setSize(const Size &size) } if (_isRunning) { - _sizePercent = (_widgetParent == NULL) ? Point::ZERO : Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); + _sizePercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); } onSizeChanged(); } -void UIWidget::setSizePercent(const Point &percent) +void UIWidget::setSizePercent(const cocos2d::Point &percent) { _sizePercent = percent; if (!_isRunning) { return; } - Size cSize = (_widgetParent == NULL) ? Size::ZERO : Size(_widgetParent->getSize().width * percent.x , _widgetParent->getSize().height * percent.y); + cocos2d::Size cSize = (_widgetParent == NULL) ? cocos2d::Size::ZERO : cocos2d::Size(_widgetParent->getSize().width * percent.x , _widgetParent->getSize().height * percent.y); if (_ignoreSize) { _size = getContentSize(); @@ -381,11 +366,11 @@ void UIWidget::updateSizeAndPosition() { _size = _customSize; } - _sizePercent = (_widgetParent == NULL) ? Point::ZERO : Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); + _sizePercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); break; case SIZE_PERCENT: { - Size cSize = (_widgetParent == NULL) ? Size::ZERO : Size(_widgetParent->getSize().width * _sizePercent.x , _widgetParent->getSize().height * _sizePercent.y); + cocos2d::Size cSize = (_widgetParent == NULL) ? cocos2d::Size::ZERO : cocos2d::Size(_widgetParent->getSize().width * _sizePercent.x , _widgetParent->getSize().height * _sizePercent.y); if (_ignoreSize) { _size = getContentSize(); @@ -401,16 +386,16 @@ void UIWidget::updateSizeAndPosition() break; } onSizeChanged(); - Point absPos = getPosition(); + cocos2d::Point absPos = getPosition(); switch (_positionType) { case POSITION_ABSOLUTE: - _positionPercent = (_widgetParent == NULL) ? Point::ZERO : Point(absPos.x / _widgetParent->getSize().width, absPos.y / _widgetParent->getSize().height); + _positionPercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(absPos.x / _widgetParent->getSize().width, absPos.y / _widgetParent->getSize().height); break; case POSITION_PERCENT: { - Size parentSize = _widgetParent->getSize(); - absPos = Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); + cocos2d::Size parentSize = _widgetParent->getSize(); + absPos = cocos2d::Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); } break; default: @@ -434,7 +419,7 @@ void UIWidget::ignoreContentAdaptWithSize(bool ignore) _ignoreSize = ignore; if (_ignoreSize) { - Size s = getContentSize(); + cocos2d::Size s = getContentSize(); _size = s; } else @@ -449,27 +434,27 @@ bool UIWidget::isIgnoreContentAdaptWithSize() const return _ignoreSize; } -const Size& UIWidget::getSize() const +const cocos2d::Size& UIWidget::getSize() const { return _size; } -const Point& UIWidget::getSizePercent() const +const cocos2d::Point& UIWidget::getSizePercent() const { return _sizePercent; } -Point UIWidget::getWorldPosition() +cocos2d::Point UIWidget::getWorldPosition() { - return _renderer->convertToWorldSpace(Point::ZERO); + return _renderer->convertToWorldSpace(cocos2d::Point::ZERO); } -Point UIWidget::convertToWorldSpace(const Point& pt) +cocos2d::Point UIWidget::convertToWorldSpace(const cocos2d::Point& pt) { return _renderer->convertToWorldSpace(pt); } -Node* UIWidget::getVirtualRenderer() +cocos2d::Node* UIWidget::getVirtualRenderer() { return _renderer; } @@ -479,7 +464,7 @@ void UIWidget::onSizeChanged() } -const Size& UIWidget::getContentSize() const +const cocos2d::Size& UIWidget::getContentSize() const { return _size; } @@ -511,6 +496,10 @@ bool UIWidget::isTouchEnabled() const void UIWidget::setUpdateEnabled(bool enable) { + if (enable == _updateEnabled) + { + return; + } _updateEnabled = enable; if (enable) { @@ -616,7 +605,7 @@ void UIWidget::didNotSelectSelf() } -bool UIWidget::onTouchBegan(const Point &touchPoint) +bool UIWidget::onTouchBegan(const cocos2d::Point &touchPoint) { setFocused(true); _touchStartPos.x = touchPoint.x; @@ -629,7 +618,7 @@ bool UIWidget::onTouchBegan(const Point &touchPoint) return _touchPassedEnabled; } -void UIWidget::onTouchMoved(const Point &touchPoint) +void UIWidget::onTouchMoved(const cocos2d::Point &touchPoint) { _touchMovePos.x = touchPoint.x; _touchMovePos.y = touchPoint.y; @@ -641,7 +630,7 @@ void UIWidget::onTouchMoved(const Point &touchPoint) moveEvent(); } -void UIWidget::onTouchEnded(const Point &touchPoint) +void UIWidget::onTouchEnded(const cocos2d::Point &touchPoint) { _touchEndPos.x = touchPoint.x; _touchEndPos.y = touchPoint.y; @@ -661,13 +650,13 @@ void UIWidget::onTouchEnded(const Point &touchPoint) } } -void UIWidget::onTouchCancelled(const Point &touchPoint) +void UIWidget::onTouchCancelled(const cocos2d::Point &touchPoint) { setFocused(false); cancelUpEvent(); } -void UIWidget::onTouchLongClicked(const Point &touchPoint) +void UIWidget::onTouchLongClicked(const cocos2d::Point &touchPoint) { longClickEvent(); } @@ -709,31 +698,31 @@ void UIWidget::longClickEvent() } -void UIWidget::addTouchEventListener(Object *target, SEL_TouchEvent selector) +void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { _touchEventListener = target; _touchEventSelector = selector; } -Node* UIWidget::getRenderer() +cocos2d::Node* UIWidget::getRenderer() { return _renderer; } -void UIWidget::addRenderer(Node* renderer, int zOrder) +void UIWidget::addRenderer(cocos2d::Node* renderer, int zOrder) { _renderer->addChild(renderer, zOrder); } -void UIWidget::removeRenderer(Node* renderer, bool cleanup) +void UIWidget::removeRenderer(cocos2d::Node* renderer, bool cleanup) { _renderer->removeChild(renderer,cleanup); } -bool UIWidget::hitTest(const Point &pt) +bool UIWidget::hitTest(const cocos2d::Point &pt) { - Point nsp = _renderer->convertToNodeSpace(pt); - Rect bb = Rect(-_size.width * _anchorPoint.x, -_size.height * _anchorPoint.y, _size.width, _size.height); + cocos2d::Point nsp = _renderer->convertToNodeSpace(pt); + cocos2d::Rect bb = cocos2d::Rect(-_size.width * _anchorPoint.x, -_size.height * _anchorPoint.y, _size.width, _size.height); if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) { return true; @@ -741,14 +730,14 @@ bool UIWidget::hitTest(const Point &pt) return false; } -bool UIWidget::clippingParentAreaContainPoint(const Point &pt) +bool UIWidget::clippingParentAreaContainPoint(const cocos2d::Point &pt) { _affectByClipping = false; UIWidget* parent = getParent(); UIWidget* clippingParent = NULL; while (parent) { - Layout* layoutParent = dynamic_cast(parent); + UILayout* layoutParent = dynamic_cast(parent); if (layoutParent) { if (layoutParent->isClippingEnabled()) @@ -783,7 +772,7 @@ bool UIWidget::clippingParentAreaContainPoint(const Point &pt) return true; } -void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) +void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { if (_widgetParent) { @@ -791,27 +780,27 @@ void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &to } } -void UIWidget::setPosition(const Point &pos) +void UIWidget::setPosition(const cocos2d::Point &pos) { if (_isRunning) { - _positionPercent = (_widgetParent == NULL) ? Point::ZERO : Point(pos.x / _widgetParent->getSize().width, pos.y / _widgetParent->getSize().height); + _positionPercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(pos.x / _widgetParent->getSize().width, pos.y / _widgetParent->getSize().height); } _renderer->setPosition(pos); } -void UIWidget::setPositionPercent(const Point &percent) +void UIWidget::setPositionPercent(const cocos2d::Point &percent) { _positionPercent = percent; if (_isRunning) { - Size parentSize = _widgetParent->getSize(); - Point absPos = Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); + cocos2d::Size parentSize = _widgetParent->getSize(); + cocos2d::Point absPos = cocos2d::Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); _renderer->setPosition(absPos); } } -void UIWidget::setAnchorPoint(const Point &pt) +void UIWidget::setAnchorPoint(const cocos2d::Point &pt) { _anchorPoint = pt; _renderer->setAnchorPoint(pt); @@ -822,12 +811,12 @@ void UIWidget::updateAnchorPoint() setAnchorPoint(_anchorPoint); } -const Point& UIWidget::getPosition() +const cocos2d::Point& UIWidget::getPosition() { return _renderer->getPosition(); } -const Point& UIWidget::getPositionPercent() +const cocos2d::Point& UIWidget::getPositionPercent() { return _positionPercent; } @@ -842,7 +831,7 @@ PositionType UIWidget::getPositionType() const return _positionType; } -const Point& UIWidget::getAnchorPoint() +const cocos2d::Point& UIWidget::getAnchorPoint() { return _anchorPoint; } @@ -930,36 +919,12 @@ bool UIWidget::isEnabled() const float UIWidget::getLeftInParent() { - float leftPos = 0.0f; - switch (_widgetType) - { - case WidgetTypeWidget: - leftPos = getPosition().x - getAnchorPoint().x * _size.width; - break; - case WidgetTypeContainer: - leftPos = getPosition().x; - break; - default: - break; - } - return leftPos; + return getPosition().x - getAnchorPoint().x * _size.width;; } float UIWidget::getBottomInParent() { - float bottomPos = 0.0f; - switch (_widgetType) - { - case WidgetTypeWidget: - bottomPos = getPosition().y - getAnchorPoint().y * _size.height; - break; - case WidgetTypeContainer: - bottomPos = getPosition().y; - break; - default: - break; - } - return bottomPos; + return getPosition().y - getAnchorPoint().y * _size.height;; } float UIWidget::getRightInParent() @@ -982,17 +947,17 @@ void UIWidget::setParent(UIWidget* parent) _widgetParent = parent; } -Action* UIWidget::runAction(Action *action) +cocos2d::Action* UIWidget::runAction(cocos2d::Action *action) { return _renderer->runAction(action); } -void UIWidget::setActionManager(ActionManager *actionManager) +void UIWidget::setActionManager(cocos2d::ActionManager *actionManager) { _renderer->setActionManager(actionManager); } -ActionManager* UIWidget::getActionManager() +cocos2d::ActionManager* UIWidget::getActionManager() { return _renderer->getActionManager(); } @@ -1002,7 +967,7 @@ void UIWidget::stopAllActions() _renderer->stopAllActions(); } -void UIWidget::stopAction(Action *action) +void UIWidget::stopAction(cocos2d::Action *action) { _renderer->stopAction(action); } @@ -1012,33 +977,33 @@ void UIWidget::stopActionByTag(int tag) _renderer->stopActionByTag(tag); } -Action* UIWidget::getActionByTag(int tag) +cocos2d::Action* UIWidget::getActionByTag(int tag) { return _renderer->getActionByTag(tag); } -void UIWidget::setColor(const Color3B &color) +void UIWidget::setColor(const cocos2d::Color3B &color) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setColor(color); } } -const Color3B& UIWidget::getColor() +const cocos2d::Color3B& UIWidget::getColor() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->getColor(); } - return Color3B::WHITE; + return cocos2d::Color3B::WHITE; } void UIWidget::setOpacity(int opacity) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setOpacity(opacity); @@ -1047,7 +1012,7 @@ void UIWidget::setOpacity(int opacity) int UIWidget::getOpacity() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->getOpacity(); @@ -1057,7 +1022,7 @@ int UIWidget::getOpacity() bool UIWidget::isCascadeOpacityEnabled() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->isCascadeOpacityEnabled(); @@ -1067,7 +1032,7 @@ bool UIWidget::isCascadeOpacityEnabled() void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setCascadeOpacityEnabled(cascadeOpacityEnabled); @@ -1076,7 +1041,7 @@ void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) bool UIWidget::isCascadeColorEnabled() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->isCascadeColorEnabled(); @@ -1086,33 +1051,33 @@ bool UIWidget::isCascadeColorEnabled() void UIWidget::setCascadeColorEnabled(bool cascadeColorEnabled) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setCascadeColorEnabled(cascadeColorEnabled); } } -void UIWidget::setBlendFunc(BlendFunc blendFunc) +void UIWidget::setBlendFunc(cocos2d::BlendFunc blendFunc) { - BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; + cocos2d::BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; if (blendNode) { blendNode->setBlendFunc(blendFunc); } } -const Point& UIWidget::getTouchStartPos() +const cocos2d::Point& UIWidget::getTouchStartPos() { return _touchStartPos; } -const Point& UIWidget::getTouchMovePos() +const cocos2d::Point& UIWidget::getTouchMovePos() { return _touchMovePos; } -const Point& UIWidget::getTouchEndPos() +const cocos2d::Point& UIWidget::getTouchEndPos() { return _touchEndPos; } @@ -1142,19 +1107,14 @@ WidgetType UIWidget::getWidgetType() const return _widgetType; } -void UIWidget::setLayoutParameter(LayoutParameter *parameter) +void UIWidget::setLayoutParameter(UILayoutParameter *parameter) { - if (_layoutParameter) - { - CC_SAFE_RELEASE_NULL(_layoutParameter); - } - _layoutParameter = parameter; - CC_SAFE_RETAIN(_layoutParameter); + _layoutParameterDictionary->setObject(parameter, parameter->getLayoutType()); } -LayoutParameter* UIWidget::getLayoutParameter() +UILayoutParameter* UIWidget::getLayoutParameter(LayoutParameterType type) { - return _layoutParameter; + return dynamic_cast(_layoutParameterDictionary->objectForKey(type)); } const char* UIWidget::getDescription() const @@ -1162,6 +1122,71 @@ const char* UIWidget::getDescription() const return "Widget"; } +UIWidget* UIWidget::clone() +{ + UIWidget* clonedWidget = createCloneInstance(); + clonedWidget->copyProperties(this); + clonedWidget->copyClonedWidgetChildren(this); + return clonedWidget; +} + +UIWidget* UIWidget::createCloneInstance() +{ + return UIWidget::create(); +} + +void UIWidget::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayWidgetChildren = model->getChildren()->data; + int length = arrayWidgetChildren->num; + for (int i=0; iarr[i]); + addChild(child->clone()); + } +} + +void UIWidget::copySpecialProperties(UIWidget* model) +{ + +} + +void UIWidget::copyProperties(UIWidget *widget) +{ + setEnabled(widget->isEnabled()); + setVisible(widget->isVisible()); + setBright(widget->isBright()); + setTouchEnabled(widget->isTouchEnabled()); + _touchPassedEnabled = false; + setZOrder(widget->getZOrder()); + setUpdateEnabled(widget->isUpdateEnabled()); + setTag(widget->getTag()); + setName(widget->getName()); + setActionTag(widget->getActionTag()); + _ignoreSize = widget->_ignoreSize; + _size = widget->_size; + _customSize = widget->_customSize; + copySpecialProperties(widget); + _sizeType = widget->getSizeType(); + _sizePercent = widget->_sizePercent; + _positionType = widget->_positionType; + _positionPercent = widget->_positionPercent; + setPosition(widget->getPosition()); + setAnchorPoint(widget->getAnchorPoint()); + setScaleX(widget->getScaleX()); + setScaleY(widget->getScaleY()); + setRotation(widget->getRotation()); + setRotationX(widget->getRotationX()); + setRotationY(widget->getRotationY()); + setFlipX(widget->isFlipX()); + setFlipY(widget->isFlipY()); + setColor(widget->getColor()); + setOpacity(widget->getOpacity()); + setCascadeOpacityEnabled(widget->isCascadeOpacityEnabled()); + setCascadeColorEnabled(widget->isCascadeColorEnabled()); + onSizeChanged(); +} + /*temp action*/ void UIWidget::setActionTag(int tag) { @@ -1214,7 +1239,7 @@ void GUIRenderer::visit() { return; } - NodeRGBA::visit(); + cocos2d::NodeRGBA::visit(); } - + } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index ebc7e8a665..d8f35578f4 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -27,9 +27,9 @@ #include "cocos2d.h" #include "gui/UILayoutDefine.h" -#include "gui/LayoutParameter.h" -namespace gui { +#include "gui/UILayoutParameter.h" +namespace gui { typedef enum { @@ -72,11 +72,10 @@ typedef enum typedef void (cocos2d::Object::*SEL_TouchEvent)(cocos2d::Object*,TouchEventType); #define toucheventselector(_SELECTOR) (SEL_TouchEvent)(&_SELECTOR) - -//class UILayer; -/*temp action*/ -class UIActionNode; - +/** +* @js NA +* @lua NA +*/ class UIWidget : public cocos2d::Object { public: @@ -260,12 +259,7 @@ public: * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. */ virtual void removeAllChildren(); - - /** - * Unschedules the "update" method. - */ - void disableUpdate(); - + /** * Reorders a child according to a new z value. * @@ -304,27 +298,27 @@ public: /** * Gets the renderer of widget * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * - * @return a CCNode object + * @return a Node object */ cocos2d::Node* getRenderer(); /** - * Add a CCNode for rendering. + * Add a Node for rendering. * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * * @param renderer A render node * - * @param zOrder Z order for drawing priority. Please refer to CCNode::setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to Node::setZOrder(int) */ void addRenderer(cocos2d::Node* renderer, int zOrder); /** - * Remove a CCNode from widget. + * Remove a Node from widget. * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * * @param renderer A render node which needs to be removed * @@ -359,7 +353,7 @@ public: /** * Changes the position (x,y) of the widget in OpenGL coordinates * - * Usually we use ccp(x,y) to compose Point object. + * Usually we use p(x,y) to compose Point object. * The original point (0,0) is at the left-bottom corner of screen. * * @param position The position (x,y) of the widget in OpenGL coordinates @@ -369,7 +363,7 @@ public: /** * Changes the position (x,y) of the widget in OpenGL coordinates * - * Usually we use ccp(x,y) to compose Point object. + * Usually we use p(x,y) to compose Point object. * The original point (0,0) is at the left-bottom corner of screen. * * @param percent The percent (x,y) of the widget in OpenGL coordinates @@ -809,15 +803,21 @@ public: * @see LayoutParameter * * @param LayoutParameter pointer + * + * @param type Relative or Linear */ - void setLayoutParameter(LayoutParameter* parameter); + void setLayoutParameter(UILayoutParameter* parameter); /** * Gets LayoutParameter of widget. * * @see LayoutParameter + * + * @param type Relative or Linear + * + * @return LayoutParameter */ - LayoutParameter* getLayoutParameter(); + UILayoutParameter* getLayoutParameter(LayoutParameterType type); /** * Ignore the widget size @@ -850,7 +850,7 @@ public: * * For example, a button's Virtual Renderer is it's texture renderer. * - * @return CCNode pointer. + * @return Node pointer. */ virtual cocos2d::Node* getVirtualRenderer(); @@ -871,14 +871,15 @@ public: */ virtual const cocos2d::Size& getContentSize() const; - virtual void onEnter(); - virtual void onExit(); - /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + UIWidget* clone(); + + virtual void onEnter(); + virtual void onExit(); /*temp action*/ void setActionTag(int tag); int getActionTag(); @@ -913,6 +914,10 @@ protected: */ virtual void releaseResoures(); void updateSizeAndPosition(); + void copyProperties(UIWidget* model); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: bool _enabled; ///< Highest control of widget bool _visible; ///< is this widget visible @@ -930,7 +935,7 @@ protected: cocos2d::Point _touchMovePos; ///< touch moved point cocos2d::Point _touchEndPos; ///< touch ended point - cocos2d::Object* _touchEventListener; + Object* _touchEventListener; SEL_TouchEvent _touchEventSelector; @@ -941,7 +946,7 @@ protected: int _actionTag; cocos2d::Size _size; cocos2d::Size _customSize; - LayoutParameter* _layoutParameter; + cocos2d::Dictionary* _layoutParameterDictionary; bool _ignoreSize; cocos2d::Array* _children; bool _affectByClipping; @@ -954,7 +959,10 @@ protected: cocos2d::Point _positionPercent; bool _isRunning; }; - +/** +* @js NA +* @lua NA +*/ class GUIRenderer : public cocos2d::NodeRGBA { public: @@ -969,5 +977,4 @@ protected: }; } - #endif /* defined(__UIWidget__) */ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 1ba28914df..750b562a67 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -19,7 +19,6 @@ CocosGUITestScene::~CocosGUITestScene() { cocostudio::SceneReader::getInstance()->purgeSceneReader(); cocostudio::ActionManagerEx::purgeActionManager(); - gui::UIHelper::purgeUIHelper(); } void CocosGUITestScene::runThisTest() diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp index e80ff2fd01..dacec9ba84 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp @@ -44,78 +44,25 @@ bool UIDragPanelTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - - // Create the dragpanel - UIDragPanel* dragPanel = UIDragPanel::create(); - dragPanel->setTouchEnabled(true); - dragPanel->setBackGroundImageScale9Enabled(true); - dragPanel->setBackGroundImage("cocosgui/scrollviewbg.png"); - dragPanel->setSize(Size(210, 122.5)); - Size backgroundSize = background->getContentSize(); - dragPanel->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - dragPanel->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - dragPanel->getSize().height) / 2)); - dragPanel->addEventListener(this, dragpaneleventselector(UIDragPanelTest::dragPanelEvent)); - - UIImageView* imageView = UIImageView::create(); - imageView->setTouchEnabled(true); - imageView->loadTexture("cocosgui/b11.png"); - dragPanel->addChild(imageView); - - dragPanel->setInnerContainerSize(imageView->getContentSize()); - Size innerSize = dragPanel->getInnerContainerSize(); - imageView->setPosition(Point(innerSize.width / 2, innerSize.height / 2)); - - m_pUiLayer->addWidget(dragPanel); + UIScrollView* sc = UIScrollView::create(); + sc->setBackGroundColor(Color3B::GREEN); + sc->setBackGroundColorType(LAYOUT_COLOR_SOLID); + sc->setDirection(SCROLLVIEW_DIR_BOTH); + sc->setInnerContainerSize(Size(480, 320)); + sc->setSize(Size(100,100)); + sc->setPosition(Point(100,100)); + sc->scrollToPercentBothDirection(Point(50, 50), 1, true); + UIImageView* iv = UIImageView::create(); + iv->loadTexture("cocosgui/Hello.png"); + iv->setPosition(Point(240, 160)); + sc->addChild(iv); + m_pUiLayer->addWidget(sc); return true; } return false; } -void UIDragPanelTest::dragPanelEvent(Object *pSender, DragPanelEventType type) -{ - switch (type) - { - case DRAGPANEL_EVENT_BERTH_LEFTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_LFETTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_LEFT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_TOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_BOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Bottom")->getCString()); - break; - - default: - break; - } -} - // UIDragPanelTest_Bounce UIDragPanelTest_Bounce::UIDragPanelTest_Bounce() : m_pDisplayValueLabel(NULL) @@ -151,76 +98,23 @@ bool UIDragPanelTest_Bounce::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - - // Create the dragpanel - UIDragPanel* dragPanel = UIDragPanel::create(); - dragPanel->setTouchEnabled(true); - dragPanel->setBounceEnable(true); - dragPanel->setBackGroundImageScale9Enabled(true); - dragPanel->setBackGroundImage("cocosgui/green_edit.png"); - dragPanel->setSize(Size(210, 122.5)); - Size backgroundSize = background->getContentSize(); - dragPanel->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - dragPanel->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - dragPanel->getSize().height) / 2)); - dragPanel->addEventListener(this, dragpaneleventselector(UIDragPanelTest_Bounce::dragPanelEvent)); - - UIImageView* imageView = UIImageView::create(); - imageView->setTouchEnabled(true); - imageView->loadTexture("cocosgui/b11.png"); - dragPanel->addChild(imageView); - - dragPanel->setInnerContainerSize(imageView->getContentSize()); - Size innerSize = dragPanel->getInnerContainerSize(); - imageView->setPosition(Point(innerSize.width / 2, innerSize.height / 2)); - - m_pUiLayer->addWidget(dragPanel); - + UIScrollView* sc = UIScrollView::create(); + sc->setBackGroundColor(Color3B::GREEN); + sc->setBackGroundColorType(LAYOUT_COLOR_SOLID); + sc->setBounceEnabled(true); + sc->setDirection(SCROLLVIEW_DIR_BOTH); + sc->setInnerContainerSize(Size(480, 320)); + sc->setSize(Size(100,100)); + sc->setPosition(Point(100,100)); + sc->scrollToPercentBothDirection(Point(50, 50), 1, true); + UIImageView* iv = UIImageView::create(); + iv->loadTexture("cocosgui/Hello.png"); + iv->setPosition(Point(240, 160)); + sc->addChild(iv); + m_pUiLayer->addWidget(sc); return true; } return false; } -void UIDragPanelTest_Bounce::dragPanelEvent(Object *pSender, DragPanelEventType type) -{ - switch (type) - { - case DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_LEFTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_LEFT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_TOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_BOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Bottom")->getCString()); - break; - - default: - break; - } -} diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h index 76f8469154..b8967247f3 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h @@ -33,7 +33,6 @@ public: UIDragPanelTest(); ~UIDragPanelTest(); bool init(); - void dragPanelEvent(Object* pSender, DragPanelEventType type); protected: UI_SCENE_CREATE_FUNC(UIDragPanelTest) @@ -46,7 +45,6 @@ public: UIDragPanelTest_Bounce(); ~UIDragPanelTest_Bounce(); bool init(); - void dragPanelEvent(Object* pSender, DragPanelEventType type); protected: UI_SCENE_CREATE_FUNC(UIDragPanelTest_Bounce) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp index 6681c744ee..c2163e8059 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp @@ -45,54 +45,23 @@ bool UIListViewTest_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - // Create the list view - m_nCount = 0; - m_array = CCArray::create(); - m_array->retain(); - for (int i = 0; i < 20; ++i) + UIListView* lv = UIListView::create(); + UIButton* model = UIButton::create(); + model->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); + lv->setItemModel(model); + + for (int i=0; i<20; i++) { - String* ccstr = String::createWithFormat("object_%d", i); - m_array->addObject(ccstr); + lv->pushBackDefaultItem(); } - - UIListView *listView = UIListView::create(); - listView->setTouchEnabled(true); - listView->setBackGroundImageScale9Enabled(true); - listView->setBackGroundImage("cocosgui/green_edit.png"); - listView->setSize(Size(240, 130)); - Size backgroundSize = background->getContentSize(); - listView->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - listView->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - listView->getSize().height) / 2)); - - float listWidth = listView->getSize().width; - float listHeight = listView->getSize().height; - - for (int i = 0; i < 5; ++i) - { - UIButton* textButton = UIButton::create(); - textButton->setName("TextButton"); - textButton->setTouchEnabled(true); - textButton->loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", ""); - - Layout *layout = Layout::create(); - layout->setName(String::createWithFormat("panel_%i", i)->getCString()); - layout->setSize(Size(textButton->getSize().width, textButton->getSize().height)); - textButton->setPosition(Point(layout->getSize().width / 2, layout->getSize().height / 2)); - layout->addChild(textButton); - - Size panel_size = layout->getSize(); - layout->setPosition(Point((listWidth - panel_size.width) / 2, - (listHeight - (panel_size.height + panel_size.height * 0.25)) - i * (panel_size.height + panel_size.height * 0.25))); - - listView->addChild(layout); - } - listView->addEventListenter(this, listvieweventselector(UIListViewTest_Vertical::listViewEvent)); - listView->initChildWithDataLength(m_array->count()); - m_pUiLayer->addWidget(listView); + lv->setItemsMargin(10); + lv->setGravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL); + lv->setSize(Size(100, 100)); + lv->setBackGroundColorType(LAYOUT_COLOR_SOLID); + lv->setBackGroundColor(Color3B::GREEN); + lv->setPosition(Point(100, 100)); + m_pUiLayer->addWidget(lv); return true; } @@ -100,46 +69,6 @@ bool UIListViewTest_Vertical::init() return false; } -void UIListViewTest_Vertical::listViewEvent(Object *pSender, ListViewEventType type) -{ - switch (type) - { - case LISTVIEW_EVENT_INIT_CHILD: - { - String* ccstr = static_cast(m_array->getObjectAtIndex(m_nCount)); - UIListView* list = dynamic_cast(pSender); - - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - - m_nCount++; - } - break; - - case LISTVIEW_EVENT_UPDATE_CHILD: - { - UIListView* list = dynamic_cast(pSender); - int index = list->getUpdateDataIndex(); - - if (index < 0 || index >= list->getDataLength()) - { - list->setUpdateSuccess(false); - } - - String* ccstr = static_cast(m_array->getObjectAtIndex(index)); - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - list->setUpdateSuccess(true); - } - break; - - default: - break; - } -} - // UIListViewTest_Horizontal UIListViewTest_Horizontal::UIListViewTest_Horizontal() @@ -176,97 +105,26 @@ bool UIListViewTest_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + + UIListView* lv = UIListView::create(); + lv->setDirection(SCROLLVIEW_DIR_HORIZONTAL); + UIButton* model = UIButton::create(); + model->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); + lv->setItemModel(model); - // Create the list view - m_nCount = 0; - m_array = CCArray::create(); - m_array->retain(); - for (int i = 0; i < 20; ++i) + for (int i=0; i<20; i++) { - String* ccstr = String::createWithFormat("object_%d", i); - m_array->addObject(ccstr); + lv->pushBackDefaultItem(); } - - UIListView *listView = UIListView::create(); - listView->setDirection(LISTVIEW_DIR_HORIZONTAL); - listView->setTouchEnabled(true); - listView->setBackGroundImageScale9Enabled(true); - listView->setBackGroundImage("cocosgui/green_edit.png"); - listView->setSize(Size(240, 130)); - Size backgroundSize = background->getContentSize(); - listView->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - listView->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - listView->getSize().height) / 2)); - - float listHeight = listView->getSize().height; - - for (int i = 0; i < 3; ++i) - { - UIButton* textButton = UIButton::create(); - textButton->setName("TextButton"); - textButton->setTouchEnabled(true); - textButton->loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", ""); - - Layout *layout = Layout::create(); - layout->setName(String::createWithFormat("panel_%i", i)->getCString()); - layout->setSize(Size(textButton->getSize().width, textButton->getSize().height)); - textButton->setPosition(Point(layout->getSize().width / 2, layout->getSize().height / 2)); - layout->addChild(textButton); - - Size layout_size = layout->getSize(); - layout->setPosition(Point(0 + (layout_size.width * 0.2) + i * (layout_size.width + layout_size.width * 0.2), - (listHeight - layout_size.height) / 2)); - - listView->addChild(layout); - } - listView->addEventListenter(this, listvieweventselector(UIListViewTest_Horizontal::listViewEvent)); - listView->initChildWithDataLength(m_array->count()); - m_pUiLayer->addWidget(listView); - + lv->setItemsMargin(10); + lv->setGravity(LISTVIEW_GRAVITY_CENTER_VERTICAL); + lv->setSize(Size(100, 100)); + lv->setBackGroundColorType(LAYOUT_COLOR_SOLID); + lv->setBackGroundColor(Color3B::GREEN); + lv->setPosition(Point(100, 100)); + m_pUiLayer->addWidget(lv); return true; } return false; -} - -void UIListViewTest_Horizontal::listViewEvent(Object *pSender, ListViewEventType type) -{ - switch (type) - { - case LISTVIEW_EVENT_INIT_CHILD: - { - String* ccstr = static_cast(m_array->getObjectAtIndex(m_nCount)); - UIListView* list = dynamic_cast(pSender); - - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - - m_nCount++; - } - break; - - case LISTVIEW_EVENT_UPDATE_CHILD: - { - UIListView* list = dynamic_cast(pSender); - int index = list->getUpdateDataIndex(); - - if (index < 0 || index >= list->getDataLength()) - { - list->setUpdateSuccess(false); - } - - String* ccstr = static_cast(m_array->getObjectAtIndex(index)); - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - list->setUpdateSuccess(true); - } - break; - - default: - break; - } -} +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h index b2725e33ee..4dee33553c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h @@ -33,7 +33,6 @@ public: UIListViewTest_Vertical(); ~UIListViewTest_Vertical(); bool init(); - void listViewEvent(Object* pSender, ListViewEventType type); protected: UI_SCENE_CREATE_FUNC(UIListViewTest_Vertical) @@ -49,7 +48,6 @@ public: UIListViewTest_Horizontal(); ~UIListViewTest_Horizontal(); bool init(); - void listViewEvent(Object* pSender, ListViewEventType type); protected: UI_SCENE_CREATE_FUNC(UIListViewTest_Horizontal) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp index 22b97ef9e6..ce5028ae35 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp @@ -44,7 +44,7 @@ bool UIPageViewTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the page view UIPageView* pageView = UIPageView::create(); @@ -58,7 +58,7 @@ bool UIPageViewTest::init() for (int i = 0; i < 3; ++i) { - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setSize(Size(240, 130)); UIImageView* imageView = UIImageView::create(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp index 49674298bc..94dbb02819 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp @@ -34,10 +34,10 @@ bool UIPanelTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setSize(Size(280, 150)); Size backgroundSize = background->getSize(); layout->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + @@ -98,10 +98,10 @@ bool UIPanelTest_Color::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with color render - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundColorType(LAYOUT_COLOR_SOLID); layout->setBackGroundColor(Color3B(128, 128, 128)); layout->setSize(Size(280, 150)); @@ -163,10 +163,10 @@ bool UIPanelTest_Gradient::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with gradient render - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundColorType(LAYOUT_COLOR_GRADIENT); layout->setBackGroundColor(Color3B(64, 64, 64), Color3B(192, 192, 192)); layout->setSize(Size(280, 150)); @@ -228,10 +228,10 @@ bool UIPanelTest_BackGroundImage::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with background image - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setClippingEnabled(true); layout->setBackGroundImage("cocosgui/Hello.png"); layout->setSize(Size(280, 150)); @@ -293,10 +293,10 @@ bool UIPanelTest_BackGroundImage_Scale9::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with background image - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundImageScale9Enabled(true); layout->setBackGroundImage("cocosgui/green_edit.png"); layout->setSize(Size(280, 150)); @@ -358,10 +358,10 @@ bool UIPanelTest_Layout_Linear_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_LINEAR_VERTICAL); layout->setSize(Size(280, 150)); Size backgroundSize = background->getSize(); @@ -377,7 +377,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - LinearLayoutParameter* lp1 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp1 = UILinearLayoutParameter::create(); button->setLayoutParameter(lp1); lp1->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp1->setMargin(UIMargin(0, 5, 0, 10)); @@ -389,7 +389,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - LinearLayoutParameter* lp2 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp2 = UILinearLayoutParameter::create(); textButton->setLayoutParameter(lp2); lp2->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp2->setMargin(UIMargin(0, 10, 0, 10)); @@ -402,7 +402,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - LinearLayoutParameter* lp3 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp3 = UILinearLayoutParameter::create(); button_scale9->setLayoutParameter(lp3); lp3->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp3->setMargin(UIMargin(0, 10, 0, 10)); @@ -441,10 +441,10 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_LINEAR_HORIZONTAL); layout->setClippingEnabled(true); layout->setSize(Size(280, 150)); @@ -460,7 +460,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - LinearLayoutParameter* lp1 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp1 = UILinearLayoutParameter::create(); button->setLayoutParameter(lp1); lp1->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp1->setMargin(UIMargin(0, 10, 0, 10)); @@ -472,7 +472,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - LinearLayoutParameter* lp2 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp2 = UILinearLayoutParameter::create(); textButton->setLayoutParameter(lp2); lp2->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp2->setMargin(UIMargin(0, 10, 0, 10)); @@ -485,7 +485,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - LinearLayoutParameter* lp3 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp3 = UILinearLayoutParameter::create(); button_scale9->setLayoutParameter(lp3); lp3->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp3->setMargin(UIMargin(0, 10, 0, 10)); @@ -524,10 +524,10 @@ bool UIPanelTest_Layout_Relative::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_RELATIVE); layout->setSize(Size(280, 150)); layout->setBackGroundColorType(LAYOUT_COLOR_SOLID); @@ -544,9 +544,9 @@ bool UIPanelTest_Layout_Relative::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - RelativeLayoutParameter* rp1 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp1 = UIRelativeLayoutParameter::create(); button->setLayoutParameter(rp1); - rp1->setAlign(RELATIVE_ALIGN_PARENT_BOTTOM); + rp1->setAlign(RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL); // rp1->setMargin(UIMargin(0, 10, 0, 10)); @@ -556,9 +556,9 @@ bool UIPanelTest_Layout_Relative::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - RelativeLayoutParameter* rp2 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp2 = UIRelativeLayoutParameter::create(); textButton->setLayoutParameter(rp2); - rp2->setAlign(RELATIVE_ALIGN_PARENT_LEFT); + rp2->setAlign(RELATIVE_ALIGN_PARENT_LEFT_BOTTOM); UIButton* button_scale9 = UIButton::create(); @@ -568,9 +568,9 @@ bool UIPanelTest_Layout_Relative::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - RelativeLayoutParameter* rp3 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp3 = UIRelativeLayoutParameter::create(); textButton->setLayoutParameter(rp3); - rp3->setAlign(RELATIVE_ALIGN_PARENT_RIGHT); + rp3->setAlign(RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM); layout->doLayout(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index a57787dfb1..38344c9490 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -3,6 +3,7 @@ #include "UIScene.h" #include "UISceneManager.h" #include "../ExtensionsTest.h" +#include "editor-support/cocostudio/CCSGUIReader.h" using namespace gui; @@ -25,7 +26,7 @@ bool UIScene::init() m_pUiLayer = UILayer::create(); addChild(m_pUiLayer); - m_pWidget = dynamic_cast(CCUIHELPER->createWidgetFromJsonFile("cocosgui/UITest/UITest.json")); + m_pWidget = dynamic_cast(cocostudio::CCSGUIReader::shareReader()->widgetFromJsonFile("cocosgui/UITest/UITest.json")); m_pUiLayer->addWidget(m_pWidget); m_pSceneTitle = dynamic_cast(m_pUiLayer->getWidgetByName("UItest")); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h index bf10ffa76b..720fdd4224 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h @@ -95,7 +95,7 @@ protected: protected: UILayer *m_pUiLayer; - Layout *m_pWidget; + UILayout *m_pWidget; }; #endif /* defined(__TestCpp__UIScene__) */ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp index c7a13fd225..01b3b83278 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp @@ -44,7 +44,7 @@ bool UIScrollViewTest_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the scrollview by vertical UIScrollView* scrollView = UIScrollView::create(); @@ -129,10 +129,11 @@ bool UIScrollViewTest_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the scrollview by horizontal - UIScrollView* scrollView = UIScrollView::create(); + UIScrollView* scrollView = UIScrollView::create(); + scrollView->setBounceEnabled(true); scrollView->setDirection(SCROLLVIEW_DIR_HORIZONTAL); scrollView->setTouchEnabled(true); scrollView->setSize(Size(280, 150)); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp index bba53b0444..c486c5be3a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp @@ -82,7 +82,7 @@ void UITextFieldTest::textFieldEvent(Object *pSender, TextFiledEventType type) } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words")->getCString()); break; @@ -132,7 +132,7 @@ bool UITextFieldTest_MaxLength::init() // Create the textfield UITextField* textField = UITextField::create(); - textField->setMaxLengthEnable(true); + textField->setMaxLengthEnabled(true); textField->setMaxLength(3); textField->setTouchEnabled(true); textField->setFontName(font_UITextFieldTest); @@ -170,7 +170,7 @@ void UITextFieldTest_MaxLength::textFieldEvent(Object *pSender, TextFiledEventTy } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: { UITextField* textField = dynamic_cast(pSender); m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words max length %d", textField->getMaxLength())->getCString()); @@ -226,7 +226,7 @@ bool UITextFieldTest_Password::init() // Create the textfield UITextField* textField = UITextField::create(); - textField->setPasswordEnable(true); + textField->setPasswordEnabled(true); textField->setPasswordStyleText("*"); textField->setTouchEnabled(true); textField->setFontName(font_UITextFieldTest); @@ -264,7 +264,7 @@ void UITextFieldTest_Password::textFieldEvent(Object *pSender, TextFiledEventTyp } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words password")->getCString()); break; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index 0ce946c5a6..f7ddf0c777 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -14,7 +14,6 @@ SceneEditorTestLayer::~SceneEditorTestLayer() ArmatureDataManager::getInstance()->destoryInstance(); SceneReader::getInstance()->purgeSceneReader(); ActionManagerEx::shareManager()->purgeActionManager(); - UIHelper::instance()->purgeUIHelper(); } SceneEditorTestLayer::SceneEditorTestLayer() From 12570b5e8fe3a103bd0f6a801dff17538369eb29 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 16:20:01 +0800 Subject: [PATCH 095/197] temp commit --- cocos/editor-support/cocostudio/CCSGUIReader.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 0f5c597306..d5b10e62b3 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -162,8 +162,8 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "ListView") == 0) { -// widget = UIListView::create(); -// setPropsForListViewFromJsonDictionary(widget, uiOptions); + widget = UIListView::create(); + setPropsForListViewFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "PageView") == 0) { @@ -232,13 +232,14 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) const char* file = DICTOOL->getStringValueFromArray_json(jsonDict, "textures", i); std::string tp = m_strFilePath; tp.append(file); -// CCUIHELPER->addSpriteFrame(tp.c_str()); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); +// UIHelper:: // CCUIHELPER->setFileDesignWidth(winSize.width); // CCUIHELPER->setFileDesignHeight(winSize.height); } From 3ea0d2f12d4881413f99f0939ac053b7c91e237a Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 16:37:30 +0800 Subject: [PATCH 096/197] change override function --- cocos/editor-support/cocostudio/CCSkin.cpp | 16 ++++++++-------- cocos/editor-support/cocostudio/CCSkin.h | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 62710e561d..394dfb48ec 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -83,11 +83,11 @@ Skin::Skin() _skinTransform = AffineTransformIdentity; } -bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) +bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) { - CCAssert(pszSpriteFrameName != nullptr, ""); + CCAssert(spriteFrameName != "", ""); - SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pszSpriteFrameName); + SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); bool ret = true; if (pFrame != nullptr) @@ -96,20 +96,20 @@ bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) } else { - CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", pszSpriteFrameName); + CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.c_str()); ret = false; } - _displayName = pszSpriteFrameName; + _displayName = spriteFrameName; return ret; } -bool Skin::initWithFile(const char *pszFilename) +bool Skin::initWithFile(const std::string& filename) { - bool ret = Sprite::initWithFile(pszFilename); + bool ret = Sprite::initWithFile(filename); - _displayName = pszFilename; + _displayName = filename; return ret; } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 3d937a76bb..e740d1eb01 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,8 +39,8 @@ public: public: Skin(); - virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; - virtual bool initWithFile(const char *pszFilename) override; + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; + virtual bool initWithFile(const std::string& filename) override; void updateArmatureTransform(); void updateTransform() override; From 94896b5b74bfa9e923468a0b3f8f542d1265c5b3 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 17:20:14 +0800 Subject: [PATCH 097/197] Modify mk files --- cocos/gui/Android.mk | 5 ++--- cocos/gui/CMakeLists.txt | 5 ++--- cocos/gui/Makefile | 5 ++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk index 33171c7c1d..17f15efe44 100644 --- a/cocos/gui/Android.mk +++ b/cocos/gui/Android.mk @@ -7,14 +7,13 @@ LOCAL_MODULE_FILENAME := libgui LOCAL_SRC_FILES := UIRootWidget.cpp \ UIWidget.cpp \ -Layout.cpp \ -LayoutParameter.cpp \ +UILayout.cpp \ +UILayoutParameter.cpp \ UILayoutDefine.cpp \ CocosGUI.cpp \ UIHelper.cpp \ UIInputManager.cpp \ UILayer.cpp \ -UIDragPanel.cpp \ UIListView.cpp \ UIPageView.cpp \ UIScrollView.cpp \ diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt index 916e5cf0f2..d4b428f890 100644 --- a/cocos/gui/CMakeLists.txt +++ b/cocos/gui/CMakeLists.txt @@ -1,14 +1,13 @@ set(GUI_SRC UIRootWidget.cpp UIWidget.cpp - Layout.cpp - LayoutParameter.cpp + UILayout.cpp + UILayoutParameter.cpp UILayoutDefine.cpp CocosGUI.cpp UIHelper.cpp UIInputManager.cpp UILayer.cpp - UIDragPanel.cpp UIListView.cpp UIPageView.cpp UIScrollView.cpp diff --git a/cocos/gui/Makefile b/cocos/gui/Makefile index 0e8501cc63..8dcb0cb404 100644 --- a/cocos/gui/Makefile +++ b/cocos/gui/Makefile @@ -6,14 +6,13 @@ INCLUDES = -I../ \ SOURCES = UIRootWidget.cpp \ UIWidget.cpp \ -Layout.cpp \ -LayoutParameter.cpp \ +UILayout.cpp \ +UILayoutParameter.cpp \ UILayoutDefine.cpp \ CocosGUI.cpp \ UIHelper.cpp \ UIInputManager.cpp \ UILayer.cpp \ -UIDragPanel.cpp \ UIListView.cpp \ UIPageView.cpp \ UIScrollView.cpp \ From 8a836dc4771f2ccb1037a769f71768a0382fa12d Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 6 Nov 2013 09:38:34 +0000 Subject: [PATCH 098/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 9b0b068f92..f55eab57aa 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 9b0b068f923249440b8a8c758b1c06d29f6cbdfe +Subproject commit f55eab57aa6b3ff20fd33bea986e4569ebd68c8e From 3deb3b4231eff1868d24961b8c65c39452e27237 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 17:52:03 +0800 Subject: [PATCH 099/197] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index e206d5cea7..93e703edb1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] EventListeners can't be removed sometimes. [FIX] When parsing XML using TinyXML, the data size has to be specified. [FIX] Parameter type: const char* -> const string& + [FIX] Armature: many bug fixed, add more samples, add function to skip some frames when playing animation [NEW] Arm64 support. [NEW] Added Mouse Support For Desktop Platforms. [Android] From 8c0ab2d4895a392593bad1904eb4a111855abf08 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 18:05:02 +0800 Subject: [PATCH 100/197] [ci skip] --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 217779827f..6d84c08926 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ How to start a new game Example: - $ cd cocos2d-x/tools/project-creator - $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp + $ cd cocos2d-x/tools/project-creator + $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp $ cd ../../projects/mygame @@ -97,8 +97,9 @@ $ open samples.xcodeproj * For Linux ``` -$ cd cocos2d-x/build -$ ./make-all-linux-projects.sh +$ cd cocos2d-x +$ cmake CMakeLists.txt +$ make ``` * For Windows From b30494cc4fa906a6995f1ba06b579d592aadc776 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 18:07:03 +0800 Subject: [PATCH 101/197] [ci skip] --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d84c08926..1cfd3a014d 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Build Requirements ------------------ * Mac OS X 10.7+, Xcode 4.6+ -* or Ubuntu 13.04+ +* or Ubuntu 12.10+, CMake 2.6+ * or Windows 7+, VS 2012+ From e765eb1e7a5a9f5cc6b20b12aa3904849ee9c767 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 18:30:09 +0800 Subject: [PATCH 102/197] Test commit --- cocos/editor-support/cocostudio/CCSGUIReader.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index d5b10e62b3..de644e6ec6 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -239,7 +239,6 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); -// UIHelper:: // CCUIHELPER->setFileDesignWidth(winSize.width); // CCUIHELPER->setFileDesignHeight(winSize.height); } From d6d041f561b2677dc600cdb41407c784ba7b2c88 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 19:15:20 +0800 Subject: [PATCH 103/197] issue #3113: [Linux] Adding options for modules. --- CMakeLists.txt | 73 ++++++++++++++++++++++++++++--- cocos/scripting/CMakeLists.txt | 6 +++ external/Box2D/CMakeLists.txt | 6 +++ external/lua/lua/CMakeLists.txt | 8 +++- external/lua/tolua/CMakeLists.txt | 5 +++ samples/CMakeLists.txt | 12 ++++- 6 files changed, 101 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e07f618e27..f75d56a708 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 2.6) -project (Cocos2dxSamples) +project (Cocos2dx) # The version number set(Cocos2dxSamples_VERSION_MAJOR 3) @@ -7,14 +7,45 @@ set(Cocos2dxSamples_VERSION_MINOR 0) include(build/BuildHelpers.CMakeLists.txt) -set(CMAKE_BUILE_TYPE DEBUG) +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(USE_BOX2D "Use box2d for physics library" OFF) +option(DEBUG_MODE "Debug or release?" ON) +option(BUILD_LIBS_LUA "Build lua libraries" ON) +option(BUILD_GUI "Build GUI library" ON) +option(BUILD_NETWORK "Build network library" ON) +option(BUILD_EXTENSIONS "Build extension library" ON) +option(BUILD_EDITOR_SPINE "Build editor support for spine" ON) +option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) +option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) + + +option(BUILD_HelloCpp "Only build HelloCpp sample" ON) +option(BUILD_TestCpp "Only build TestCpp sample" ON) +option(BUILD_HelloLua "Only build HelloLua sample" ON) +option(BUILD_TestLua "Only build TestLua sample" ON) + + +if(DEBUG_MODE) + set(CMAKE_BUILE_TYPE DEBUG) +else(DEBUG_MODE) + set(CMAKE_BUILE_TYPE RELEASE) +endif(DEBUG_MODE) + set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") -add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1) +else(USE_CHIPMUNK) + message(FATAL_ERROR "Must choose a physics library.") +endif(USE_CHIPMUNK) # architecture if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) @@ -58,6 +89,7 @@ link_directories( ${CMAKE_SOURCE_DIR}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} ) + # kazmath add_subdirectory(cocos/math/kazmath) @@ -73,8 +105,6 @@ add_subdirectory(external/unzip) # tinyxml2 library add_subdirectory(external/tinyxml2) -add_subdirectory(external/json) - # audio add_subdirectory(cocos/audio) @@ -84,22 +114,51 @@ add_subdirectory(cocos/base) # cocos 2d library add_subdirectory(cocos/2d) +if(BUILD_GUI) +# gui add_subdirectory(cocos/gui) +endif(BUILD_GUI) +if(BUILD_NETWORK) +# network add_subdirectory(cocos/network) +endif(BUILD_NETWORK) +if(BUILD_EXTENSIONS) +# extensions add_subdirectory(extensions) +endif(BUILD_EXTENSIONS) +## Editor Support + +if(BUILD_EDITOR_SPINE) +# spine add_subdirectory(cocos/editor-support/spine) +endif(BUILD_EDITOR_SPINE) + +if(BUILD_EDITOR_COCOSBUILDER) +# cocosbuilder add_subdirectory(cocos/editor-support/cocosbuilder) +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) +## Scripting +# lua add_subdirectory(external/lua/lua) + +# tolua add_subdirectory(external/lua/tolua) +# luabinding add_subdirectory(cocos/scripting) +endif(BUILD_LIBS_LUA) # build samples add_subdirectory(samples) - diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt index 478ae9a039..612d728162 100644 --- a/cocos/scripting/CMakeLists.txt +++ b/cocos/scripting/CMakeLists.txt @@ -36,3 +36,9 @@ target_link_libraries(luabinding tolua lua ) + +set_target_properties(luabinding + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt index 94a1fffb50..fd1f63dc64 100644 --- a/external/Box2D/CMakeLists.txt +++ b/external/Box2D/CMakeLists.txt @@ -53,3 +53,9 @@ include_directories( add_library(box2d STATIC ${BOX2D_SRC} ) + +set_target_properties(box2d + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/lua/lua/CMakeLists.txt b/external/lua/lua/CMakeLists.txt index faba14e849..c63d80a7b2 100644 --- a/external/lua/lua/CMakeLists.txt +++ b/external/lua/lua/CMakeLists.txt @@ -33,4 +33,10 @@ set(LUA_SRC add_library(lua STATIC ${LUA_SRC} -) \ No newline at end of file +) + +set_target_properties(lua + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/lua/tolua/CMakeLists.txt b/external/lua/tolua/CMakeLists.txt index 481bdd1247..b12e144e75 100644 --- a/external/lua/tolua/CMakeLists.txt +++ b/external/lua/tolua/CMakeLists.txt @@ -15,3 +15,8 @@ add_library(tolua STATIC ${TOLUA_SRC} ) +set_target_properties(tolua + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index d73334ce7e..198764a991 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,5 +1,15 @@ - +if(BUILD_HelloCpp) add_subdirectory(Cpp/HelloCpp) +endif(BUILD_HelloCpp) + +if(BUILD_TestCpp) add_subdirectory(Cpp/TestCpp) +endif(BUILD_TestCpp) + +if(BUILD_HelloLua) add_subdirectory(Lua/HelloLua) +endif(BUILD_HelloLua) + +if(BUILD_TestLua) add_subdirectory(Lua/TestLua) +endif(BUILD_TestLua) \ No newline at end of file From b7173cd60d086217a930dd5e51c78769f7ce1a75 Mon Sep 17 00:00:00 2001 From: Michael Contento Date: Wed, 6 Nov 2013 14:42:31 +0100 Subject: [PATCH 104/197] add Sprite::setScale(float, float) --- cocos/2d/CCSprite.cpp | 6 ++++++ cocos/2d/CCSprite.h | 1 + 2 files changed, 7 insertions(+) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index fa6f4878b0..63aa9fb5bb 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -840,6 +840,12 @@ void Sprite::setScale(float fScale) SET_DIRTY_RECURSIVELY(); } +void Sprite::setScale(float scaleX, float scaleY) +{ + Node::setScale(scaleX, scaleY); + SET_DIRTY_RECURSIVELY(); +} + void Sprite::setVertexZ(float fVertexZ) { Node::setVertexZ(fVertexZ); diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 7ebf7ff616..0c0b652972 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -494,6 +494,7 @@ public: /// @name Functions inherited from Node virtual void setScaleX(float scaleX) override; virtual void setScaleY(float scaleY) override; + virtual void setScale(float scaleX, float scaleY) override; /** * @js NA * @lua NA From 6be59456a5c03d9bac50d0f7359a16e9a1ed0aa3 Mon Sep 17 00:00:00 2001 From: Oleg Loginov Date: Thu, 7 Nov 2013 01:24:33 +0400 Subject: [PATCH 105/197] correct type in root CMakeLists.txt --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f75d56a708..c03a1e9d87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,9 +26,9 @@ option(BUILD_TestLua "Only build TestLua sample" ON) if(DEBUG_MODE) - set(CMAKE_BUILE_TYPE DEBUG) + set(CMAKE_BUILD_TYPE DEBUG) else(DEBUG_MODE) - set(CMAKE_BUILE_TYPE RELEASE) + set(CMAKE_BUILD_TYPE RELEASE) endif(DEBUG_MODE) set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") From 998b7986465d1288ad683d0e8263965b379778ae Mon Sep 17 00:00:00 2001 From: Oleg Loginov Date: Thu, 7 Nov 2013 01:43:26 +0400 Subject: [PATCH 106/197] ignore output files from script make-all-linux-project.sh --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 8acdd3504c..d16b0398e7 100644 --- a/.gitignore +++ b/.gitignore @@ -100,3 +100,8 @@ tools/jenkins_scripts/mac/android/userconf.ini # CTags tags + +# ignore files, created with make-all-linux-project script +/lib +/build/linux-build + From ddb0111392f921c826cfb6ec0f211960b7d8ff0d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 6 Nov 2013 17:05:13 -0800 Subject: [PATCH 107/197] continue replacing `const char*` with `const std::string&` This patch includes: * Continue replacing `const char*` with `const std::string&` where it makes sense. * It also removes some Hungarian notation from the code. * It fixes some indentation issues in part of the code * It replaces `int` or `unsigned int` with `long` where it makes sense. --- cocos/2d/CCAtlasNode.cpp | 10 +- cocos/2d/CCAtlasNode.h | 17 +- cocos/2d/CCDrawNode.cpp | 10 +- cocos/2d/CCDrawNode.h | 6 +- cocos/2d/CCFont.cpp | 4 +- cocos/2d/CCFont.h | 23 +- cocos/2d/CCFontAtlas.cpp | 30 +- cocos/2d/CCFontAtlas.h | 50 ++-- cocos/2d/CCFontAtlasCache.cpp | 2 +- cocos/2d/CCFontAtlasCache.h | 6 +- cocos/2d/CCFontAtlasFactory.cpp | 30 +- cocos/2d/CCFontDefinition.cpp | 8 +- cocos/2d/CCFontDefinition.h | 12 +- cocos/2d/CCFontFNT.cpp | 32 ++- cocos/2d/CCFontFNT.h | 7 +- cocos/2d/CCGrabber.h | 2 +- cocos/2d/CCGrid.cpp | 2 +- cocos/2d/CCGrid.h | 12 +- cocos/2d/CCLabelAtlas.cpp | 43 ++- cocos/2d/CCLabelAtlas.h | 12 +- cocos/2d/CCLabelBMFont.cpp | 28 +- cocos/2d/CCLabelBMFont.h | 6 +- cocos/2d/CCLabelTTF.cpp | 145 +++++----- cocos/2d/CCLabelTTF.h | 28 +- cocos/2d/CCMenuItem.cpp | 272 +++++++++--------- cocos/2d/CCMenuItem.h | 50 ++-- cocos/2d/CCScene.h | 14 +- cocos/2d/CCTMXTiledMap.cpp | 49 ++-- cocos/2d/CCTMXTiledMap.h | 14 +- cocos/2d/CCTMXXMLParser.cpp | 30 +- cocos/2d/CCTMXXMLParser.h | 24 +- cocos/gui/UIButton.cpp | 2 +- .../CCControlExtension/CCControlButton.cpp | 2 +- 33 files changed, 508 insertions(+), 474 deletions(-) diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 7d5a64dba7..6922a8f7ca 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -61,8 +61,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender) +AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { AtlasNode * pRet = new AtlasNode(); if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -74,15 +73,14 @@ AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned return NULL; } -bool AtlasNode::initWithTileFile(const char *tile, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender) +bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { - CCASSERT(tile != NULL, "title should not be null"); + CCASSERT(tile.size() > 0, "file size should not be empty"); Texture2D *texture = TextureCache::getInstance()->addImage(tile); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); } -bool AtlasNode::initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender) +bool AtlasNode::initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender) { _itemWidth = tileWidth; _itemHeight = tileHeight; diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 74dcc9f970..9f06456589 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -52,8 +52,7 @@ class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol { public: /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - static AtlasNode * create(const char* tile,unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender); + static AtlasNode * create(const std::string& filename, long tileWidth, long tileHeight, long itemsToRender); /** * @js ctor */ @@ -65,10 +64,10 @@ public: virtual ~AtlasNode(); /** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - bool initWithTileFile(const char* tile, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender); + bool initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender); /** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/ - bool initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender); + bool initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender); /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses @@ -115,14 +114,14 @@ private : protected: //! chars per row - unsigned int _itemsPerRow; + long _itemsPerRow; //! chars per column - unsigned int _itemsPerColumn; + long _itemsPerColumn; //! width of each char - unsigned int _itemWidth; + long _itemWidth; //! height of each char - unsigned int _itemHeight; + long _itemHeight; Color3B _colorUnmodified; @@ -132,7 +131,7 @@ protected: BlendFunc _blendFunc; // quads to draw - unsigned int _quadsToDraw; + long _quadsToDraw; // color uniform GLint _uniformColor; // This varible is only used for LabelAtlas FPS display. So plz don't modify its value. diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 3623266864..d373709686 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -140,7 +140,7 @@ DrawNode* DrawNode::create() return pRet; } -void DrawNode::ensureCapacity(int count) +void DrawNode::ensureCapacity(long count) { CCASSERT(count>=0, "capacity must be >= 0"); @@ -331,8 +331,10 @@ void DrawNode::drawSegment(const Point &from, const Point &to, float radius, con _dirty = true; } -void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) +void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) { + CCASSERT(count >= 0, "invalid count value"); + struct ExtrudeVerts {Vertex2F offset, n;}; struct ExtrudeVerts* extrude = (struct ExtrudeVerts*)malloc(sizeof(struct ExtrudeVerts)*count); memset(extrude, 0, sizeof(struct ExtrudeVerts)*count); @@ -376,9 +378,9 @@ void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fill *cursor++ = tmp; } - for(unsigned int i = 0; i < count; i++) + for(long i = 0; i < count; i++) { - int j = (i+1)%count; + long j = (i+1)%count; Vertex2F v0 = __v2f(verts[i]); Vertex2F v1 = __v2f(verts[j]); diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 3e128d26ea..fe7312ade8 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -71,7 +71,7 @@ public: * In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor) * @endcode */ - void drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); + void drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); /** Clear the geometry in the node's buffer. */ void clear(); @@ -99,13 +99,13 @@ public: virtual void draw() override; protected: - void ensureCapacity(int count); + void ensureCapacity(long count); void render(); GLuint _vao; GLuint _vbo; - int _bufferCapacity; + long _bufferCapacity; GLsizei _bufferCount; V2F_C4B_T2F *_buffer; diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 3dc8271499..c48acdc0b5 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -99,12 +99,12 @@ const char * Font::getCurrentGlyphCollection() const } } -Font* Font::createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) +Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); } -Font* Font::createWithFNT(const char* fntFilePath) +Font* Font::createWithFNT(const std::string& fntFilePath) { return FontFNT::create(fntFilePath); } diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index e4bcb141ce..cf3084011d 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -42,21 +42,21 @@ class CC_DLL Font : public Object public: // create the font - static Font* createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - static Font* createWithFNT(const char* fntFilePath); + static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); + static Font* createWithFNT(const std::string& fntFilePath); virtual FontAtlas *createFontAtlas() = 0; - virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; - virtual const char * getCurrentGlyphCollection() const; + virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; + virtual const char* getCurrentGlyphCollection() const; - virtual int getLetterPadding() const { return 0; } - virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } - virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } - virtual int getFontMaxHeight() const { return 0; } - virtual Rect getRectForChar(unsigned short theChar) const; + virtual int getLetterPadding() const { return 0; } + virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } + virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } + virtual int getFontMaxHeight() const { return 0; } + virtual Rect getRectForChar(unsigned short theChar) const; - virtual int getUTF16TextLenght(unsigned short int *text) const; + virtual int getUTF16TextLenght(unsigned short int *text) const; virtual unsigned short int * getUTF16Text(const char *text, int &outNumLetters) const; virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; @@ -71,8 +71,7 @@ protected: void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0); const char * getGlyphCollection(GlyphCollection glyphs) const; -private: - + GlyphCollection _usedGlyphs; char * _customGlyphs; static const char * _glyphASCII; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 24b56bd448..72f29e13d8 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -1,10 +1,26 @@ -// -// CCFontAtlas.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/18/13. -// -// +/**************************************************************************** + Copyright (c) 2013 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. + ****************************************************************************/ #include "cocos2d.h" #include "CCFontAtlas.h" diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index a388a5b987..317a06561d 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -24,7 +24,7 @@ #ifndef _CCFontAtlas_h_ #define _CCFontAtlas_h_ -#include +#include NS_CC_BEGIN @@ -34,17 +34,17 @@ class Font; struct FontLetterDefinition { unsigned short letteCharUTF16; - float U; - float V; - float width; - float height; - float offsetX; - float offsetY; - int textureID; - float commonLineHeight; - float anchorX; - float anchorY; - bool validDefinition; + float U; + float V; + float width; + float height; + float offsetX; + float offsetY; + int textureID; + float commonLineHeight; + float anchorX; + float anchorY; + bool validDefinition; }; class CC_DLL FontAtlas : public Object @@ -69,26 +69,26 @@ public: float getCommonLineHeight() const; void setCommonLineHeight(float newHeight); - Texture2D & getTexture(int slot); - const Font * getFont() const; + Texture2D& getTexture(int slot); + const Font* getFont() const; private: bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); void relaseTextures(); - std::map _atlasTextures; - std::map _fontLetterDefinitions; - float _commonLineHeight; - Font * _font; + std::unordered_map _atlasTextures; + std::unordered_map _fontLetterDefinitions; + float _commonLineHeight; + Font * _font; // Dynamic GlyphCollection related stuff - int _currentPage; - unsigned char *_currentPageData; - int _currentPageDataSize; - float _currentPageOrigX; - float _currentPageOrigY; - float _currentPageLineHeight; - float _letterPadding; + int _currentPage; + unsigned char *_currentPageData; + int _currentPageDataSize; + float _currentPageOrigX; + float _currentPageOrigY; + float _currentPageLineHeight; + float _letterPadding; }; diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 762a506ae4..00fc1e2a1f 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -28,7 +28,7 @@ NS_CC_BEGIN -std::map FontAtlasCache::_atlasMap; +std::unordered_map FontAtlasCache::_atlasMap; FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) { diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index c63c832d48..f5f8ca7df4 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -26,7 +26,7 @@ #define _CCFontAtlasCache_h_ #include -#include +#include #include "cocos2d.h" #include "CCFontAtlas.h" @@ -41,12 +41,12 @@ public: static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0); static FontAtlas * getFontAtlasFNT(const char *fontFileName); - static bool releaseFontAtlas(FontAtlas *atlas); + static bool releaseFontAtlas(FontAtlas *atlas); private: static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs); - static std::map _atlasMap; + static std::unordered_map _atlasMap; }; NS_CC_END diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index f5e4f60802..b1cd69172f 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -1,10 +1,26 @@ -// -// CCFontAtlasFactory.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/23/13. -// -// +/**************************************************************************** + Copyright (c) 2013 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. + ****************************************************************************/ #include "CCFontAtlasFactory.h" #include "CCFontFNT.h" diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp index 938204f3b0..d8414dc64d 100644 --- a/cocos/2d/CCFontDefinition.cpp +++ b/cocos/2d/CCFontDefinition.cpp @@ -27,7 +27,7 @@ NS_CC_BEGIN -const int FontDefinitionTTF::DEFAUL_ATALS_TEXTURE_SIZE = 1024; +const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024; FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) { @@ -36,7 +36,7 @@ FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) { if (textureSize == 0) - textureSize = DEFAUL_ATALS_TEXTURE_SIZE; + textureSize = DEFAUL_ATLAS_TEXTURE_SIZE; FontDefinitionTTF *ret = new FontDefinitionTTF; @@ -82,8 +82,8 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) // loops all the lines in this page for (int cLines = 0; cLinesgetPageAt(cPages)->getNumLines(); ++cLines) { - float posXUV = 0.0; - float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); + float posXUV = 0.0; + float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); int charsCounter = 0; diff --git a/cocos/2d/CCFontDefinition.h b/cocos/2d/CCFontDefinition.h index f5e6da10b6..1f9504920c 100644 --- a/cocos/2d/CCFontDefinition.h +++ b/cocos/2d/CCFontDefinition.h @@ -25,6 +25,8 @@ #ifndef _FontDefinition_h_ #define _FontDefinition_h_ +#include + #include "CCTextImage.h" #include "CCFont.h" #include "CCFontAtlas.h" @@ -55,11 +57,11 @@ private: bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); void addLetterDefinition(const FontLetterDefinition &defToAdd); - TextImage * _textImages; - std::map _fontLettersDefinitionUTF16; - float _commonLineHeight; - static const int DEFAUL_ATALS_TEXTURE_SIZE; - + TextImage * _textImages; + std::unordered_map _fontLettersDefinitionUTF16; + float _commonLineHeight; + + static const int DEFAUL_ATLAS_TEXTURE_SIZE; }; NS_CC_END diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index e655236a1b..1992b4f828 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -1,17 +1,33 @@ -// -// CCFontFNT.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/24/13. -// -// +/**************************************************************************** + Copyright (c) 2013 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. + ****************************************************************************/ #include "CCFontFNT.h" #include "CCFontAtlas.h" NS_CC_BEGIN -FontFNT * FontFNT::create(const char* fntFilePath) +FontFNT * FontFNT::create(const std::string& fntFilePath) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index 3994e14463..e9c4327672 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -35,7 +35,7 @@ class FontFNT : public Font public: - static FontFNT * create(const char* fntFilePath); + static FontFNT * create(const std::string& fntFilePath); virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual Rect getRectForChar(unsigned short theChar) const override; @@ -43,7 +43,8 @@ public: protected: - FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {} + FontFNT(CCBMFontConfiguration *theContfig) : + _configuration(theContfig) {} /** * @js NA * @lua NA @@ -56,7 +57,7 @@ private: int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; Rect getRectForCharInternal(unsigned short theChar) const; - CCBMFontConfiguration * _configuration; + CCBMFontConfiguration * _configuration; }; diff --git a/cocos/2d/CCGrabber.h b/cocos/2d/CCGrabber.h index 9fef542459..022e68ed0d 100644 --- a/cocos/2d/CCGrabber.h +++ b/cocos/2d/CCGrabber.h @@ -59,7 +59,7 @@ public: protected: GLuint _FBO; GLint _oldFBO; - GLfloat _oldClearColor[4]; + GLfloat _oldClearColor[4]; }; // end of effects group diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index fc2152ab13..717277eff8 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -119,7 +119,7 @@ bool GridBase::initWithSize(const Size& gridSize) // we only use rgba8888 Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888; - int dataLen = (int)(POTWide * POTHigh * 4); + long dataLen = POTWide * POTHigh * 4; void *data = calloc(dataLen, 1); if (! data) { diff --git a/cocos/2d/CCGrid.h b/cocos/2d/CCGrid.h index 97904cdf3e..61a8cbbe34 100644 --- a/cocos/2d/CCGrid.h +++ b/cocos/2d/CCGrid.h @@ -66,23 +66,23 @@ public: bool initWithSize(const Size& gridSize); /** whether or not the grid is active */ - inline bool isActive(void) { return _active; } + inline bool isActive(void) const { return _active; } void setActive(bool bActive); /** number of times that the grid will be reused */ - inline int getReuseGrid(void) { return _reuseGrid; } + inline int getReuseGrid(void) const { return _reuseGrid; } inline void setReuseGrid(int nReuseGrid) { _reuseGrid = nReuseGrid; } /** size of the grid */ - inline const Size& getGridSize(void) { return _gridSize; } + inline const Size& getGridSize(void) const { return _gridSize; } inline void setGridSize(const Size& gridSize) { _gridSize = gridSize; } /** pixels between the grids */ - inline const Point& getStep(void) { return _step; } + inline const Point& getStep(void) const { return _step; } inline void setStep(const Point& step) { _step = step; } /** is texture flipped */ - inline bool isTextureFlipped(void) { return _isTextureFlipped; } + inline bool isTextureFlipped(void) const { return _isTextureFlipped; } void setTextureFlipped(bool bFlipped); void beforeDraw(void); @@ -95,7 +95,7 @@ public: protected: bool _active; - int _reuseGrid; + long _reuseGrid; Size _gridSize; Texture2D *_texture; Point _step; diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index f1a9126b54..56a6ff723b 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN //CCLabelAtlas - Creation & Init -LabelAtlas* LabelAtlas::create(const char *string, const char *charMapFile, unsigned int itemWidth, int unsigned itemHeight, unsigned int startCharMap) +LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) { LabelAtlas *pRet = new LabelAtlas(); if(pRet && pRet->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) @@ -54,16 +54,15 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *charMapFile, unsi return NULL; } -bool LabelAtlas::initWithString(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) { Texture2D *texture = TextureCache::getInstance()->addImage(charMapFile); return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } -bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +bool LabelAtlas::initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap) { - CCASSERT(string != NULL, ""); - if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, strlen(string))) + if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, string.size())) { _mapStartChar = startCharMap; this->setString(string); @@ -72,7 +71,7 @@ bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned return false; } -LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile) +LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile) { LabelAtlas *ret = new LabelAtlas(); if (ret) @@ -90,24 +89,24 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile) return ret; } -bool LabelAtlas::initWithString(const char *theString, const char *fntFile) +bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile) { - std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); - std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; - Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str()); - - CCASSERT(((String*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version"); - - std::string texturePathStr = relPathStr + ((String*)dict->objectForKey("textureFilename"))->getCString(); - String *textureFilename = String::create(texturePathStr); - unsigned int width = ((String*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR(); - unsigned int height = ((String*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR(); - unsigned int startChar = ((String*)dict->objectForKey("firstChar"))->intValue(); - + std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); + std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; + Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str()); - this->initWithString(theString, textureFilename->getCString(), width, height, startChar); - - return true; + CCASSERT(((String*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version"); + + std::string texturePathStr = relPathStr + ((String*)dict->objectForKey("textureFilename"))->getCString(); + String *textureFilename = String::create(texturePathStr); + unsigned int width = ((String*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR(); + unsigned int height = ((String*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR(); + unsigned int startChar = ((String*)dict->objectForKey("firstChar"))->intValue(); + + + this->initWithString(theString, textureFilename->getCString(), width, height, startChar); + + return true; } //CCLabelAtlas - Atlas generation diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index b8df38f62d..eb8d06f4be 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -67,23 +67,23 @@ public: } /** creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - static LabelAtlas * create(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + static LabelAtlas * create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap); /** creates the LabelAtlas with a string and a configuration file @since v2.0 */ - static LabelAtlas* create(const char *string, const char *fntFile); + static LabelAtlas* create(const std::string& string, const std::string& fntFile); /** initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - bool initWithString(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + bool initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap); /** initializes the LabelAtlas with a string and a configuration file @since v2.0 */ - bool initWithString(const char *string, const char *fntFile); + bool initWithString(const std::string& string, const std::string& fntFile); /** initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the starting char of the atlas */ - bool initWithString(const char* string, Texture2D* texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + bool initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap); // super methods virtual void updateAtlasValues(); @@ -98,7 +98,7 @@ protected: // string to render std::string _string; // the first char in the charmap - unsigned int _mapStartChar; + long _mapStartChar; }; // end of GUI group diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 1000889c62..e28d4d0afc 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -64,7 +64,7 @@ static Dictionary* s_pConfigurations = NULL; CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) { - CCBMFontConfiguration* pRet = NULL; + CCBMFontConfiguration* ret = NULL; if( s_pConfigurations == NULL ) { @@ -72,17 +72,17 @@ CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) s_pConfigurations->init(); } - pRet = static_cast( s_pConfigurations->objectForKey(fntFile) ); - if( pRet == NULL ) + ret = static_cast( s_pConfigurations->objectForKey(fntFile) ); + if( ret == NULL ) { - pRet = CCBMFontConfiguration::create(fntFile.c_str()); - if (pRet) + ret = CCBMFontConfiguration::create(fntFile.c_str()); + if (ret) { - s_pConfigurations->setObject(pRet, fntFile); + s_pConfigurations->setObject(ret, fntFile); } } - return pRet; + return ret; } void FNTConfigRemoveCache( void ) @@ -98,19 +98,19 @@ void FNTConfigRemoveCache( void ) //BitmapFontConfiguration // -CCBMFontConfiguration * CCBMFontConfiguration::create(const char *FNTfile) +CCBMFontConfiguration * CCBMFontConfiguration::create(const std::string& FNTfile) { - CCBMFontConfiguration * pRet = new CCBMFontConfiguration(); - if (pRet->initWithFNTfile(FNTfile)) + CCBMFontConfiguration * ret = new CCBMFontConfiguration(); + if (ret->initWithFNTfile(FNTfile)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile) +bool CCBMFontConfiguration::initWithFNTfile(const std::string& FNTfile) { _kerningDictionary = NULL; _fontDefDictionary = NULL; diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index 0da1584387..cc49dd0806 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -140,10 +140,10 @@ public: const char * description() const; /** allocates a CCBMFontConfiguration with a FNT file */ - static CCBMFontConfiguration * create(const char *FNTfile); + static CCBMFontConfiguration * create(const std::string& FNTfile); /** initializes a BitmapFontConfiguration with a FNT file */ - bool initWithFNTfile(const char *FNTfile); + bool initWithFNTfile(const std::string& FNTfile); inline const std::string& getAtlasName(){ return _atlasName; } inline void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } @@ -303,7 +303,7 @@ protected: bool _cascadeColorEnabled; bool _cascadeOpacityEnabled; /** conforms to RGBAProtocol protocol */ - bool _isOpacityModifyRGB; + bool _isOpacityModifyRGB; }; diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 051b07d9b7..3eec437d09 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN LabelTTF::LabelTTF() : _alignment(TextHAlignment::CENTER) , _vAlignment(TextVAlignment::TOP) -, _fontName(NULL) +, _fontName("") , _fontSize(0.0) , _string("") , _shadowEnabled(false) @@ -53,58 +53,57 @@ LabelTTF::LabelTTF() LabelTTF::~LabelTTF() { - CC_SAFE_DELETE(_fontName); } LabelTTF * LabelTTF::create() { - LabelTTF * pRet = new LabelTTF(); - if (pRet && pRet->init()) + LabelTTF * ret = new LabelTTF(); + if (ret && ret->init()) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } -LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize) +LabelTTF * LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize) { return LabelTTF::create(string, fontName, fontSize, Size::ZERO, TextHAlignment::CENTER, TextVAlignment::TOP); } -LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize, +LabelTTF * LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment hAlignment) { return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, TextVAlignment::TOP); } -LabelTTF* LabelTTF::create(const char *string, const char *fontName, float fontSize, +LabelTTF* LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize, const Size &dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment) { - LabelTTF *pRet = new LabelTTF(); - if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) + LabelTTF *ret = new LabelTTF(); + if(ret && ret->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -LabelTTF * LabelTTF::createWithFontDefinition(const char *string, FontDefinition &textDefinition) +LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDefinition &textDefinition) { - LabelTTF *pRet = new LabelTTF(); - if(pRet && pRet->initWithStringAndTextDefinition(string, textDefinition)) + LabelTTF *ret = new LabelTTF(); + if(ret && ret->initWithStringAndTextDefinition(string, textDefinition)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -113,19 +112,19 @@ bool LabelTTF::init() return this->initWithString("", "Helvetica", 12); } -bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize, +bool LabelTTF::initWithString(const std::string& label, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment alignment) { return this->initWithString(label, fontName, fontSize, dimensions, alignment, TextVAlignment::TOP); } -bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize) +bool LabelTTF::initWithString(const std::string& label, const std::string& fontName, float fontSize) { return this->initWithString(label, fontName, fontSize, Size::ZERO, TextHAlignment::LEFT, TextVAlignment::TOP); } -bool LabelTTF::initWithString(const char *string, const char *fontName, float fontSize, +bool LabelTTF::initWithString(const std::string& string, const std::string& fontName, float fontSize, const cocos2d::Size &dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment) { @@ -135,10 +134,10 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM)); _dimensions = Size(dimensions.width, dimensions.height); - _alignment = hAlignment; - _vAlignment = vAlignment; - _fontName = new std::string(fontName); - _fontSize = fontSize; + _alignment = hAlignment; + _vAlignment = vAlignment; + _fontName = fontName; + _fontSize = fontSize; this->setString(string); @@ -148,7 +147,7 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo return false; } -bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition) +bool LabelTTF::initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition) { if (Sprite::init()) { @@ -188,7 +187,7 @@ const char* LabelTTF::getString(void) const const char* LabelTTF::description() const { - return String::createWithFormat("", _fontName->c_str(), _fontSize)->getCString(); + return String::createWithFormat("", _fontName.c_str(), _fontSize)->getCString(); } TextHAlignment LabelTTF::getHorizontalAlignment() const @@ -236,6 +235,7 @@ const Size& LabelTTF::getDimensions() const void LabelTTF::setDimensions(const Size &dim) { + // XXX: float comparison... very unreliable if (dim.width != _dimensions.width || dim.height != _dimensions.height) { _dimensions = dim; @@ -255,6 +255,7 @@ float LabelTTF::getFontSize() const void LabelTTF::setFontSize(float fontSize) { + // XXX: float comparison... very unreliable if (_fontSize != fontSize) { _fontSize = fontSize; @@ -267,17 +268,16 @@ void LabelTTF::setFontSize(float fontSize) } } -const char* LabelTTF::getFontName() const +const std::string& LabelTTF::getFontName() const { - return _fontName->c_str(); + return _fontName; } -void LabelTTF::setFontName(const char *fontName) +void LabelTTF::setFontName(const std::string& fontName) { - if (_fontName->compare(fontName)) + if (_fontName.compare(fontName)) { - delete _fontName; - _fontName = new std::string(fontName); + _fontName = fontName; // Force update if (_string.size() > 0) @@ -296,21 +296,21 @@ bool LabelTTF::updateTexture() if (!tex) return false; - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) FontDefinition texDef = _prepareTextDefinition(true); tex->initWithString( _string.c_str(), texDef ); - #else +#else tex->initWithString( _string.c_str(), - _fontName->c_str(), + _fontName.c_str(), _fontSize * CC_CONTENT_SCALE_FACTOR(), CC_SIZE_POINTS_TO_PIXELS(_dimensions), _alignment, _vAlignment); - #endif +#endif // set the texture this->setTexture(tex); @@ -340,7 +340,7 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float if ( (_shadowOffset.width != shadowOffset.width) || (_shadowOffset.height!=shadowOffset.height) ) { - _shadowOffset.width = shadowOffset.width; + _shadowOffset.width = shadowOffset.width; _shadowOffset.height = shadowOffset.height; valueChanged = true; @@ -352,27 +352,26 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float valueChanged = true; } - if (_shadowBlur != shadowBlur) + if (_shadowBlur != shadowBlur) { _shadowBlur = shadowBlur; valueChanged = true; } - if ( valueChanged && updateTexture ) { this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::disableShadow(bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (_shadowEnabled) { @@ -380,17 +379,16 @@ void LabelTTF::disableShadow(bool updateTexture) if (updateTexture) this->updateTexture(); - } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) bool valueChanged = false; @@ -417,15 +415,15 @@ void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool u this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::disableStroke(bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (_strokeEnabled) { @@ -435,15 +433,15 @@ void LabelTTF::disableStroke(bool updateTexture) this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (_textFillColor.r != tintColor.r || _textFillColor.g != tintColor.g || _textFillColor.b != tintColor.b) { _textFillColor = tintColor; @@ -451,9 +449,9 @@ void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture) if (updateTexture) this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::setTextDefinition(const FontDefinition& theDefinition) @@ -469,11 +467,11 @@ FontDefinition LabelTTF::getTextDefinition() void LabelTTF::_updateWithTextDefinition(const FontDefinition& textDefinition, bool mustUpdateTexture) { _dimensions = Size(textDefinition._dimensions.width, textDefinition._dimensions.height); - _alignment = textDefinition._alignment; - _vAlignment = textDefinition._vertAlignment; + _alignment = textDefinition._alignment; + _vAlignment = textDefinition._vertAlignment; - _fontName = new std::string(textDefinition._fontName); - _fontSize = textDefinition._fontSize; + _fontName = textDefinition._fontName; + _fontSize = textDefinition._fontSize; // shadow @@ -500,19 +498,19 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution) FontDefinition texDef; if (adjustForResolution) - texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); + texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); else - texDef._fontSize = _fontSize; + texDef._fontSize = _fontSize; - texDef._fontName = *_fontName; - texDef._alignment = _alignment; - texDef._vertAlignment = _vAlignment; + texDef._fontName = _fontName; + texDef._alignment = _alignment; + texDef._vertAlignment = _vAlignment; if (adjustForResolution) - texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); + texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); else - texDef._dimensions = _dimensions; + texDef._dimensions = _dimensions; // stroke @@ -525,21 +523,18 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution) texDef._stroke._strokeSize = _strokeSize * CC_CONTENT_SCALE_FACTOR(); else texDef._stroke._strokeSize = _strokeSize; - - } else { texDef._stroke._strokeEnabled = false; } - // shadow if ( _shadowEnabled ) { - texDef._shadow._shadowEnabled = true; - texDef._shadow._shadowBlur = _shadowBlur; - texDef._shadow._shadowOpacity = _shadowOpacity; + texDef._shadow._shadowEnabled = true; + texDef._shadow._shadowBlur = _shadowBlur; + texDef._shadow._shadowOpacity = _shadowOpacity; if (adjustForResolution) texDef._shadow._shadowOffset = CC_SIZE_POINTS_TO_PIXELS(_shadowOffset); diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 1f785028c4..029a125def 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -75,39 +75,39 @@ public: /** creates a LabelTTF with a font name and font size in points @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize); /** creates a LabelTTF from a fontname, horizontal alignment, dimension in points, and font size in points. @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize, - const Size& dimensions, TextHAlignment hAlignment); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize, + const Size& dimensions, TextHAlignment hAlignment); /** creates a Label from a fontname, alignment, dimension in points and font size in points @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize, - const Size& dimensions, TextHAlignment hAlignment, - TextVAlignment vAlignment); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize, + const Size& dimensions, TextHAlignment hAlignment, + TextVAlignment vAlignment); /** Create a lable with string and a font definition*/ - static LabelTTF * createWithFontDefinition(const char *string, FontDefinition &textDefinition); + static LabelTTF * createWithFontDefinition(const std::string& string, FontDefinition &textDefinition); /** initializes the LabelTTF with a font name and font size */ - bool initWithString(const char *string, const char *fontName, float fontSize); + bool initWithString(const std::string& string, const std::string& fontName, float fontSize); /** initializes the LabelTTF with a font name, alignment, dimension and font size */ - bool initWithString(const char *string, const char *fontName, float fontSize, + bool initWithString(const std::string& string, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment hAlignment); /** initializes the LabelTTF with a font name, alignment, dimension and font size */ - bool initWithString(const char *string, const char *fontName, float fontSize, + bool initWithString(const std::string& string, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment); /** initializes the LabelTTF with a font name, alignment, dimension and font size */ - bool initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition); + bool initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition); /** set the text definition used by this label */ void setTextDefinition(const FontDefinition& theDefinition); @@ -159,8 +159,8 @@ public: float getFontSize() const; void setFontSize(float fontSize); - const char* getFontName() const; - void setFontName(const char *fontName); + const std::string& getFontName() const; + void setFontName(const std::string& fontName); private: bool updateTexture(); @@ -177,7 +177,7 @@ protected: /** The vertical alignment of the label */ TextVAlignment _vAlignment; /** Font name used in the label */ - std::string * _fontName; + std::string _fontName; /** Font size of the label */ float _fontSize; /** label's string */ diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 24ec16a3a7..89aa7eaba6 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -42,7 +42,7 @@ THE SOFTWARE. NS_CC_BEGIN -static unsigned int _globalFontSize = kItemSize; +static long _globalFontSize = kItemSize; static std::string _globalFontName = "Marker Felt"; static bool _globalFontNameRelease = false; @@ -64,18 +64,18 @@ MenuItem* MenuItem::create() // XXX deprecated MenuItem* MenuItem::create(Object *target, SEL_MenuHandler selector) { - MenuItem *pRet = new MenuItem(); - pRet->initWithTarget(target, selector); - pRet->autorelease(); - return pRet; + MenuItem *ret = new MenuItem(); + ret->initWithTarget(target, selector); + ret->autorelease(); + return ret; } MenuItem* MenuItem::create( const ccMenuCallback& callback) { - MenuItem *pRet = new MenuItem(); - pRet->initWithCallback(callback); - pRet->autorelease(); - return pRet; + MenuItem *ret = new MenuItem(); + ret->initWithCallback(callback); + ret->autorelease(); + return ret; } // XXX deprecated @@ -188,26 +188,26 @@ void MenuItemLabel::setLabel(Node* var) // XXX: deprecated MenuItemLabel * MenuItemLabel::create(Node*label, Object* target, SEL_MenuHandler selector) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, target, selector); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, target, selector); + ret->autorelease(); + return ret; } MenuItemLabel * MenuItemLabel::create(Node*label, const ccMenuCallback& callback) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, callback); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, callback); + ret->autorelease(); + return ret; } MenuItemLabel* MenuItemLabel::create(Node *label) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, (const ccMenuCallback&) nullptr); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, (const ccMenuCallback&) nullptr); + ret->autorelease(); + return ret; } // XXX: deprecated @@ -237,7 +237,7 @@ MenuItemLabel::~MenuItemLabel() { } -void MenuItemLabel::setString(const char * label) +void MenuItemLabel::setString(const std::string& label) { dynamic_cast(_label)->setString(label); this->setContentSize(_label->getContentSize()); @@ -310,41 +310,39 @@ void MenuItemLabel::setEnabled(bool enabled) //CCMenuItemAtlasFont // -MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap) +MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap) { return MenuItemAtlasFont::create(value, charMapFile, itemWidth, itemHeight, startCharMap, (const ccMenuCallback&)nullptr); } // XXX: deprecated -MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) +MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) { - MenuItemAtlasFont *pRet = new MenuItemAtlasFont(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); - pRet->autorelease(); - return pRet; + MenuItemAtlasFont *ret = new MenuItemAtlasFont(); + ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); + ret->autorelease(); + return ret; } -MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) +MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback) { - MenuItemAtlasFont *pRet = new MenuItemAtlasFont(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); - pRet->autorelease(); - return pRet; + MenuItemAtlasFont *ret = new MenuItemAtlasFont(); + ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); + ret->autorelease(); + return ret; } // XXX: deprecated -bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) +bool MenuItemAtlasFont::initWithString(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) { - CCASSERT( value != NULL && strlen(value) != 0, "value length must be greater than 0"); - _target = target; CC_SAFE_RETAIN(_target); return initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) +bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback) { - CCASSERT( value != NULL && strlen(value) != 0, "value length must be greater than 0"); + CCASSERT( value.size() != 0, "value length must be greater than 0"); LabelAtlas *label = new LabelAtlas(); label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); label->autorelease(); @@ -359,17 +357,17 @@ bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFil //CCMenuItemFont // -void MenuItemFont::setFontSize(unsigned int s) +void MenuItemFont::setFontSize(long s) { _globalFontSize = s; } -unsigned int MenuItemFont::getFontSize() +long MenuItemFont::getFontSize() { return _globalFontSize; } -void MenuItemFont::setFontName(const char *name) +void MenuItemFont::setFontName(const std::string& name) { if (_globalFontNameRelease) { @@ -379,35 +377,35 @@ void MenuItemFont::setFontName(const char *name) _globalFontNameRelease = true; } -const char * MenuItemFont::getFontName() +const std::string& MenuItemFont::getFontName() { - return _globalFontName.c_str(); + return _globalFontName; } // XXX: deprecated MenuItemFont * MenuItemFont::create(const char *value, Object* target, SEL_MenuHandler selector) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, target, selector); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, target, selector); + ret->autorelease(); + return ret; } -MenuItemFont * MenuItemFont::create(const char *value, const ccMenuCallback& callback) +MenuItemFont * MenuItemFont::create(const std::string& value, const ccMenuCallback& callback) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, callback); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, callback); + ret->autorelease(); + return ret; } -MenuItemFont * MenuItemFont::create(const char *value) +MenuItemFont * MenuItemFont::create(const std::string& value) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, (const ccMenuCallback&)nullptr); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, (const ccMenuCallback&)nullptr); + ret->autorelease(); + return ret; } MenuItemFont::MenuItemFont() @@ -429,14 +427,14 @@ bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHan return initWithString(value, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemFont::initWithString(const char *value, const ccMenuCallback& callback) +bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback) { - CCASSERT( value != NULL && strlen(value) != 0, "Value length must be greater than 0"); + CCASSERT( value.size() >= 0, "Value length must be greater than 0"); _fontName = _globalFontName; _fontSize = _globalFontSize; - LabelTTF *label = LabelTTF::create(value, _fontName.c_str(), (float)_fontSize); + LabelTTF *label = LabelTTF::create(value, _fontName, (float)_fontSize); if (MenuItemLabel::initWithLabel(label, callback)) { // do something ? @@ -451,26 +449,26 @@ void MenuItemFont::recreateLabel() this->setLabel(label); } -void MenuItemFont::setFontSizeObj(unsigned int s) +void MenuItemFont::setFontSizeObj(long s) { _fontSize = s; recreateLabel(); } -unsigned int MenuItemFont::getFontSizeObj() const +long MenuItemFont::getFontSizeObj() const { return _fontSize; } -void MenuItemFont::setFontNameObj(const char* name) +void MenuItemFont::setFontNameObj(const std::string& name) { _fontName = name; recreateLabel(); } -const char* MenuItemFont::getFontNameObj() const +const std::string& MenuItemFont::getFontNameObj() const { - return _fontName.c_str(); + return _fontName; } // @@ -561,18 +559,18 @@ MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite // XXX deprecated MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, Object *target, SEL_MenuHandler selector) { - MenuItemSprite *pRet = new MenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); - pRet->autorelease(); - return pRet; + MenuItemSprite *ret = new MenuItemSprite(); + ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); + ret->autorelease(); + return ret; } MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, const ccMenuCallback& callback) { - MenuItemSprite *pRet = new MenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); - pRet->autorelease(); - return pRet; + MenuItemSprite *ret = new MenuItemSprite(); + ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); + ret->autorelease(); + return ret; } // XXX deprecated @@ -687,71 +685,71 @@ void MenuItemSprite::updateImagesVisibility() MenuItemImage* MenuItemImage::create() { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->init()) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->init()) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } bool MenuItemImage::init(void) { - return initWithNormalImage(NULL, NULL, NULL, (const ccMenuCallback&)nullptr); + return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage) { - return MenuItemImage::create(normalImage, selectedImage, NULL, (const ccMenuCallback&)nullptr); + return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr); } // XXX deprecated MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector) { - return MenuItemImage::create(normalImage, selectedImage, NULL, target, selector); + return MenuItemImage::create(normalImage, selectedImage, "", target, selector); } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const ccMenuCallback& callback) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const ccMenuCallback& callback) { - return MenuItemImage::create(normalImage, selectedImage, NULL, callback); + return MenuItemImage::create(normalImage, selectedImage, "", callback); } // XXX deprecated MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -762,23 +760,23 @@ bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *sel CC_SAFE_RETAIN(_target); return initWithNormalImage(normalImage, selectedImage, disabledImage, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback) +bool MenuItemImage::initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback) { Node *normalSprite = NULL; Node *selectedSprite = NULL; Node *disabledSprite = NULL; - if (normalImage) + if (normalImage.size() >0) { normalSprite = Sprite::create(normalImage); } - if (selectedImage) + if (selectedImage.size() >0) { selectedSprite = Sprite::create(selectedImage); } - if(disabledImage) + if(disabledImage.size() >0) { disabledSprite = Sprite::create(disabledImage); } @@ -810,38 +808,38 @@ void MenuItemImage::setDisabledSpriteFrame(SpriteFrame * frame) // XXX: deprecated MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->MenuItem::initWithTarget(target, selector); - pRet->_subItems = Array::create(); - pRet->_subItems->retain(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->MenuItem::initWithTarget(target, selector); + ret->_subItems = Array::create(); + ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - pRet->_subItems->addObject(menuItem); + ret->_subItems->addObject(menuItem); } - pRet->_selectedIndex = UINT_MAX; - pRet->setSelectedIndex(0); - return pRet; + ret->_selectedIndex = UINT_MAX; + ret->setSelectedIndex(0); + return ret; } MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->MenuItem::initWithCallback(callback); - pRet->_subItems = Array::create(); - pRet->_subItems->retain(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->MenuItem::initWithCallback(callback); + ret->_subItems = Array::create(); + ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - pRet->_subItems->addObject(menuItem); + ret->_subItems->addObject(menuItem); } - pRet->_selectedIndex = UINT_MAX; - pRet->setSelectedIndex(0); - return pRet; + ret->_selectedIndex = UINT_MAX; + ret->setSelectedIndex(0); + return ret; } // XXX: deprecated @@ -849,30 +847,30 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle { va_list args; va_start(args, item); - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithTarget(target, selector, item, args); - pRet->autorelease(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithTarget(target, selector, item, args); + ret->autorelease(); va_end(args); - return pRet; + return ret; } MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, MenuItem* item, ...) { va_list args; va_start(args, item); - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithCallback(callback, item, args); - pRet->autorelease(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithCallback(callback, item, args); + ret->autorelease(); va_end(args); - return pRet; + return ret; } MenuItemToggle * MenuItemToggle::create() { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithItem(NULL); - pRet->autorelease(); - return pRet; + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithItem(NULL); + ret->autorelease(); + return ret; } // XXX: deprecated @@ -903,10 +901,10 @@ bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem * MenuItemToggle* MenuItemToggle::create(MenuItem *item) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithItem(item); - pRet->autorelease(); - return pRet; + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithItem(item); + ret->autorelease(); + return ret; } bool MenuItemToggle::initWithItem(MenuItem *item) diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 78b8d333ef..d0fcda9a50 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -166,7 +166,7 @@ public: CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector); /** sets a new string to the inner label */ - void setString(const char * label); + void setString(const std::string& label); /** Gets the color that will be used to disable the item */ inline const Color3B& getDisabledColor() const { return _disabledColor; }; @@ -204,11 +204,11 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** creates a menu item from a string and atlas with a target/selector */ - static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap); + static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ - CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); + CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ - static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); + static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); /** * @js ctor */ @@ -220,9 +220,9 @@ public: virtual ~MenuItemAtlasFont(){} /** initializes a menu item from a string and atlas with a target/selector */ - CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); + CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** initializes a menu item from a string and atlas with a target/selector */ - bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); }; @@ -233,11 +233,11 @@ class CC_DLL MenuItemFont : public MenuItemLabel { public: /** creates a menu item from a string without target/selector. To be used with MenuItemToggle */ - static MenuItemFont * create(const char *value); + static MenuItemFont * create(const std::string& value); /** creates a menu item from a string with a target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string with a target/selector */ - static MenuItemFont * create(const char *value, const ccMenuCallback& callback); + static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback); /** * @js ctor */ @@ -251,30 +251,30 @@ public: /** initializes a menu item from a string with a target/selector */ CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); /** initializes a menu item from a string with a target/selector */ - bool initWithString(const char *value, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const ccMenuCallback& callback); /** set default font size */ - static void setFontSize(unsigned int s); + static void setFontSize(long size); /** get default font size */ - static unsigned int getFontSize(); + static long getFontSize(); CC_DEPRECATED_ATTRIBUTE static unsigned int fontSize() { return MenuItemFont::getFontSize(); }; /** set the default font name */ - static void setFontName(const char *name); + static void setFontName(const std::string& name); /** get the default font name */ - static const char *getFontName(); - CC_DEPRECATED_ATTRIBUTE static const char *fontName() { return MenuItemFont::getFontName(); }; + static const std::string& getFontName(); + CC_DEPRECATED_ATTRIBUTE static const std::string& fontName() { return MenuItemFont::getFontName(); }; /** set font size * c++ can not overload static and non-static member functions with the same parameter types * so change the name to setFontSizeObj * @js setFontSize */ - void setFontSizeObj(unsigned int s); + void setFontSizeObj(long size); /** get font size * @js getFontSize */ - unsigned int getFontSizeObj() const; + long getFontSizeObj() const; CC_DEPRECATED_ATTRIBUTE unsigned int fontSizeObj() const { return getFontSizeObj(); }; /** set the font name @@ -282,20 +282,20 @@ public: * so change the name to setFontNameObj * @js setFontName */ - void setFontNameObj(const char* name); + void setFontNameObj(const std::string& name); /** returns the name of the Font * @js getFontNameObj */ - const char* getFontNameObj() const; + const std::string& getFontNameObj() const; /** deprecated Use getFontNameObj() instead */ - CC_DEPRECATED_ATTRIBUTE const char* fontNameObj() const { return getFontNameObj(); } + CC_DEPRECATED_ATTRIBUTE const std::string& fontNameObj() const { return getFontNameObj(); } protected: void recreateLabel(); - unsigned int _fontSize; + long _fontSize; std::string _fontName; }; @@ -384,18 +384,18 @@ public: /** Creates an MenuItemImage. */ static MenuItemImage* create(); /** creates a menu item with a normal and selected image*/ - static MenuItemImage* create(const char *normalImage, const char *selectedImage); + static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage); /** creates a menu item with a normal,selected and disabled image*/ - static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage); + static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage); /** creates a menu item with a normal and selected image with target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector); /** creates a menu item with a normal and selected image with a callable object */ - static MenuItemImage* create(const char *normalImage, const char *selectedImage, const ccMenuCallback& callback); + static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const ccMenuCallback& callback); /** creates a menu item with a normal,selected and disabled image with target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); /** creates a menu item with a normal,selected and disabled image with a callable object */ - static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback); + static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const std::string&disabledImage, const ccMenuCallback& callback); /** * @js ctor */ @@ -410,7 +410,7 @@ public: /** initializes a menu item with a normal, selected and disabled image with target/selector */ CC_DEPRECATED_ATTRIBUTE bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); /** initializes a menu item with a normal, selected and disabled image with a callable object */ - bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback); + bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback); /** sets the sprite frame for the normal image */ void setNormalSpriteFrame(SpriteFrame* frame); diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index e0f69edd82..19f5c5f1cc 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -68,18 +68,14 @@ public: #ifdef CC_USE_PHYSICS public: bool initWithPhysics(); - + + inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; } + virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - - /* - * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" - */ - virtual void update(float delta) override; - - inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; } - + virtual void update(float delta) override; + protected: virtual void addChildToPhysicsWorld(Node* child); diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index c6c47b3abd..4205adb1fe 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -32,33 +32,33 @@ NS_CC_BEGIN // implementation TMXTiledMap -TMXTiledMap * TMXTiledMap::create(const char *tmxFile) +TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile) { - TMXTiledMap *pRet = new TMXTiledMap(); - if (pRet->initWithTMXFile(tmxFile)) + TMXTiledMap *ret = new TMXTiledMap(); + if (ret->initWithTMXFile(tmxFile)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -TMXTiledMap* TMXTiledMap::createWithXML(const char* tmxString, const char* resourcePath) +TMXTiledMap* TMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath) { - TMXTiledMap *pRet = new TMXTiledMap(); - if (pRet->initWithXML(tmxString, resourcePath)) + TMXTiledMap *ret = new TMXTiledMap(); + if (ret->initWithXML(tmxString, resourcePath)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -bool TMXTiledMap::initWithTMXFile(const char *tmxFile) +bool TMXTiledMap::initWithTMXFile(const std::string& tmxFile) { - CCASSERT(tmxFile != NULL && strlen(tmxFile)>0, "TMXTiledMap: tmx file should not bi NULL"); + CCASSERT(tmxFile.size()>0, "TMXTiledMap: tmx file should not be empty"); setContentSize(Size::ZERO); @@ -74,7 +74,7 @@ bool TMXTiledMap::initWithTMXFile(const char *tmxFile) return true; } -bool TMXTiledMap::initWithXML(const char* tmxString, const char* resourcePath) +bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath) { setContentSize(Size::ZERO); @@ -195,8 +195,8 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) // update content size with the max size const Size& childSize = child->getContentSize(); Size currentSize = this->getContentSize(); - currentSize.width = MAX( currentSize.width, childSize.width ); - currentSize.height = MAX( currentSize.height, childSize.height ); + currentSize.width = std::max( currentSize.width, childSize.width ); + currentSize.height = std::max( currentSize.height, childSize.height ); this->setContentSize(currentSize); idx++; @@ -206,16 +206,16 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) } // public -TMXLayer * TMXTiledMap::getLayer(const char *layerName) const +TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const { - CCASSERT(layerName != NULL && strlen(layerName) > 0, "Invalid layer name!"); + CCASSERT(layerName.size() > 0, "Invalid layer name!"); Object* pObj = NULL; CCARRAY_FOREACH(_children, pObj) { TMXLayer* layer = dynamic_cast(pObj); if(layer) { - if(0 == strcmp(layer->getLayerName(), layerName)) + if(layerName.compare( layer->getLayerName()) == 0) { return layer; } @@ -226,11 +226,10 @@ TMXLayer * TMXTiledMap::getLayer(const char *layerName) const return NULL; } -TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const +TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const { - CCASSERT(groupName != NULL && strlen(groupName) > 0, "Invalid group name!"); + CCASSERT(groupName.size() > 0, "Invalid group name!"); - std::string sGroupName = groupName; if (_objectGroups && _objectGroups->count()>0) { TMXObjectGroup* objectGroup = NULL; @@ -238,7 +237,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const CCARRAY_FOREACH(_objectGroups, pObj) { objectGroup = static_cast(pObj); - if (objectGroup && objectGroup->getGroupName() == sGroupName) + if (objectGroup && objectGroup->getGroupName() == groupName) { return objectGroup; } @@ -249,7 +248,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const return NULL; } -String* TMXTiledMap::getProperty(const char *propertyName) const +String* TMXTiledMap::getProperty(const std::string& propertyName) const { return static_cast(_properties->objectForKey(propertyName)); } diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index 82ea45bd13..f870938174 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -120,19 +120,19 @@ public: virtual ~TMXTiledMap(); /** creates a TMX Tiled Map with a TMX file.*/ - static TMXTiledMap* create(const char *tmxFile); + static TMXTiledMap* create(const std::string& tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - static TMXTiledMap* createWithXML(const char* tmxString, const char* resourcePath); + static TMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath); /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(const char *tmxFile); + bool initWithTMXFile(const std::string& tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(const char* tmxString, const char* resourcePath); + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); /** return the TMXLayer for the specific layer */ - TMXLayer* getLayer(const char *layerName) const; + TMXLayer* getLayer(const std::string& layerName) const; /** * @js NA * @lua NA @@ -140,7 +140,7 @@ public: CC_DEPRECATED_ATTRIBUTE TMXLayer* layerNamed(const char *layerName) const { return getLayer(layerName); }; /** return the TMXObjectGroup for the specific group */ - TMXObjectGroup* getObjectGroup(const char *groupName) const; + TMXObjectGroup* getObjectGroup(const std::string& groupName) const; /** * @js NA * @lua NA @@ -148,7 +148,7 @@ public: CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const char *groupName) const { return getObjectGroup(groupName); }; /** return the value for the specific property name */ - String *getProperty(const char *propertyName) const; + String *getProperty(const std::string& propertyName) const; /** * @js NA * @lua NA diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 8497638cf7..d981cca6b4 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -112,7 +112,7 @@ Rect TMXTilesetInfo::rectForGID(unsigned int gid) // implementation TMXMapInfo -TMXMapInfo * TMXMapInfo::create(const char *tmxFile) +TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile) { TMXMapInfo *pRet = new TMXMapInfo(); if(pRet->initWithTMXFile(tmxFile)) @@ -124,7 +124,7 @@ TMXMapInfo * TMXMapInfo::create(const char *tmxFile) return NULL; } -TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resourcePath) +TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath) { TMXMapInfo *pRet = new TMXMapInfo(); if(pRet->initWithXML(tmxString, resourcePath)) @@ -136,7 +136,7 @@ TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resour return NULL; } -void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) +void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath) { _tilesets = Array::create(); _tilesets->retain(); @@ -144,12 +144,12 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) _layers = Array::create(); _layers->retain(); - if (tmxFileName != NULL) + if (tmxFileName.size() > 0) { _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName); } - if (resourcePath != NULL) + if (resourcePath.size() > 0) { _resources = resourcePath; } @@ -169,15 +169,15 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) _parentElement = TMXPropertyNone; _currentFirstGID = 0; } -bool TMXMapInfo::initWithXML(const char* tmxString, const char* resourcePath) +bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath) { - internalInit(NULL, resourcePath); + internalInit("", resourcePath); return parseXMLString(tmxString); } -bool TMXMapInfo::initWithTMXFile(const char *tmxFile) +bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) { - internalInit(tmxFile, NULL); + internalInit(tmxFile, ""); return parseXMLFile(_TMXFileName.c_str()); } @@ -205,13 +205,11 @@ TMXMapInfo::~TMXMapInfo() CC_SAFE_RELEASE(_objectGroups); } -bool TMXMapInfo::parseXMLString(const char *xmlString) +bool TMXMapInfo::parseXMLString(const std::string& xmlString) { - int len = strlen(xmlString); - if (xmlString == NULL || len <= 0) - { + int len = xmlString.size(); + if (len <= 0) return false; - } SAXParser parser; @@ -222,10 +220,10 @@ bool TMXMapInfo::parseXMLString(const char *xmlString) parser.setDelegator(this); - return parser.parse(xmlString, len); + return parser.parse(xmlString.c_str(), len); } -bool TMXMapInfo::parseXMLFile(const char *xmlFilename) +bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename) { SAXParser parser; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 7b4851386c..80afafd1aa 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -166,9 +166,9 @@ class CC_DLL TMXMapInfo : public Object, public SAXDelegator { public: /** creates a TMX Format with a tmx file */ - static TMXMapInfo * create(const char *tmxFile); + static TMXMapInfo * create(const std::string& tmxFile); /** creates a TMX Format with an XML string and a TMX resource path */ - static TMXMapInfo * createWithXML(const char* tmxString, const char* resourcePath); + static TMXMapInfo * createWithXML(const std::string& tmxString, const std::string& resourcePath); /** creates a TMX Format with a tmx file */ CC_DEPRECATED_ATTRIBUTE static TMXMapInfo * formatWithTMXFile(const char *tmxFile) { return TMXMapInfo::create(tmxFile); }; @@ -185,13 +185,13 @@ public: virtual ~TMXMapInfo(); /** initializes a TMX format with a tmx file */ - bool initWithTMXFile(const char *tmxFile); + bool initWithTMXFile(const std::string& tmxFile); /** initializes a TMX format with an XML string and a TMX resource path */ - bool initWithXML(const char* tmxString, const char* resourcePath); + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ - bool parseXMLFile(const char *xmlFilename); + bool parseXMLFile(const std::string& xmlFilename); /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ - bool parseXMLString(const char *xmlString); + bool parseXMLString(const std::string& xmlString); Dictionary* getTileProperties() { return _tileProperties; }; void setTileProperties(Dictionary* tileProperties) { @@ -278,13 +278,13 @@ public: */ void textHandler(void *ctx, const char *ch, int len); - inline const char* getCurrentString(){ return _currentString.c_str(); } - inline void setCurrentString(const char *currentString){ _currentString = currentString; } - inline const char* getTMXFileName(){ return _TMXFileName.c_str(); } - inline void setTMXFileName(const char *fileName){ _TMXFileName = fileName; } -private: - void internalInit(const char* tmxFileName, const char* resourcePath); + inline const std::string& getCurrentString() const { return _currentString; } + inline void setCurrentString(const std::string& currentString){ _currentString = currentString; } + inline const std::string& getTMXFileName() const { return _TMXFileName; } + inline void setTMXFileName(const std::string& fileName){ _TMXFileName = fileName; } + protected: + void internalInit(const std::string& tmxFileName, const std::string& resourcePath); /// map orientation int _orientation; diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 12cc3cc932..1190e8ae8d 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -603,7 +603,7 @@ void UIButton::setTitleFontName(const char* fontName) const char* UIButton::getTitleFontName() const { - return _titleRenderer->getFontName(); + return _titleRenderer->getFontName().c_str(); } void UIButton::setColor(const Color3B &color) diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index 5e4e102aba..e747dfe24c 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -404,7 +404,7 @@ const char * ControlButton::getTitleTTFForState(State state) LabelTTF* labelTTF = dynamic_cast(label); if(labelTTF != 0) { - return labelTTF->getFontName(); + return labelTTF->getFontName().c_str(); } else { From fa0011346e21345a03e688e7a85181cc67aa03d0 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 09:58:24 +0800 Subject: [PATCH 108/197] fixed linux build error --- cocos/gui/UILabelBMFont.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/gui/UILabelBMFont.cpp b/cocos/gui/UILabelBMFont.cpp index d8560fd4a8..ee3ad66ddf 100644 --- a/cocos/gui/UILabelBMFont.cpp +++ b/cocos/gui/UILabelBMFont.cpp @@ -60,7 +60,7 @@ void UILabelBMFont::initRenderer() void UILabelBMFont::setFntFile(const char *fileName) { - if (!fileName || std::strcmp(fileName, "") == 0) + if (!fileName || strcmp(fileName, "") == 0) { return; } From f05b79d14082f1fb09aeca7e8247960f7d60a79f Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 7 Nov 2013 11:29:23 +0800 Subject: [PATCH 109/197] remove unneeded files --- samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 1 - 1 file changed, 1 deletion(-) delete mode 100644 samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id deleted file mode 100644 index 06123eec12..0000000000 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3275ac270645139eb273b2a47c215f39bcb0e0d5 \ No newline at end of file From af5ab02bc7a123292a85d78b27f2397e7cd13d04 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 14:00:51 +0800 Subject: [PATCH 110/197] temp commit --- .../cocostudio/CCSGUIReader.cpp | 9 ++++---- cocos/gui/UIHelper.cpp | 23 +++++++++++++++++++ cocos/gui/UIHelper.h | 5 +++- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index de644e6ec6..f799c26752 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -236,16 +236,15 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); - if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { + if (fileDesignWidth <= 0 || fileDesignHeight <= 0) + { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); -// CCUIHELPER->setFileDesignWidth(winSize.width); -// CCUIHELPER->setFileDesignHeight(winSize.height); + UIHelper::setFileDesignSize(fileName, winSize); } else { -// CCUIHELPER->setFileDesignWidth(fileDesignWidth); -// CCUIHELPER->setFileDesignHeight(fileDesignHeight); + UIHelper::setFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index d896a6372c..8b43c8f890 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -25,6 +25,8 @@ #include "CocosGUI.h" namespace gui { + +static cocos2d::Dictionary* fileDesignSizes = NULL; UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -118,5 +120,26 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) } return NULL; } + +void UIHelper::setFileDesignSize(const char *fileName, const cocos2d::Size &size) +{ + if (!fileDesignSizes) + { + fileDesignSizes = cocos2d::Dictionary::create(); + fileDesignSizes->retain(); + } + cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); + fileDesignSizes->setObject(strSize, fileName); +} + +const cocos2d::Size UIHelper::getFileDesignSize(const char* fileName) +{ + if (!fileDesignSizes) + { + return cocos2d::Size::ZERO; + } + cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)fileDesignSizes->objectForKey(fileName))->_string.c_str()); + return designSize; +} } \ No newline at end of file diff --git a/cocos/gui/UIHelper.h b/cocos/gui/UIHelper.h index 75ccba81eb..68893ceff0 100644 --- a/cocos/gui/UIHelper.h +++ b/cocos/gui/UIHelper.h @@ -71,8 +71,11 @@ public: /*temp action*/ static UIWidget* seekActionWidgetByActionTag(UIWidget* root, int tag); + + static void setFileDesignSize(const char* fileName, const cocos2d::Size &size); + + static const cocos2d::Size getFileDesignSize(const char* fileName); }; - } #endif /* defined(__CocoGUI__UISystem__) */ From f2cd5ca63003e7d4c1425309ea76a68d677e2aff Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 14:17:57 +0800 Subject: [PATCH 111/197] issue #2771: fix body and joint memory bugs. add removeFormWorld and destroy to PhysicsJoint, and add a destroy param to PhysicsWorld->removeJoint() --- cocos/physics/CCPhysicsBody.cpp | 35 +++++---- cocos/physics/CCPhysicsBody.h | 2 + cocos/physics/CCPhysicsJoint.cpp | 50 +++++++++++-- cocos/physics/CCPhysicsJoint.h | 10 ++- cocos/physics/CCPhysicsShape.cpp | 4 +- cocos/physics/CCPhysicsWorld.cpp | 125 ++++++++++++++++++++++--------- cocos/physics/CCPhysicsWorld.h | 13 ++-- 7 files changed, 176 insertions(+), 63 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 131bfdc3c5..031104157a 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -86,22 +86,15 @@ PhysicsBody::PhysicsBody() PhysicsBody::~PhysicsBody() { - if (_world) - { - removeFromWorld(); - } - - removeAllShapes(); - for (auto it = _joints.begin(); it != _joints.end(); ++it) { PhysicsJoint* joint = *it; + PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA(); - - other->_joints.erase(std::find(other->_joints.begin(), other->_joints.end(), joint)); - + other->removeJoint(joint); delete joint; } + CC_SAFE_DELETE(_info); } @@ -282,6 +275,16 @@ bool PhysicsBody::init() return false; } +void PhysicsBody::removeJoint(PhysicsJoint* joint) +{ + auto it = std::find(_joints.begin(), _joints.end(), joint); + + if (it != _joints.end()) + { + _joints.erase(it); + } +} + void PhysicsBody::setDynamic(bool dynamic) { if (dynamic != _dynamic) @@ -616,7 +619,7 @@ void PhysicsBody::removeShape(int tag) void PhysicsBody::removeShape(PhysicsShape* shape) { - if (_shapes->getIndexOfObject(shape) == UINT_MAX) + if (_shapes->getIndexOfObject(shape) != UINT_MAX) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -629,6 +632,9 @@ void PhysicsBody::removeShape(PhysicsShape* shape) { _world->removeShape(shape); } + + // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. + shape->_body = nullptr; shape->setBody(nullptr); _shapes->removeObject(shape); } @@ -650,6 +656,9 @@ void PhysicsBody::removeAllShapes() { _world->removeShape(shape); } + + // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. + shape->_body = nullptr; shape->setBody(nullptr); } @@ -674,10 +683,10 @@ void PhysicsBody::setEnable(bool enable) { if (enable) { - _world->addBody(this); + _world->delayTestAddBody(this); }else { - _world->removeBody(this); + _world->delayTestRemoveBody(this); } } } diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 6ae92e4b33..7f465d561c 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -263,6 +263,8 @@ protected: virtual void update(float delta) override; + void removeJoint(PhysicsJoint* joint); + protected: PhysicsBody(); virtual ~PhysicsBody(); diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 791266f8ba..38eb106fce 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -32,6 +32,7 @@ #endif #include "CCPhysicsBody.h" +#include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsJointInfo_chipmunk.h" #include "box2d/CCPhysicsJointInfo_box2d.h" @@ -48,9 +49,11 @@ NS_CC_BEGIN PhysicsJoint::PhysicsJoint() : _bodyA(nullptr) , _bodyB(nullptr) +, _world(nullptr) , _info(nullptr) , _enable(false) , _collisionEnable(true) +, _destoryMark(false) , _tag(0) { @@ -94,12 +97,15 @@ void PhysicsJoint::setEnable(bool enable) { _enable = enable; - if (enable) + if (_world != nullptr) { - - }else - { - + if (enable) + { + _world->delayTestAddJoint(this); + }else + { + _world->delayTestRemoveJoint(this); + } } } } @@ -174,6 +180,40 @@ void PhysicsJoint::setCollisionEnable(bool enable) } } +void PhysicsJoint::removeFormWorld() +{ + if (_world) + { + _world->removeJoint(this, false); + } +} + +void PhysicsJoint::destroy(PhysicsJoint* joint) +{ + if (joint!= nullptr) + { + // remove the joint and delete it. + if (joint->_world != nullptr) + { + joint->_world->removeJoint(joint, true); + } + else + { + if (joint->_bodyA != nullptr) + { + joint->_bodyA->removeJoint(joint); + } + + if (joint->_bodyB != nullptr) + { + joint->_bodyB->removeJoint(joint); + } + + delete joint; + } + } +} + PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointFixed* joint = new PhysicsJointFixed(); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index fea8ba4707..55befaf328 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -34,6 +34,7 @@ NS_CC_BEGIN class PhysicsBody; +class PhysicsWorld; class PhysicsJointInfo; class PhysicsBodyInfo; @@ -47,14 +48,17 @@ protected: virtual ~PhysicsJoint() = 0; public: - PhysicsBody* getBodyA() const { return _bodyA; } - PhysicsBody* getBodyB() const { return _bodyB; } + inline PhysicsBody* getBodyA() const { return _bodyA; } + inline PhysicsBody* getBodyB() const { return _bodyB; } + inline PhysicsWorld* getWorld() const { return _world; } inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } inline bool isEnabled() const { return _enable; } void setEnable(bool enable); inline bool isCollisionEnabled() const { return _collisionEnable; } void setCollisionEnable(bool enable); + void removeFormWorld(); + static void destroy(PhysicsJoint* joint); protected: bool init(PhysicsBody* a, PhysicsBody* b); @@ -68,9 +72,11 @@ protected: protected: PhysicsBody* _bodyA; PhysicsBody* _bodyB; + PhysicsWorld* _world; PhysicsJointInfo* _info; bool _enable; bool _collisionEnable; + bool _destoryMark; int _tag; friend class PhysicsBody; diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 7cc64483cd..05264e6a70 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -265,7 +265,7 @@ Point PhysicsShape::getPolyonCenter(const Point* points, int count) void PhysicsShape::setBody(PhysicsBody *body) { // already added - if (_body == body) + if (body != nullptr && _body == body) { return; } @@ -278,12 +278,10 @@ void PhysicsShape::setBody(PhysicsBody *body) if (body == nullptr) { _info->setBody(nullptr); - //_info->setGroup(CP_NO_GROUP); _body = nullptr; }else { _info->setBody(body->_info->getBody()); - //_info->setGroup(body->_info->group); _body = body; } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 3c5956b85c..104b916530 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -307,32 +307,82 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) void PhysicsWorld::addJoint(PhysicsJoint* joint) { - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it == _joints.end()) - { - delayTestAddJoint(joint); - _joints.push_back(joint); - } - + delayTestAddJoint(joint); + _joints.push_back(joint); + joint->_world = this; } -void PhysicsWorld::removeJoint(PhysicsJoint* joint) +void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) { - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it != _joints.end()) + if (joint->getWorld() != this) { - delayTestRemoveJoint(*it); - _joints.remove(joint); + if (destroy) + { + CCLOG("physics warnning: the joint is not in this world, it won't be destoried utill the body it conntect is destoried"); + } + return; + } + + delayTestRemoveJoint(joint); + + _joints.remove(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } } } -void PhysicsWorld::removeAllJoints() +void PhysicsWorld::removeAllJoints(bool destroy) { for (auto joint : _joints) { delayTestRemoveJoint(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } + } } _joints.clear(); @@ -365,8 +415,6 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) if (body->isEnabled()) { - body->_world = this; - //is gravity enable if (!body->isGravityEnabled()) { @@ -393,14 +441,28 @@ PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) delayTestAddBody(body); _bodies->addObject(body); + body->_world = this; return body; } void PhysicsWorld::removeBody(PhysicsBody* body) { + + if (body->getWorld() != this) + { + return; + } + + // destory the body's joints + for (auto joint : body->_joints) + { + removeJoint(joint, true); + } + delayTestRemoveBody(body); _bodies->removeObject(body); + body->_world = nullptr; } void PhysicsWorld::removeBody(int tag) @@ -420,23 +482,12 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() != this) - { - return; - } - // reset the gravity if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } - // remove joints - for (auto joint : body->_joints) - { - removeJoint(joint); - } - // remove shaps for (auto shape : *body->getShapes()) { @@ -445,8 +496,6 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) // remove body _info->removeBody(body->_info->getBody()); - - body->_world = nullptr; } void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) @@ -461,7 +510,9 @@ void PhysicsWorld::removeAllBodies() { for (Object* obj : *_bodies) { - delayTestRemoveBody(dynamic_cast(obj)); + PhysicsBody* child = dynamic_cast(obj); + delayTestRemoveBody(child); + child->_world = nullptr; } _bodies->removeAllObjects(); @@ -515,6 +566,11 @@ void PhysicsWorld::updateJoints() for (auto joint : _delayRemoveJoints) { realRemoveJoint(joint); + + if (joint->_destoryMark) + { + delete joint; + } } _delayAddJoints.clear(); @@ -525,8 +581,9 @@ void PhysicsWorld::update(float delta) { if (_delayDirty) { - updateBodies(); + // the updateJoints must run before the updateBodies. updateJoints(); + updateBodies(); _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); } @@ -795,7 +852,7 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) _scene->getEventDispatcher()->dispatchEvent(&event); } -void PhysicsWorld::setGravity(Point gravity) +void PhysicsWorld::setGravity(const Vect& gravity) { if (_bodies != nullptr) { @@ -932,8 +989,8 @@ PhysicsWorld::PhysicsWorld() PhysicsWorld::~PhysicsWorld() { + removeAllJoints(true); removeAllBodies(); - removeAllJoints(); CC_SAFE_RELEASE(_delayRemoveBodies); CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 2e70749f57..65ffd19927 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -57,7 +57,7 @@ public: Point start; Point end; Point contact; - Point normal; + Vect normal; float fraction; void* data; }Info; @@ -101,9 +101,9 @@ public: /** Adds a joint to the physics world.*/ virtual void addJoint(PhysicsJoint* joint); /** Removes a joint from the physics world.*/ - virtual void removeJoint(PhysicsJoint* joint); + virtual void removeJoint(PhysicsJoint* joint, bool destroy); /** Remove all joints from the physics world.*/ - virtual void removeAllJoints(); + virtual void removeAllJoints(bool destroy); virtual void removeBody(PhysicsBody* body); virtual void removeBody(int tag); @@ -123,9 +123,9 @@ public: inline Scene& getScene() const { return *_scene; } /** get the gravity value */ - inline Point getGravity() const { return _gravity; } + inline Vect getGravity() const { return _gravity; } /** set the gravity value */ - void setGravity(Point gravity); + void setGravity(const Vect& gravity); /** test the debug draw is enabled */ inline bool isDebugDraw() const { return _debugDraw; } @@ -162,7 +162,7 @@ protected: virtual void updateJoints(); protected: - Point _gravity; + Vect _gravity; float _speed; PhysicsWorldInfo* _info; @@ -187,6 +187,7 @@ protected: friend class Scene; friend class PhysicsBody; friend class PhysicsShape; + friend class PhysicsJoint; friend class PhysicsWorldCallback; }; From a02fd7c6dadf2bac0d7a88dfaf0513ab4bb97045 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 14:40:09 +0800 Subject: [PATCH 112/197] issue #2771: fix PhysicsWorld some bugs --- cocos/physics/CCPhysicsWorld.cpp | 29 +++++++++++++++++++---------- cocos/physics/CCPhysicsWorld.h | 4 ++-- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 104b916530..eeabdbce13 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -307,6 +307,11 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) void PhysicsWorld::addJoint(PhysicsJoint* joint) { + if (joint->getWorld() != nullptr && joint->getWorld() != this) + { + joint->removeFormWorld(); + } + delayTestAddJoint(joint); _joints.push_back(joint); joint->_world = this; @@ -388,14 +393,14 @@ void PhysicsWorld::removeAllJoints(bool destroy) _joints.clear(); } -PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) +void PhysicsWorld::addShape(PhysicsShape* shape) { for (auto cps : shape->_info->getShapes()) { _info->addShape(cps); } - return shape; + return; } void PhysicsWorld::realAddJoint(PhysicsJoint *joint) @@ -408,11 +413,6 @@ void PhysicsWorld::realAddJoint(PhysicsJoint *joint) void PhysicsWorld::realAddBody(PhysicsBody* body) { - if (body->getWorld() != this && body->getWorld() != nullptr) - { - body->removeFromWorld(); - } - if (body->isEnabled()) { //is gravity enable @@ -435,15 +435,23 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) } } -PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) +void PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); + if (body->getWorld() == this) + { + return; + } + + if (body->getWorld() != nullptr) + { + body->removeFromWorld(); + } + delayTestAddBody(body); _bodies->addObject(body); body->_world = this; - - return body; } void PhysicsWorld::removeBody(PhysicsBody* body) @@ -451,6 +459,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) if (body->getWorld() != this) { + CCLOG("Physics Warnning: this body doesn't belong to this world"); return; } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 65ffd19927..1b7775f546 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -136,8 +136,8 @@ protected: static PhysicsWorld* create(Scene& scene); bool init(Scene& scene); - virtual PhysicsBody* addBody(PhysicsBody* body); - virtual PhysicsShape* addShape(PhysicsShape* shape); + virtual void addBody(PhysicsBody* body); + virtual void addShape(PhysicsShape* shape); virtual void removeShape(PhysicsShape* shape); virtual void update(float delta); From eb508e47289fbccdce28e9cd5fadfa51fb66798c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 15:12:13 +0800 Subject: [PATCH 113/197] issue #2771: fix PhysicsWorld functions name readadd/removexxx -> doadd/removexxx delayTestAdd/Removexxx -> add/removexxxOrDelay --- cocos/physics/CCPhysicsBody.cpp | 4 +-- cocos/physics/CCPhysicsJoint.cpp | 4 +-- cocos/physics/CCPhysicsWorld.cpp | 44 ++++++++++++++++---------------- cocos/physics/CCPhysicsWorld.h | 16 ++++++------ 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 031104157a..9304e3652b 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -683,10 +683,10 @@ void PhysicsBody::setEnable(bool enable) { if (enable) { - _world->delayTestAddBody(this); + _world->addBodyOrDelay(this); }else { - _world->delayTestRemoveBody(this); + _world->removeBodyOrDelay(this); } } } diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 38eb106fce..2e037cf2f5 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -101,10 +101,10 @@ void PhysicsJoint::setEnable(bool enable) { if (enable) { - _world->delayTestAddJoint(this); + _world->addJointOrDelay(this); }else { - _world->delayTestRemoveJoint(this); + _world->removeJointOrDelay(this); } } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index eeabdbce13..976fb29e04 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -219,7 +219,7 @@ bool PhysicsWorld::init(Scene& scene) return false; } -void PhysicsWorld::delayTestAddBody(PhysicsBody* body) +void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) { if (_delayRemoveBodies->getIndexOfObject(body) != UINT_MAX) { @@ -236,11 +236,11 @@ void PhysicsWorld::delayTestAddBody(PhysicsBody* body) } }else { - realAddBody(body); + doAddBody(body); } } -void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) +void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) { if (_delayAddBodies->getIndexOfObject(body) != UINT_MAX) { @@ -257,11 +257,11 @@ void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) } }else { - realRemoveBody(body); + doRemoveBody(body); } } -void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) +void PhysicsWorld::addJointOrDelay(PhysicsJoint* joint) { auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); if (it != _delayRemoveJoints.end()) @@ -279,11 +279,11 @@ void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) } }else { - realAddJoint(joint); + doAddJoint(joint); } } -void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) +void PhysicsWorld::removeJointOrDelay(PhysicsJoint* joint) { auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); if (it != _delayAddJoints.end()) @@ -301,7 +301,7 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) } }else { - realRemoveJoint(joint); + doRemoveJoint(joint); } } @@ -312,7 +312,7 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) joint->removeFormWorld(); } - delayTestAddJoint(joint); + addJointOrDelay(joint); _joints.push_back(joint); joint->_world = this; } @@ -328,7 +328,7 @@ void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) return; } - delayTestRemoveJoint(joint); + removeJointOrDelay(joint); _joints.remove(joint); joint->_world = nullptr; @@ -362,7 +362,7 @@ void PhysicsWorld::removeAllJoints(bool destroy) { for (auto joint : _joints) { - delayTestRemoveJoint(joint); + removeJointOrDelay(joint); joint->_world = nullptr; // clean the connection to this joint @@ -403,7 +403,7 @@ void PhysicsWorld::addShape(PhysicsShape* shape) return; } -void PhysicsWorld::realAddJoint(PhysicsJoint *joint) +void PhysicsWorld::doAddJoint(PhysicsJoint *joint) { for (auto subjoint : joint->_info->getJoints()) { @@ -411,7 +411,7 @@ void PhysicsWorld::realAddJoint(PhysicsJoint *joint) } } -void PhysicsWorld::realAddBody(PhysicsBody* body) +void PhysicsWorld::doAddBody(PhysicsBody* body) { if (body->isEnabled()) { @@ -449,7 +449,7 @@ void PhysicsWorld::addBody(PhysicsBody* body) body->removeFromWorld(); } - delayTestAddBody(body); + addBodyOrDelay(body); _bodies->addObject(body); body->_world = this; } @@ -469,7 +469,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) removeJoint(joint, true); } - delayTestRemoveBody(body); + removeBodyOrDelay(body); _bodies->removeObject(body); body->_world = nullptr; } @@ -487,7 +487,7 @@ void PhysicsWorld::removeBody(int tag) } } -void PhysicsWorld::realRemoveBody(PhysicsBody* body) +void PhysicsWorld::doRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -507,7 +507,7 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) _info->removeBody(body->_info->getBody()); } -void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) +void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) { for (auto subjoint : joint->_info->getJoints()) { @@ -520,7 +520,7 @@ void PhysicsWorld::removeAllBodies() for (Object* obj : *_bodies) { PhysicsBody* child = dynamic_cast(obj); - delayTestRemoveBody(child); + removeBodyOrDelay(child); child->_world = nullptr; } @@ -548,12 +548,12 @@ void PhysicsWorld::updateBodies() for (auto body : *_delayAddBodies) { - realAddBody(dynamic_cast(body)); + doAddBody(dynamic_cast(body)); } for (auto body : *_delayRemoveBodies) { - realRemoveBody(dynamic_cast(body)); + doRemoveBody(dynamic_cast(body)); } _delayAddBodies->removeAllObjects(); @@ -569,12 +569,12 @@ void PhysicsWorld::updateJoints() for (auto joint : _delayAddJoints) { - realAddJoint(joint); + doAddJoint(joint); } for (auto joint : _delayRemoveJoints) { - realRemoveJoint(joint); + doRemoveJoint(joint); if (joint->_destoryMark) { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 1b7775f546..aee0dfefbd 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -150,14 +150,14 @@ protected: virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); - virtual void realAddBody(PhysicsBody* body); - virtual void realRemoveBody(PhysicsBody* body); - virtual void realAddJoint(PhysicsJoint* joint); - virtual void realRemoveJoint(PhysicsJoint* joint); - virtual void delayTestAddBody(PhysicsBody* body); - virtual void delayTestRemoveBody(PhysicsBody* body); - virtual void delayTestAddJoint(PhysicsJoint* joint); - virtual void delayTestRemoveJoint(PhysicsJoint* joint); + virtual void doAddBody(PhysicsBody* body); + virtual void doRemoveBody(PhysicsBody* body); + virtual void doAddJoint(PhysicsJoint* joint); + virtual void doRemoveJoint(PhysicsJoint* joint); + virtual void addBodyOrDelay(PhysicsBody* body); + virtual void removeBodyOrDelay(PhysicsBody* body); + virtual void addJointOrDelay(PhysicsJoint* joint); + virtual void removeJointOrDelay(PhysicsJoint* joint); virtual void updateBodies(); virtual void updateJoints(); From 8c025a2cee14a732cac0ba5b614e29de79519a8e Mon Sep 17 00:00:00 2001 From: samuele3 Date: Thu, 7 Nov 2013 15:12:19 +0800 Subject: [PATCH 114/197] Reslove the linux compiled error --- cocos/2d/CCProfiling.cpp | 2 +- cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 3cd9878375..1db8ba0678 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -125,7 +125,7 @@ const char* ProfilingTimer::description() const { static char s_desciption[512] = {0}; - sprintf(s_desciption, "%s ::\tavg1: %dµ,\tavg2: %dµ,\tmin: %dµ,\tmax: %dµ,\ttotal: %.2fs,\tnr calls: %d", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls); + sprintf(s_desciption, "%s ::\tavg1: %ldµ,\tavg2: %ldµ,\tmin: %ldµ,\tmax: %ldµ,\ttotal: %.2fs,\tnr calls: %ld", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls); return s_desciption; } diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp index 7e5a38abb1..39083ae1e3 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp @@ -51,8 +51,8 @@ static int tolua_cocos2d_MenuItemImage_create(lua_State* tolua_S) ok = true; break; } - const char* normalImage = ((const char*) tolua_tostring(tolua_S,2,0)); - const char* selectedImage = ((const char*) tolua_tostring(tolua_S,3,0)); + const std::string normalImage = ((const std::string) tolua_tocppstring(tolua_S,2,0)); + const std::string selectedImage = ((const std::string) tolua_tocppstring(tolua_S,3,0)); MenuItemImage* tolua_ret = (MenuItemImage*) MenuItemImage::create(normalImage,selectedImage); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; @@ -70,9 +70,9 @@ static int tolua_cocos2d_MenuItemImage_create(lua_State* tolua_S) break; } #endif - const char* normalImage = ((const char*) tolua_tostring(tolua_S,2,0)); - const char* selectedImage = ((const char*) tolua_tostring(tolua_S,3,0)); - const char* disabledImage = ((const char*) tolua_tostring(tolua_S,4,0)); + const std::string normalImage = ((const std::string) tolua_tocppstring(tolua_S,2,0)); + const std::string selectedImage = ((const std::string) tolua_tocppstring(tolua_S,3,0)); + const std::string disabledImage = ((const std::string) tolua_tocppstring(tolua_S,4,0)); MenuItemImage* tolua_ret = (MenuItemImage*) MenuItemImage::create(normalImage,selectedImage,disabledImage); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; @@ -155,7 +155,7 @@ static int tolua_cocos2d_MenuItemFont_create(lua_State* tolua_S) goto tolua_lerror; } #endif - const char* value = ((const char*) tolua_tostring(tolua_S,2,0)); + const std::string value = ((const std::string) tolua_tocppstring(tolua_S,2,0)); MenuItemFont* tolua_ret = (MenuItemFont*) MenuItemFont::create(value); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; From ef5440f738cdfb45469708a0c7ca13d03af5fc3e Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 16:23:50 +0800 Subject: [PATCH 115/197] issue #2771: change rayCast and rectQuery callback class to std::function --- cocos/physics/CCPhysicsWorld.cpp | 28 +++-- cocos/physics/CCPhysicsWorld.h | 68 +++++------- .../Classes/PhysicsTest/PhysicsTest.cpp | 101 ++++++------------ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 4 +- 4 files changed, 74 insertions(+), 127 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 976fb29e04..5b223bb798 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -73,7 +73,7 @@ namespace typedef struct RayCastCallbackInfo { PhysicsWorld* world; - PhysicsRayCastCallback* callback; + PhysicsRayCastCallbackFunc func; Point p1; Point p2; void* data; @@ -82,7 +82,7 @@ namespace typedef struct RectQueryCallbackInfo { PhysicsWorld* world; - PhysicsRectQueryCallback* callback; + PhysicsRectQueryCallbackFunc func; void* data; }RectQueryCallbackInfo; } @@ -148,7 +148,7 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect auto it = PhysicsShapeInfo::getMap().find(shape); CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - PhysicsRayCastCallback::Info callbackInfo = + PhysicsRayCastInfo callbackInfo = { it->second->getShape(), info->p1, @@ -158,7 +158,7 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect (float)t, }; - PhysicsWorldCallback::continues = info->callback->report(*info->world, callbackInfo, info->data); + PhysicsWorldCallback::continues = info->func(*info->world, callbackInfo, info->data); } void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) @@ -172,9 +172,7 @@ void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallba return; } - PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->getShape(), - info->data); + PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) @@ -883,13 +881,13 @@ void PhysicsWorld::setGravity(const Vect& gravity) } -void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data) +void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data) { - CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + CCASSERT(func != nullptr, "callback.report shouldn't be nullptr"); - if (callback.report != nullptr) + if (func != nullptr) { - RayCastCallbackInfo info = { this, &callback, point1, point2, data }; + RayCastCallbackInfo info = { this, func, point1, point2, data }; PhysicsWorldCallback::continues = true; cpSpaceSegmentQuery(this->_info->getSpace(), @@ -903,13 +901,13 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, const Point& point1 } -void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data) +void PhysicsWorld::rectQuery(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data) { - CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + CCASSERT(func != nullptr, "callback.report shouldn't be nullptr"); - if (callback.report != nullptr) + if (func != nullptr) { - RectQueryCallbackInfo info = {this, &callback, data}; + RectQueryCallbackInfo info = {this, func, data}; PhysicsWorldCallback::continues = true; cpSpaceBBQuery(this->_info->getSpace(), diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index aee0dfefbd..240e3fa660 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -48,49 +48,31 @@ class Scene; class DrawNode; class PhysicsWorld; -class PhysicsRayCastCallback -{ -public: - typedef struct Info - { - PhysicsShape* shape; - Point start; - Point end; - Point contact; - Vect normal; - float fraction; - void* data; - }Info; - -public: - PhysicsRayCastCallback() - : report(nullptr) - {} - virtual ~PhysicsRayCastCallback(){} - /** - * @brief Called for each fixture found in the query. You control how the ray cast - * proceeds by returning a float: - * return true: continue - * return false: terminate the ray cast - * @param fixture the fixture hit by the ray - * @param point the point of initial intersection - * @param normal the normal vector at the point of intersection - * @return true to continue, false to terminate - */ - std::function report; -}; -class PhysicsRectQueryCallback + +typedef struct PhysicsRayCastInfo { -public: - PhysicsRectQueryCallback() - : report(nullptr) - {} - virtual ~PhysicsRectQueryCallback(){} - -public: - std::function report; -}; + PhysicsShape* shape; + Point start; + Point end; + Point contact; + Vect normal; + float fraction; + void* data; +}PhysicsRayCastInfo; + +/** + * @brief Called for each fixture found in the query. You control how the ray cast + * proceeds by returning a float: + * return true: continue + * return false: terminate the ray cast + * @param fixture the fixture hit by the ray + * @param point the point of initial intersection + * @param normal the normal vector at the point of intersection + * @return true to continue, false to terminate + */ +typedef std::function PhysicsRayCastCallbackFunc; +typedef std::function PhysicsRectQueryCallbackFunc; /** * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object. @@ -109,8 +91,8 @@ public: virtual void removeBody(int tag); virtual void removeAllBodies(); - void rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data); - void rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data); + void rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data); + void rectQuery(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data); Array* getShapes(const Point& point) const; PhysicsShape* getShape(const Point& point) const; Array* getAllBodies() const; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 0885218d9a..af27626949 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -602,65 +602,12 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data) { *((Point*)data) = info.contact; return false; } -class PhysicsDemoNearestRayCastCallback : public PhysicsRayCastCallback -{ -public: - PhysicsDemoNearestRayCastCallback(); - -private: - float _friction; -}; - -PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() -: _friction(1.0f) -{ - report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool - { - if (_friction > info.fraction) - { - *((Point*)data) = info.contact; - _friction = info.fraction; - } - - return true; - }; -} - -namespace -{ - static const int MAX_MULTI_RAYCAST_NUM = 5; -} - -class PhysicsDemoMultiRayCastCallback : public PhysicsRayCastCallback -{ -public: - PhysicsDemoMultiRayCastCallback(); - -public: - Point points[MAX_MULTI_RAYCAST_NUM]; - int num; -}; - -PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() -: num(0) -{ - report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool - { - if (num < MAX_MULTI_RAYCAST_NUM) - { - points[num++] = info.contact; - } - - return true; - }; -} - void PhysicsDemoRayCast::update(float delta) { float L = 150.0f; @@ -674,11 +621,10 @@ void PhysicsDemoRayCast::update(float delta) { case 0: { - PhysicsRayCastCallback callback; Point point3 = point2; - callback.report = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); + auto func = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _scene->getPhysicsWorld()->rayCast(func, point1, point2, &point3); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) @@ -691,10 +637,20 @@ void PhysicsDemoRayCast::update(float delta) } case 1: { - PhysicsDemoNearestRayCastCallback callback; Point point3 = point2; + float friction = 1.0f; + PhysicsRayCastCallbackFunc func = [&point3, &friction](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool + { + if (friction > info.fraction) + { + point3 = info.contact; + friction = info.fraction; + } + + return true; + }; - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) @@ -707,15 +663,27 @@ void PhysicsDemoRayCast::update(float delta) } case 2: { - PhysicsDemoMultiRayCastCallback callback; +#define MAX_MULTI_RAYCAST_NUM 5 + Point points[MAX_MULTI_RAYCAST_NUM]; + int num = 0; - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, nullptr); + PhysicsRayCastCallbackFunc func = [&points, &num](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool + { + if (num < MAX_MULTI_RAYCAST_NUM) + { + points[num++] = info.contact; + } + + return true; + }; + + _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point2, 1, STATIC_COLOR); - for (int i = 0; i < callback.num; ++i) + for (int i = 0; i < num; ++i) { - _node->drawDot(callback.points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + _node->drawDot(points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); } addChild(_node); @@ -1089,7 +1057,7 @@ void PhysicsDemoSlice::onEnter() addChild(box); } -bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastCallback::Info &info, void *data) +bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastInfo& info, void *data) { if (info.shape->getBody()->getTag() != _sliceTag) { @@ -1156,9 +1124,8 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) { - PhysicsRayCastCallback callback; - callback.report = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); - _scene->getPhysicsWorld()->rayCast(callback, touch->getStartLocation(), touch->getLocation(), nullptr); + auto func = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); + _scene->getPhysicsWorld()->rayCast(func, touch->getStartLocation(), touch->getLocation(), nullptr); } std::string PhysicsDemoSlice::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 7355045cad..5235f92e34 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -96,7 +96,7 @@ public: void changeModeCallback(Object* sender); - bool anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); + bool anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data); private: float _angle; @@ -150,7 +150,7 @@ public: std::string title() override; std::string subtitle() override; - bool slice(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); + bool slice(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data); void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); bool onTouchBegan(Touch *touch, Event *event); From c9f814c0160023bb90f44025ca733dd889c66c75 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 7 Nov 2013 16:39:41 +0800 Subject: [PATCH 116/197] fix Accelerometer Test with missing: Device::setAccelerometerEnabled(true); --- .../Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp | 1 + samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 2 ++ samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp | 1 + samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 1 + 4 files changed, 5 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index db535fe321..8ca2430219 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -32,6 +32,7 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index e0c4ba23ed..0d52bdde86 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -20,6 +20,7 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -60,6 +61,7 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 50d5dc7252..fbc07ca9c3 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -26,6 +26,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index db51829b3f..3184565698 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -210,6 +210,7 @@ void PhysicsDemoClickAdd::onEnter() touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); From 9f5095b9c35171bdd962a9bb37c8239534358abd Mon Sep 17 00:00:00 2001 From: samuele3 Date: Thu, 7 Nov 2013 16:43:04 +0800 Subject: [PATCH 117/197] Reslove the compiled error --- cocos/gui/UITextField.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 2eabd208b2..7eb30518cd 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -586,7 +586,7 @@ void UITextField::copySpecialProperties(UIWidget *widget) setText(textField->_textFieldRenderer->getString()); setPlaceHolder(textField->getStringValue()); setFontSize(textField->_textFieldRenderer->getFontSize()); - setFontName(textField->_textFieldRenderer->getFontName()); + setFontName(textField->_textFieldRenderer->getFontName().c_str()); setMaxLengthEnabled(textField->isMaxLengthEnabled()); setMaxLength(textField->getMaxLength()); setPasswordEnabled(textField->isPasswordEnabled()); From 9f2297a5a6502f26ab6df1a70db293e9e3ee989f Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 16:46:41 +0800 Subject: [PATCH 118/197] add "retain" to listeners --- cocos/gui/UICheckBox.cpp | 6 +++++- cocos/gui/UIPageView.cpp | 5 +++++ cocos/gui/UIScrollView.cpp | 6 +++++- cocos/gui/UISlider.cpp | 6 +++++- cocos/gui/UITextField.cpp | 5 +++++ cocos/gui/UIWidget.cpp | 21 ++++++++++--------- cocos/gui/UIWidget.h | 6 ------ .../CocoStudioGUITest/UIScene.cpp | 3 +++ 8 files changed, 39 insertions(+), 19 deletions(-) diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index a826fa40ef..c577a86fe6 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -51,7 +51,9 @@ _frontCrossDisabledFileName("") UICheckBox::~UICheckBox() { - + CC_SAFE_RELEASE(_selectedStateEventListener); + _selectedStateEventListener = NULL; + _selectedStateEventSelector = NULL; } UICheckBox* UICheckBox::create() @@ -300,7 +302,9 @@ void UICheckBox::unSelectedEvent() void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { + CC_SAFE_RELEASE(_selectedStateEventListener); _selectedStateEventListener = target; + CC_SAFE_RETAIN(_selectedStateEventListener); _selectedStateEventSelector = selector; } diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 8498e79d88..bb88e6cb80 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -51,6 +51,9 @@ UIPageView::~UIPageView() { _pages->removeAllObjects(); CC_SAFE_RELEASE(_pages); + CC_SAFE_RELEASE(_eventListener); + _eventListener = NULL; + _eventSelector = NULL; } UIPageView* UIPageView::create() @@ -571,7 +574,9 @@ void UIPageView::pageTurningEvent() void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { + CC_SAFE_RELEASE(_eventListener); _eventListener = target; + CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 1270c78682..2654eeda53 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -76,7 +76,9 @@ _eventSelector(NULL) UIScrollView::~UIScrollView() { - + CC_SAFE_RELEASE(_eventListener); + _eventListener = NULL; + _eventSelector = NULL; } UIScrollView* UIScrollView::create() @@ -1529,7 +1531,9 @@ void UIScrollView::bounceRightEvent() void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { + CC_SAFE_RELEASE(_eventListener); _eventListener = target; + CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index f3c0a90b97..d5e0eac9ae 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -58,7 +58,9 @@ _ballDTexType(UI_TEX_TYPE_LOCAL) UISlider::~UISlider() { - + CC_SAFE_RELEASE(_slidPercentListener); + _slidPercentListener = NULL; + _slidPercentSelector = NULL; } UISlider* UISlider::create() @@ -412,7 +414,9 @@ float UISlider::getPercentWithBallPos(float px) void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { + CC_SAFE_RELEASE(_slidPercentListener); _slidPercentListener = target; + CC_SAFE_RETAIN(_slidPercentListener); _slidPercentSelector = selector; } diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 2eabd208b2..68f4c1c75b 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -283,6 +283,9 @@ _passwordStyleText("") UITextField::~UITextField() { + CC_SAFE_RELEASE(_eventListener); + _eventListener = NULL; + _eventSelector = NULL; } UITextField* UITextField::create() @@ -504,7 +507,9 @@ void UITextField::deleteBackwardEvent() void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { + CC_SAFE_RELEASE(_eventListener); _eventListener = target; + CC_SAFE_RETAIN(_eventListener); _eventSelector = selecor; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 00ee50680c..3f93746594 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -75,7 +75,15 @@ _isRunning(false) UIWidget::~UIWidget() { - releaseResoures(); + CCLOG("widget aa"); + CC_SAFE_RELEASE(_touchEventListener); + _touchEventListener = NULL; + _touchEventSelector = NULL; + removeAllChildren(); + _children->release(); + _renderer->removeAllChildrenWithCleanup(true); + _renderer->removeFromParentAndCleanup(true); + _renderer->release(); setParent(NULL); _layoutParameterDictionary->removeAllObjects(); CC_SAFE_RELEASE(_layoutParameterDictionary); @@ -116,15 +124,6 @@ bool UIWidget::init() return true; } -void UIWidget::releaseResoures() -{ - removeAllChildren(); - _children->release(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); -} - void UIWidget::onEnter() { arrayMakeObjectsPerformSelector(_children, onEnter, UIWidget*); @@ -700,7 +699,9 @@ void UIWidget::longClickEvent() void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { + CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = target; + CC_SAFE_RETAIN(_touchEventListener); _touchEventSelector = selector; } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index d8f35578f4..f4f48f2a94 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -907,12 +907,6 @@ protected: void cancelUpEvent(); void longClickEvent(); void updateAnchorPoint(); - /** - * Release texture resoures of widget. - * Release renderer. - * If you override releaseResoures, you shall call its parent's one, e.g. UIWidget::releaseResoures(). - */ - virtual void releaseResoures(); void updateSizeAndPosition(); void copyProperties(UIWidget* model); virtual UIWidget* createCloneInstance(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index 38344c9490..cc95546ca1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -74,6 +74,7 @@ void UIScene::previousCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->previousUIScene()); } } @@ -82,6 +83,7 @@ void UIScene::restartCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->currentUIScene()); } } @@ -90,6 +92,7 @@ void UIScene::nextCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->nextUIScene()); } } From b5f83c30b66b696c02725ddaa1237ad064ace846 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 7 Nov 2013 17:08:16 +0800 Subject: [PATCH 119/197] fix indention --- .../TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp | 2 +- samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 4 ++-- samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp | 2 +- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index 8ca2430219..5bc3d6a7ed 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -32,7 +32,7 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index 0d52bdde86..b7a60bb7a8 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -20,7 +20,7 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -61,7 +61,7 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index fbc07ca9c3..4a4cd5e027 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -26,7 +26,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 3184565698..2ef3f4fc4a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -210,7 +210,7 @@ void PhysicsDemoClickAdd::onEnter() touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); From a116e7ec79b786bcddfba4c8ffb2761f8a420622 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 7 Nov 2013 09:11:22 +0000 Subject: [PATCH 120/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f55eab57aa..52e968dfe0 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f55eab57aa6b3ff20fd33bea986e4569ebd68c8e +Subproject commit 52e968dfe02f077f56d4df6cc04e38c8b76e22b9 From e2249c8c3f4bebd788e06699f2b7584f51cecfd2 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 17:15:52 +0800 Subject: [PATCH 121/197] Fixed crash --- cocos/gui/UIInputManager.cpp | 8 ++++---- cocos/gui/UIWidget.cpp | 1 - .../CocoStudioGUITest/CocosGUIScene.cpp | 13 +------------ .../ExtensionsTest/CocoStudioGUITest/UIScene.cpp | 1 + 4 files changed, 6 insertions(+), 17 deletions(-) diff --git a/cocos/gui/UIInputManager.cpp b/cocos/gui/UIInputManager.cpp index bb36043855..a1c6659557 100644 --- a/cocos/gui/UIInputManager.cpp +++ b/cocos/gui/UIInputManager.cpp @@ -176,10 +176,10 @@ void UIInputManager::onTouchEnd(Touch* touch) int length = selectedWidgetArray->num; for (int i=0; iarr[i]); + UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); + _selectedWidgets->removeObject(hitWidget); hitWidget->onTouchEnded(_touchEndedPoint); } - _selectedWidgets->removeAllObjects(); } void UIInputManager::onTouchCancelled(Touch* touch) @@ -191,10 +191,10 @@ void UIInputManager::onTouchCancelled(Touch* touch) int length = selectedWidgetArray->num; for (int i=0; iarr[i]); + UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); + _selectedWidgets->removeObject(hitWidget); hitWidget->onTouchCancelled(_touchEndedPoint); } - _selectedWidgets->removeAllObjects(); } void UIInputManager::setRootWidget(UIWidget *root) diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 3f93746594..7f2adc545a 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -75,7 +75,6 @@ _isRunning(false) UIWidget::~UIWidget() { - CCLOG("widget aa"); CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = NULL; _touchEventSelector = NULL; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 750b562a67..43a15715c8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -25,17 +25,7 @@ void CocosGUITestScene::runThisTest() { Director::getInstance()->replaceScene(this); - - ul = UILayer::create(); - ul->scheduleUpdate(); - this->addChild(ul); - - /* - Layout* layout = static_cast(CCUIHELPER->createWidgetFromJsonFile("cocosgui/UI/UI01.json")); - ul->addWidget(layout); - */ - -// /* + Size s = CCDirector::getInstance()->getWinSize(); _itemMenu = CCMenu::create(); @@ -56,7 +46,6 @@ void CocosGUITestScene::runThisTest() } void CocosGUITestScene::MainMenuCallback(Object* pSender) { - ul->removeFromParent(); ExtensionsTestScene *pScene = new ExtensionsTestScene(); pScene->runThisTest(); pScene->release(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index cc95546ca1..a2a3ddcf42 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -64,6 +64,7 @@ void UIScene::menuCloseCallback(Object* pSender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); auto scene = new ExtensionsTestScene(); scene->runThisTest(); scene->release(); From b9b14571ac3e21f252b1483a101065ccea810d0b Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 7 Nov 2013 17:16:31 +0800 Subject: [PATCH 122/197] fix compiling erros on Android --- cocos/2d/CCUserDefaultAndroid.cpp | 4 +- .../platform/android/CCFileUtilsAndroid.cpp | 40 +++++++++---------- .../2d/platform/android/CCFileUtilsAndroid.h | 6 +-- cocos/gui/UILayoutDefine.h | 1 - 4 files changed, 25 insertions(+), 26 deletions(-) diff --git a/cocos/2d/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp index 38c09c2a90..db18dd2951 100644 --- a/cocos/2d/CCUserDefaultAndroid.cpp +++ b/cocos/2d/CCUserDefaultAndroid.cpp @@ -74,8 +74,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - unsigned long nSize; - const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); + long size; + const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) { diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp index d15e4f874a..c447b5db32 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp @@ -130,21 +130,21 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const } -unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* pszMode, unsigned long * pSize) +unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* mode, long * size) { - return doGetFileData(filename, pszMode, pSize, false); + return doGetFileData(filename, mode, size, false); } -unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize) +unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, long * pSize) { return doGetFileData(filename, pszMode, pSize, true); } -unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync) +unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* mode, long * size, bool forAsync) { - unsigned char * pData = 0; + unsigned char * data = 0; - if ((! filename) || (! pszMode) || 0 == strlen(filename)) + if ((! filename) || (! mode) || 0 == strlen(filename)) { return 0; } @@ -189,14 +189,14 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* return NULL; } - off_t size = AAsset_getLength(asset); + off_t fileSize = AAsset_getLength(asset); - pData = new unsigned char[size]; + data = new unsigned char[fileSize]; - int bytesread = AAsset_read(asset, (void*)pData, size); - if (pSize) + int bytesread = AAsset_read(asset, (void*)data, fileSize); + if (size) { - *pSize = bytesread; + *size = bytesread; } AAsset_close(asset); @@ -207,32 +207,32 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* { // read rrom other path than user set it //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename); - FILE *fp = fopen(fullPath.c_str(), pszMode); + FILE *fp = fopen(fullPath.c_str(), mode); CC_BREAK_IF(!fp); - unsigned long size; + long fileSize; fseek(fp,0,SEEK_END); - size = ftell(fp); + fileSize = ftell(fp); fseek(fp,0,SEEK_SET); - pData = new unsigned char[size]; - size = fread(pData,sizeof(unsigned char), size,fp); + data = new unsigned char[fileSize]; + fileSize = fread(data,sizeof(unsigned char), fileSize,fp); fclose(fp); - if (pSize) + if (size) { - *pSize = size; + *size = fileSize; } } while (0); } - if (! pData) + if (! data) { std::string msg = "Get data from file("; msg.append(filename).append(") failed!"); CCLOG("%s", msg.c_str()); } - return pData; + return data; } string FileUtilsAndroid::getWritablePath() const diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.h b/cocos/2d/platform/android/CCFileUtilsAndroid.h index 87a2445f48..3bee6d2e39 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.h +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.h @@ -55,7 +55,7 @@ public: /* override funtions */ bool init(); - virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize); + virtual unsigned char* getFileData(const char* filename, const char* mode, long * size); virtual std::string getWritablePath() const; virtual bool isFileExist(const std::string& strFilePath) const; @@ -64,10 +64,10 @@ public: /** This function is android specific. It is used for TextureCache::addImageAsync(). Don't use it in your codes. */ - unsigned char* getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize); + unsigned char* getFileDataForAsync(const char* filename, const char* mode, long * size); private: - unsigned char* doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync); + unsigned char* doGetFileData(const char* filename, const char* mode, long * size, bool forAsync); static AAssetManager* assetmanager; }; diff --git a/cocos/gui/UILayoutDefine.h b/cocos/gui/UILayoutDefine.h index 0b772837ca..70ab70251f 100644 --- a/cocos/gui/UILayoutDefine.h +++ b/cocos/gui/UILayoutDefine.h @@ -26,7 +26,6 @@ #define __UILAYOUTDEFINE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" namespace gui { /** From e278ad66c80ec24f047a6b007893dbaa90a89e70 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 17:46:05 +0800 Subject: [PATCH 123/197] issue #2771: change PhysicsJoint::create() to PhysicsJoint::construct() --- cocos/physics/CCPhysicsJoint.cpp | 10 +++++----- cocos/physics/CCPhysicsJoint.h | 12 ++++++------ .../TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 16 ++++++++-------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 2e037cf2f5..578b8fefc7 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -214,7 +214,7 @@ void PhysicsJoint::destroy(PhysicsJoint* joint) } } -PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) +PhysicsJointFixed* PhysicsJointFixed::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointFixed* joint = new PhysicsJointFixed(); @@ -255,7 +255,7 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) return false; } -PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) +PhysicsJointPin* PhysicsJointPin::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointPin* joint = new PhysicsJointPin(); @@ -296,7 +296,7 @@ float PhysicsJointPin::getMaxForce() const return PhysicsHelper::cpfloat2float(_info->getJoints().front()->maxForce); } -PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) +PhysicsJointSliding* PhysicsJointSliding::construct(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) { PhysicsJointSliding* joint = new PhysicsJointSliding(); @@ -331,7 +331,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo } -PhysicsJointLimit* PhysicsJointLimit::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +PhysicsJointLimit* PhysicsJointLimit::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { PhysicsJointLimit* joint = new PhysicsJointLimit(); @@ -386,7 +386,7 @@ void PhysicsJointLimit::setMax(float max) cpSlideJointSetMax(_info->getJoints().front(), PhysicsHelper::float2cpfloat(max)); } -PhysicsJointDistance* PhysicsJointDistance::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +PhysicsJointDistance* PhysicsJointDistance::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { PhysicsJointDistance* joint = new PhysicsJointDistance(); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 55befaf328..789d64a5b2 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -89,7 +89,7 @@ protected: class PhysicsJointFixed : public PhysicsJoint { public: - static PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointFixed* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); @@ -105,7 +105,7 @@ protected: class PhysicsJointSliding : public PhysicsJoint { public: - static PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); + static PhysicsJointSliding* construct(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); @@ -121,7 +121,7 @@ protected: class PhysicsJointSpring : public PhysicsJoint { public: - PhysicsJointSpring* create(); + PhysicsJointSpring* construct(); protected: bool init(); @@ -137,7 +137,7 @@ protected: class PhysicsJointLimit : public PhysicsJoint { public: - PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + PhysicsJointLimit* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); float getMin() const; void setMin(float min); @@ -158,7 +158,7 @@ protected: class PhysicsJointPin : public PhysicsJoint { public: - static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointPin* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr); void setMaxForce(float force); float getMaxForce() const; @@ -175,7 +175,7 @@ class PhysicsJointDistance : public PhysicsJoint { public: - static PhysicsJointDistance* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + static PhysicsJointDistance* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index af27626949..f635e4541f 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -403,7 +403,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); - PhysicsJointPin* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + PhysicsJointPin* joint = PhysicsJointPin::construct(mouse->getPhysicsBody(), shape->getBody(), location); joint->setMaxForce(5000.0f * shape->getBody()->getMass()); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); @@ -765,7 +765,7 @@ void PhysicsDemoJoints::onEnter() auto sp2 = makeBall(offset + Point(30, 0), 10); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - PhysicsJointPin* joint = PhysicsJointPin::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + PhysicsJointPin* joint = PhysicsJointPin::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -780,7 +780,7 @@ void PhysicsDemoJoints::onEnter() auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - PhysicsJointFixed* joint = PhysicsJointFixed::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -895,7 +895,7 @@ void PhysicsDemoPump::onEnter() sgearB->setCategoryBitmask(0x04); sgearB->setCollisionBitmask(0x04); sgearB->setTag(1); - _world->addJoint(PhysicsJointPin::create(body, sgearB, sgearB->getPosition())); + _world->addJoint(PhysicsJointPin::construct(body, sgearB, sgearB->getPosition())); // big gear @@ -905,7 +905,7 @@ void PhysicsDemoPump::onEnter() bgear->setPosition(VisibleRect::leftBottom() + Point(275, 0)); this->addChild(bgear); bgearB->setCategoryBitmask(0x04); - _world->addJoint(PhysicsJointPin::create(body, bgearB, bgearB->getPosition())); + _world->addJoint(PhysicsJointPin::construct(body, bgearB, bgearB->getPosition())); // pump @@ -917,7 +917,7 @@ void PhysicsDemoPump::onEnter() this->addChild(pump); pumpB->setCategoryBitmask(0x02); pumpB->setGravityEnable(false); - _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -44))); + _world->addJoint(PhysicsJointDistance::construct(pumpB, sgearB, Point(0, 0), Point(0, -44))); // plugger Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; @@ -934,8 +934,8 @@ void PhysicsDemoPump::onEnter() this->addChild(plugger); pluggerB->setCategoryBitmask(0x02); sgearB->setCollisionBitmask(0x04 | 0x01); - _world->addJoint(PhysicsJointPin::create(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); - _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); + _world->addJoint(PhysicsJointPin::construct(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); + _world->addJoint(PhysicsJointDistance::construct(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); } void PhysicsDemoPump::update(float delta) From 3e8871f2c962d554685b52e3a742a963f175f21a Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 17:53:30 +0800 Subject: [PATCH 124/197] issue #2771: delete some unfinished PhysicsTest and change subtitle --- .../Classes/PhysicsTest/PhysicsTest.cpp | 54 +++---------------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 17 +----- 2 files changed, 8 insertions(+), 63 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f635e4541f..c97b377709 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -6,7 +6,6 @@ namespace { static std::function createFunctions[] = { CL(PhysicsDemoLogoSmash), - CL(PhysicsDemoPyramidStack), CL(PhysicsDemoPlink), CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), @@ -481,42 +480,6 @@ std::string PhysicsDemoLogoSmash::title() return "Logo Smash"; } -void PhysicsDemoPyramidStack::onEnter() -{ - PhysicsDemo::onEnter(); - - auto touchListener = EventListenerTouchOneByOne::create(); - touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchBegan, this); - touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchMoved, this); - touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchEnded, this); - _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - - auto node = Node::create(); - node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); - this->addChild(node); - - auto ball = Sprite::create("Images/ball.png"); - ball->setScale(1); - ball->setPhysicsBody(PhysicsBody::createCircle(10)); - ball->setPosition(VisibleRect::bottom() + Point(0, 60)); - this->addChild(ball); - - for(int i=0; i<14; i++) - { - for(int j=0; j<=i; j++) - { - auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); - - sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - } - } -} -std::string PhysicsDemoPyramidStack::title() -{ - return "Pyramid Stack"; -} - - void PhysicsDemoPlink::onEnter() { PhysicsDemo::onEnter(); @@ -995,6 +958,11 @@ std::string PhysicsDemoPump::title() return "Pump"; } +std::string PhysicsDemoPump::subtitle() +{ + return "open debug to see it"; +} + void PhysicsDemoOneWayPlatform::onEnter() { PhysicsDemo::onEnter(); @@ -1135,15 +1103,5 @@ std::string PhysicsDemoSlice::title() std::string PhysicsDemoSlice::subtitle() { - return "click and drag to slice up the block"; -} - -void PhysicsDemoWater::onEnter() -{ - PhysicsDemo::onEnter(); -} - -std::string PhysicsDemoWater::title() -{ - return "Water"; + return "click and drag to slice up the block, open debug to see it"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 5235f92e34..4ca37bd77b 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -70,13 +70,6 @@ public: std::string title() override; }; -class PhysicsDemoPyramidStack : public PhysicsDemo -{ -public: - void onEnter() override; - std::string title() override; -}; - class PhysicsDemoPlink : public PhysicsDemo { public: @@ -122,8 +115,9 @@ class PhysicsDemoPump : public PhysicsDemo { public: void onEnter() override; - std::string title() override; void update(float delta) override; + std::string title() override; + std::string subtitle() override; bool onTouchBegan(Touch* touch, Event* event); void onTouchMoved(Touch* touch, Event* event); @@ -161,11 +155,4 @@ private: int _sliceTag; }; -class PhysicsDemoWater : public PhysicsDemo -{ -public: - void onEnter() override; - std::string title() override; -}; - #endif From 99546cef4686babdfbd208bea5fd6c441f604368 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 18:52:36 +0800 Subject: [PATCH 125/197] issue #3025: add getTextureCache() in CCdirector() --- cocos/2d/CCDirector.cpp | 28 +++++++++++++++++++++++++++- cocos/2d/CCDirector.h | 10 ++++++++++ cocos/2d/CCTextureCache.cpp | 27 +++++++++------------------ cocos/2d/CCTextureCache.h | 4 ++++ 4 files changed, 50 insertions(+), 19 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 130d170d30..b55bec2446 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -145,6 +145,8 @@ bool Director::init(void) _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); + //init TextureCache + initTextureCache(); // create autorelease pool PoolManager::sharedPoolManager()->push(); @@ -359,6 +361,29 @@ void Director::setOpenGLView(EGLView *pobOpenGLView) } } +TextureCache* Director::getTextureCache() const +{ + return _textureCache; +} + +void Director::initTextureCache() +{ +#ifdef EMSCRIPTEN + _textureCache = new TextureCacheEmscripten(); +#else + _textureCache = new TextureCache(); +#endif // EMSCRIPTEN +} + +void Director::destroyTextureCache() +{ + if (_textureCache) + { + _textureCache->waitForQuit(); + CC_SAFE_RELEASE_NULL(_textureCache); + } +} + void Director::setViewport() { if (_openGLView) @@ -693,7 +718,6 @@ void Director::purgeDirector() DrawPrimitives::free(); AnimationCache::destroyInstance(); SpriteFrameCache::destroyInstance(); - TextureCache::destroyInstance(); ShaderCache::destroyInstance(); FileUtils::destroyInstance(); Configuration::destroyInstance(); @@ -704,6 +728,8 @@ void Director::purgeDirector() GL::invalidateStateCache(); + destroyTextureCache(); + CHECK_GL_ERROR_DEBUG(); // OpenGL view diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index b01b0fe954..0eb4b5d390 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -54,6 +54,7 @@ class Node; class Scheduler; class ActionManager; class EventDispatcher; +class TextureCache; /** @brief Class that creates and handles the main Window and manages how @@ -137,6 +138,8 @@ public: inline EGLView* getOpenGLView() { return _openGLView; } void setOpenGLView(EGLView *pobOpenGLView); + TextureCache* getTextureCache() const; + inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; } void setNextDeltaTimeZero(bool nextDeltaTimeZero); @@ -381,6 +384,10 @@ protected: /** calculates delta time since last time it was called */ void calculateDeltaTime(); + //textureCache creation or release + void initTextureCache(); + void destroyTextureCache(); + protected: /** Scheduler associated with this director @since v2.0 @@ -403,6 +410,9 @@ protected: /* The EGLView, where everything is rendered */ EGLView *_openGLView; + //texture cache belongs to this director + TextureCache *_textureCache; + double _animationInterval; double _oldAnimationInterval; diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 8f3fc6fe3a..cf1e8887f9 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -55,15 +55,7 @@ TextureCache* TextureCache::_sharedTextureCache = nullptr; TextureCache * TextureCache::getInstance() { - if (!_sharedTextureCache) - { -#ifdef EMSCRIPTEN - _sharedTextureCache = new TextureCacheEmscripten(); -#else - _sharedTextureCache = new TextureCache(); -#endif // EMSCRIPTEN - } - return _sharedTextureCache; + return Director::getInstance()->getTextureCache(); } TextureCache::TextureCache() @@ -89,15 +81,6 @@ TextureCache::~TextureCache() void TextureCache::destroyInstance() { - if (_sharedTextureCache) - { - // notify sub thread to quick - _sharedTextureCache->_needQuit = true; - _sharedTextureCache->_sleepCondition.notify_one(); - if (_sharedTextureCache->_loadingThread) _sharedTextureCache->_loadingThread->join(); - - CC_SAFE_RELEASE_NULL(_sharedTextureCache); - } } const char* TextureCache::description() const @@ -443,6 +426,14 @@ void TextureCache::reloadAllTextures() #endif } +void TextureCache::waitForQuit() +{ + // notify sub thread to quick + _needQuit = true; + _sleepCondition.notify_one(); + if (_loadingThread) _loadingThread->join(); +} + void TextureCache::dumpCachedTextureInfo() const { unsigned int count = 0; diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index ec87d891d8..1dcc96eb3e 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -158,6 +158,10 @@ public: */ void dumpCachedTextureInfo() const; + //wait for texture cahe to quit befor destroy instance + //called by director, please do not called outside + void waitForQuit(); + private: void addImageAsyncCallBack(float dt); void loadImage(); From c8fe6077aad9811ea19d1154ad94a15636bd49cf Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 19:10:14 +0800 Subject: [PATCH 126/197] issue #3025: Deprecate TextureCache::getInstance() destroyInstance() --- cocos/2d/CCTextureCache.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 1dcc96eb3e..7916696513 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -59,7 +59,7 @@ class CC_DLL TextureCache : public Object { public: /** Returns the shared instance of the cache */ - static TextureCache * getInstance(); + CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance(); /** @deprecated Use getInstance() instead */ CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache() { return TextureCache::getInstance(); } @@ -67,7 +67,7 @@ public: /** purges the cache. It releases the retained instance. @since v0.99.0 */ - static void destroyInstance(); + CC_DEPRECATED_ATTRIBUTE static void destroyInstance(); /** @deprecated Use destroyInstance() instead */ CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } From 99bcca0532df738b3ac1a9e33c45a42a3d9c580b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 19:11:09 +0800 Subject: [PATCH 127/197] issue #3025: replace TextureCache::getInstance() by Director::getInstance()->getTextureCache() in cocos folder --- cocos/2d/CCAnimation.cpp | 3 ++- cocos/2d/CCAtlasNode.cpp | 2 +- cocos/2d/CCDirector.cpp | 4 ++-- cocos/2d/CCFontFNT.cpp | 4 ++-- cocos/2d/CCLabelAtlas.cpp | 2 +- cocos/2d/CCLabelBMFont.cpp | 4 ++-- cocos/2d/CCMotionStreak.cpp | 4 ++-- cocos/2d/CCParticleBatchNode.cpp | 2 +- cocos/2d/CCParticleExamples.cpp | 4 ++-- cocos/2d/CCParticleSystem.cpp | 6 +++--- cocos/2d/CCSprite.cpp | 10 +++++----- cocos/2d/CCSpriteBatchNode.cpp | 2 +- cocos/2d/CCSpriteFrame.cpp | 2 +- cocos/2d/CCSpriteFrameCache.cpp | 5 +++-- cocos/2d/CCTMXLayer.cpp | 2 +- cocos/2d/CCTextureAtlas.cpp | 3 ++- cocos/editor-support/cocosbuilder/CCBReader.cpp | 2 +- cocos/editor-support/cocosbuilder/CCNodeLoader.cpp | 4 ++-- cocos/editor-support/spine/spine-cocos2dx.cpp | 2 +- 19 files changed, 35 insertions(+), 32 deletions(-) diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 5fa37cd85c..ca1c949882 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "CCTexture2D.h" #include "ccMacros.h" #include "CCSpriteFrame.h" +#include "CCDirector.h" NS_CC_BEGIN @@ -176,7 +177,7 @@ void Animation::addSpriteFrame(SpriteFrame *pFrame) void Animation::addSpriteFrameWithFile(const char *filename) { - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect); diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 6922a8f7ca..7ced2ffc9d 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -76,7 +76,7 @@ AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tile bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { CCASSERT(tile.size() > 0, "file size should not be empty"); - Texture2D *texture = TextureCache::getInstance()->addImage(tile); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(tile); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); } diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index b55bec2446..5a10d83d1e 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -462,7 +462,7 @@ void Director::purgeCachedData(void) if (s_SharedDirector->getOpenGLView()) { SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); - TextureCache::getInstance()->removeUnusedTextures(); + _textureCache->removeUnusedTextures(); } FileUtils::getInstance()->purgeCachedEntries(); } @@ -867,7 +867,7 @@ void Director::getFPSImageData(unsigned char** datapointer, long* length) void Director::createStatsLabel() { Texture2D *texture = nullptr; - TextureCache *textureCache = TextureCache::getInstance(); + TextureCache *textureCache = _textureCache; if (_FPSLabel && _SPFLabel) { diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 1992b4f828..25709c714e 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -34,7 +34,7 @@ FontFNT * FontFNT::create(const std::string& fntFilePath) return nullptr; // add the texture - Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName()); + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName()); if (!tempTexture) { delete newConf; @@ -198,7 +198,7 @@ FontAtlas * FontFNT::createFontAtlas() // add the texture (only one texture for now) - Texture2D *tempTexture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()); if (!tempTexture) return 0; diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 56a6ff723b..119492b062 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -56,7 +56,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& cha bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) { - Texture2D *texture = TextureCache::getInstance()->addImage(charMapFile); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(charMapFile); return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index e28d4d0afc..6e1a9aefda 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -486,7 +486,7 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string _fntFile = fntFile; - texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); + texture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()); } else { @@ -1213,7 +1213,7 @@ void LabelBMFont::setFntFile(const char* fntFile) CC_SAFE_RELEASE(_configuration); _configuration = newConf; - this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName())); + this->setTexture(Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName())); this->createFontChars(); } } diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 47cb43a207..14920662ce 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCGLProgram.h" #include "CCShaderCache.h" #include "ccMacros.h" - +#include "CCDirector.h" #include "CCVertex.h" NS_CC_BEGIN @@ -93,7 +93,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co { CCASSERT(path != NULL, "Invalid filename"); - Texture2D *texture = TextureCache::getInstance()->addImage(path); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path); return initWithFade(fade, minSeg, stroke, color, texture); } diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 788fdd221c..cd473bf097 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -111,7 +111,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity) */ bool ParticleBatchNode::initWithFile(const char* fileImage, unsigned int capacity) { - Texture2D *tex = TextureCache::getInstance()->addImage(fileImage); + Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage); return initWithTexture(tex, capacity); } diff --git a/cocos/2d/CCParticleExamples.cpp b/cocos/2d/CCParticleExamples.cpp index c7e2946172..7120c4b821 100644 --- a/cocos/2d/CCParticleExamples.cpp +++ b/cocos/2d/CCParticleExamples.cpp @@ -42,7 +42,7 @@ static Texture2D* getDefaultTexture() { bool bRet = false; const char* key = "/__firePngData"; - texture = TextureCache::getInstance()->getTextureForKey(key); + texture = Director::getInstance()->getTextureCache()->getTextureForKey(key); CC_BREAK_IF(texture != NULL); pImage = new Image(); @@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture() bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData)); CC_BREAK_IF(!bRet); - texture = TextureCache::getInstance()->addImage(pImage, key); + texture = Director::getInstance()->getTextureCache()->addImage(pImage, key); } while (0); CC_SAFE_RELEASE(pImage); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 21c473f2f2..cb2c4326f3 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -374,7 +374,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin // set not pop-up message box when load image failed bool bNotify = FileUtils::getInstance()->isPopupNotify(); FileUtils::getInstance()->setPopupNotify(false); - tex = TextureCache::getInstance()->addImage(textureName.c_str()); + tex = Director::getInstance()->getTextureCache()->addImage(textureName.c_str()); // reset the value of UIImage notify FileUtils::getInstance()->setPopupNotify(bNotify); } @@ -400,13 +400,13 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); - // For android, we should retain it in VolatileTexture::addImage which invoked in TextureCache::getInstance()->addUIImage() + // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage() image = new Image(); bool isOK = image->initWithImageData(deflated, deflatedLen); CCASSERT(isOK, "CCParticleSystem: error init image with Data"); CC_BREAK_IF(!isOK); - setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str())); + setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str())); image->release(); } diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index fa6f4878b0..98680b0ea3 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -219,7 +219,7 @@ bool Sprite::initWithFile(const std::string& filename) { CCASSERT(filename.size()>0, "Invalid filename for sprite"); - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); if (texture) { Rect rect = Rect::ZERO; @@ -237,7 +237,7 @@ bool Sprite::initWithFile(const std::string &filename, const Rect& rect) { CCASSERT(filename.size()>0, "Invalid filename"); - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); if (texture) { return initWithTexture(texture, rect); @@ -284,7 +284,7 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey) CCASSERT(pImage != NULL); // XXX: possible bug. See issue #349. New API should be added - Texture2D *texture = TextureCache::getInstance()->addCGImage(pImage, pszKey); + Texture2D *texture = Director::getInstance()->getTextureCache()->addCGImage(pImage, pszKey); const Size& size = texture->getContentSize(); Rect rect = Rect(0 ,0, size.width, size.height); @@ -1107,7 +1107,7 @@ void Sprite::setTexture(Texture2D *texture) if (NULL == texture) { // Gets the texture by key firstly. - texture = TextureCache::getInstance()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); + texture = Director::getInstance()->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); // If texture wasn't in cache, create it from RAW data. if (NULL == texture) @@ -1116,7 +1116,7 @@ void Sprite::setTexture(Texture2D *texture) bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8); CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully."); - texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); + texture = Director::getInstance()->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); CC_SAFE_RELEASE(image); } } diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 820a999401..f13a306aa2 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -114,7 +114,7 @@ bool SpriteBatchNode::init() */ bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity) { - Texture2D *texture2D = TextureCache::getInstance()->addImage(fileImage); + Texture2D *texture2D = Director::getInstance()->getTextureCache()->addImage(fileImage); return initWithTexture(texture2D, capacity); } diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index d2fd2c2495..06ca1b80c5 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -180,7 +180,7 @@ Texture2D* SpriteFrame::getTexture(void) } if( _textureFilename.length() > 0 ) { - return TextureCache::getInstance()->addImage(_textureFilename.c_str()); + return Director::getInstance()->getTextureCache()->addImage(_textureFilename.c_str()); } // no texture or texture filename return NULL; diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 7ab33b85fe..f5afd18f76 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -37,6 +37,7 @@ THE SOFTWARE. #include "CCString.h" #include "CCArray.h" #include "CCDictionary.h" +#include "CCDirector.h" #include using namespace std; @@ -215,7 +216,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Text void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) { CCASSERT(textureFileName.size()>0, "texture name should not be null"); - Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(textureFileName); if (texture) { @@ -265,7 +266,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str()); } - Texture2D *texture = TextureCache::getInstance()->addImage(texturePath.c_str()); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(texturePath.c_str()); if (texture) { diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 4b801ea83e..aa48b8b2b4 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -58,7 +58,7 @@ bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *la Texture2D *texture = NULL; if( tilesetInfo ) { - texture = TextureCache::getInstance()->addImage(tilesetInfo->_sourceImage.c_str()); + texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage.c_str()); } if (SpriteBatchNode::initWithTexture(texture, (unsigned int)capacity)) diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index 3ef2a365c4..f19a2f5f87 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -32,6 +32,7 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "CCNotificationCenter.h" #include "CCEventType.h" +#include "CCDirector.h" #include "CCGL.h" // support #include "CCTexture2D.h" @@ -134,7 +135,7 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity bool TextureAtlas::initWithFile(const char * file, long capacity) { // retained in property - Texture2D *texture = TextureCache::getInstance()->addImage(file); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file); if (texture) { diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 154d2b0b36..5dd2a20624 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -833,7 +833,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) { spriteFile = _CCBRootPath + spriteFile; - Texture2D *texture = TextureCache::getInstance()->addImage(spriteFile.c_str()); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index e82764ce86..7eba8e9340 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -577,7 +577,7 @@ SpriteFrame * NodeLoader::parsePropTypeSpriteFrame(Node * pNode, Node * pParent, if (spriteSheet.length() == 0) { spriteFile = ccbReader->getCCBRootPath() + spriteFile; - Texture2D * texture = TextureCache::getInstance()->addImage(spriteFile.c_str()); + Texture2D * texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); if(texture != NULL) { Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); @@ -635,7 +635,7 @@ Texture2D * NodeLoader::parsePropTypeTexture(Node * pNode, Node * pParent, CCBRe if (spriteFile.length() > 0) { - return TextureCache::getInstance()->addImage(spriteFile.c_str()); + return Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); } else { diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index dbc389db51..298031aaab 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -31,7 +31,7 @@ USING_NS_CC; namespace spine { void _AtlasPage_createTexture (AtlasPage* self, const char* path) { - Texture2D* texture = TextureCache::getInstance()->addImage(path); + Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(path); TextureAtlas* textureAtlas = TextureAtlas::createWithTexture(texture, 4); textureAtlas->retain(); self->rendererObject = textureAtlas; From cee966e28428dbfab97d3e44a66de4c1e3182100 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 19:24:15 +0800 Subject: [PATCH 128/197] issue #2771: fix build error --- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index c97b377709..e1c52d2705 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -1,4 +1,5 @@ #include "PhysicsTest.h" +#include #include "../testResource.h" USING_NS_CC; @@ -1071,7 +1072,7 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float if (aDist*bDist < 0.0f) { - float t = abs(aDist)/(abs(aDist) + abs(bDist)); + float t = std::fabs(aDist)/(std::fabs(aDist) + std::fabs(bDist)); points[pointsCount] = a.lerp(b, t); ++pointsCount; } From cbb9c655d962577f5ed586bfed56b7d1d93a7edf Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 21:10:48 +0800 Subject: [PATCH 129/197] fixed bugs --- .../UILoadingBarTest/UILoadingBarTest.cpp | 83 ++++++++++++++----- 1 file changed, 61 insertions(+), 22 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp index 18b150ef6d..f031bc87e8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp @@ -67,20 +67,29 @@ void UILoadingBarTest_Left::update(float delta) void UILoadingBarTest_Left::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Left::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Left::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Right @@ -142,20 +151,29 @@ void UILoadingBarTest_Right::update(float delta) void UILoadingBarTest_Right::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Right::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Right::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Left_Scale9 @@ -219,20 +237,29 @@ void UILoadingBarTest_Left_Scale9::update(float delta) void UILoadingBarTest_Left_Scale9::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Left_Scale9::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Left_Scale9::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Right_Scale9 @@ -290,22 +317,34 @@ void UILoadingBarTest_Right_Scale9::update(float delta) { m_nCount = 0; } - + CCLOG("wocao"); UILoadingBar* loadingBar = dynamic_cast(m_pUiLayer->getWidgetByName("LoadingBar")); loadingBar->setPercent(m_nCount); } void UILoadingBarTest_Right_Scale9::previousCallback(Object* sender, TouchEventType type) { - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Right_Scale9::restartCallback(Object* sender, TouchEventType type) { - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Right_Scale9::nextCallback(Object* sender, TouchEventType type) { - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } \ No newline at end of file From c69163559b2a0f2a829163be2fb580a47e8aca1d Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 21:26:56 +0800 Subject: [PATCH 130/197] Move some method from helper to reader --- .../cocostudio/CCSGUIReader.cpp | 28 ++++++++++++++++--- .../editor-support/cocostudio/CCSGUIReader.h | 4 +++ cocos/gui/UIHelper.cpp | 23 --------------- cocos/gui/UIHelper.h | 4 --- 4 files changed, 28 insertions(+), 31 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index f799c26752..3ad788b563 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -40,12 +40,13 @@ CCSGUIReader::CCSGUIReader(): m_strFilePath(""), m_bOlderVersion(false) { - + _fileDesignSizes = Dictionary::create(); + CC_SAFE_RETAIN(_fileDesignSizes); } CCSGUIReader::~CCSGUIReader() { - + CC_SAFE_RELEASE(_fileDesignSizes); } CCSGUIReader* CCSGUIReader::shareReader() @@ -197,7 +198,26 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) return widget; } +void CCSGUIReader::storeFileDesignSize(const char *fileName, const cocos2d::Size &size) +{ + if (!_fileDesignSizes) + { + _fileDesignSizes = cocos2d::Dictionary::create(); + _fileDesignSizes->retain(); + } + cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); + _fileDesignSizes->setObject(strSize, fileName); +} +const cocos2d::Size CCSGUIReader::getFileDesignSize(const char* fileName) const +{ + if (!_fileDesignSizes) + { + return cocos2d::Size::ZERO; + } + cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)_fileDesignSizes->objectForKey(fileName))->_string.c_str()); + return designSize; +} UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) { @@ -240,11 +260,11 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); - UIHelper::setFileDesignSize(fileName, winSize); + storeFileDesignSize(fileName, winSize); } else { - UIHelper::setFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); + storeFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h index d39c349ee0..415b7b9e81 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/CCSGUIReader.h @@ -65,9 +65,13 @@ public: void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); void setPropsForDragPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void storeFileDesignSize(const char* fileName, const cocos2d::Size &size); + + const cocos2d::Size getFileDesignSize(const char* fileName) const; protected: std::string m_strFilePath; bool m_bOlderVersion; + cocos2d::Dictionary* _fileDesignSizes; }; } diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index 8b43c8f890..d896a6372c 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -25,8 +25,6 @@ #include "CocosGUI.h" namespace gui { - -static cocos2d::Dictionary* fileDesignSizes = NULL; UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -120,26 +118,5 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) } return NULL; } - -void UIHelper::setFileDesignSize(const char *fileName, const cocos2d::Size &size) -{ - if (!fileDesignSizes) - { - fileDesignSizes = cocos2d::Dictionary::create(); - fileDesignSizes->retain(); - } - cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); - fileDesignSizes->setObject(strSize, fileName); -} - -const cocos2d::Size UIHelper::getFileDesignSize(const char* fileName) -{ - if (!fileDesignSizes) - { - return cocos2d::Size::ZERO; - } - cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)fileDesignSizes->objectForKey(fileName))->_string.c_str()); - return designSize; -} } \ No newline at end of file diff --git a/cocos/gui/UIHelper.h b/cocos/gui/UIHelper.h index 68893ceff0..838875adf4 100644 --- a/cocos/gui/UIHelper.h +++ b/cocos/gui/UIHelper.h @@ -71,10 +71,6 @@ public: /*temp action*/ static UIWidget* seekActionWidgetByActionTag(UIWidget* root, int tag); - - static void setFileDesignSize(const char* fileName, const cocos2d::Size &size); - - static const cocos2d::Size getFileDesignSize(const char* fileName); }; } From bd7d62aee04cb4dcebb04398a9bec4ba8abddfdf Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 21:48:39 +0800 Subject: [PATCH 131/197] issue #3025: replace TextureCache::getInstance() by Director::getInstance()->getTextureCache() in samples folder --- .../TestCpp/Classes/Box2DTest/Box2dTest.cpp | 2 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 2 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 2 +- .../DataVisitorTest/DataVisitorTest.cpp | 2 +- .../Classes/IntervalTest/IntervalTest.cpp | 2 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 4 +- .../Classes/ParticleTest/ParticleTest.cpp | 46 +++--- .../PerformanceParticleTest.cpp | 20 +-- .../PerformanceTest/PerformanceSpriteTest.cpp | 2 +- .../PerformanceTextureTest.cpp | 4 +- .../RenderTextureTest/RenderTextureTest.cpp | 4 +- .../Classes/SchedulerTest/SchedulerTest.cpp | 2 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 146 +++++++++--------- .../TextureCacheTest/TextureCacheTest.cpp | 40 ++--- .../Classes/TouchesTest/TouchesTest.cpp | 4 +- 16 files changed, 142 insertions(+), 142 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp index ca75a9efe3..ba9d1982fe 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp @@ -29,7 +29,7 @@ Box2DTestLayer::Box2DTestLayer() _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower - _spriteTexture = TextureCache::getInstance()->addImage("Images/blocks.png"); + _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/blocks.png"); auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 50d5dc7252..aad89f259d 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -46,7 +46,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower - _spriteTexture = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas.png"); + _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 93e26514a2..f69ba49240 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -107,7 +107,7 @@ bool BaseClippingNodeTest::init() BaseClippingNodeTest::~BaseClippingNodeTest() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } std::string BaseClippingNodeTest::title() diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp index 4f8a1fb932..aeed903837 100644 --- a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -71,7 +71,7 @@ void PrettyPrinterDemo::onEnter() vistor.clear(); addSprite(); -// dict = TextureCache::getInstance()->snapshotTextures(); +// dict = Director::getInstance()->getTextureCache()->snapshotTextures(); // dict->acceptVisitor(vistor); // log("%s", vistor.getResult().c_str()); } diff --git a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp b/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp index da9fefdca9..3771b1e2aa 100644 --- a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp +++ b/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp @@ -16,7 +16,7 @@ IntervalLayer::IntervalLayer() auto s = Director::getInstance()->getWinSize(); // sun auto sun = ParticleSun::create(); - sun->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + sun->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); sun->setPosition( Point(VisibleRect::rightTop().x-32,VisibleRect::rightTop().y-32) ); sun->setTotalParticles(130); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 82a8a6ebcb..1b2655680f 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -359,7 +359,7 @@ void StressTest1::shouldNotCrash(float dt) // if the node has timers, it crashes auto explosion = ParticleSun::create(); - explosion->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + explosion->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // if it doesn't, it works Ok. // auto explosion = [Sprite create:@"grossinis_sister2.png"); @@ -409,7 +409,7 @@ StressTest2::StressTest2() sublayer->addChild(sp1, 1); auto fire = ParticleFire::create(); - fire->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + fire->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); fire->setPosition( Point(80, s.height/2-50) ); auto copy_seq3 = seq3->clone(); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index d238482244..c4e3b15bad 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -22,7 +22,7 @@ void DemoFirework::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); setEmitterPosition(); } @@ -46,7 +46,7 @@ void DemoFire::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) );//.pvr"); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) );//.pvr"); auto p = _emitter->getPosition(); _emitter->setPosition( Point(p.x, 100) ); @@ -71,7 +71,7 @@ void DemoSun::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -94,7 +94,7 @@ void DemoGalaxy::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -116,7 +116,7 @@ void DemoFlower::onEnter() _emitter = ParticleFlower::create(); _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); setEmitterPosition(); } @@ -141,7 +141,7 @@ void DemoBigFlower::onEnter() _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : use this line or remove this line and use autorelease() - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setDuration(-1); @@ -225,7 +225,7 @@ void DemoRotFlower::onEnter() _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : Remove this line - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars2) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars2) ); // duration _emitter->setDuration(-1); @@ -308,7 +308,7 @@ void DemoMeteor::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -331,7 +331,7 @@ void DemoSpiral::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -354,7 +354,7 @@ void DemoExplosion::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setAutoRemoveOnFinish(true); @@ -378,7 +378,7 @@ void DemoSmoke::onEnter() _emitter = ParticleSmoke::create(); _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); auto p = _emitter->getPosition(); _emitter->setPosition( Point( p.x, 100) ); @@ -429,7 +429,7 @@ void DemoSnow::onEnter() _emitter->setEmissionRate(_emitter->getTotalParticles()/_emitter->getLife()); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_snow) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_snow) ); setEmitterPosition(); } @@ -456,7 +456,7 @@ void DemoRain::onEnter() _emitter->setPosition( Point( p.x, p.y-100) ); _emitter->setLife(4); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -540,7 +540,7 @@ void DemoModernArt::onEnter() _emitter->setEndSizeVar(8.0f); // texture - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); // additive _emitter->setBlendAdditive(false); @@ -567,7 +567,7 @@ void DemoRing::onEnter() _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setLifeVar(0); _emitter->setLife(10); _emitter->setSpeed(100); @@ -605,14 +605,14 @@ void ParallaxParticle::onEnter() _emitter = ParticleFlower::create(); _emitter->retain(); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); p1->addChild(_emitter, 10); _emitter->setPosition( Point(250,200) ); auto par = ParticleSun::create(); p2->addChild(par, 10); - par->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + par->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); auto move = MoveBy::create(4, Point(300,0)); auto move_back = move->reverse(); @@ -641,7 +641,7 @@ void RadiusMode1::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(200); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/stars-grayscale.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -725,7 +725,7 @@ void RadiusMode2::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(200); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/stars-grayscale.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -809,7 +809,7 @@ void Issue704::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(100); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -900,7 +900,7 @@ void Issue870::onEnter() auto system = new ParticleSystemQuad(); system->initWithFile("Particles/SpinningPeas.plist"); - system->setTextureWithRect(TextureCache::getInstance()->addImage("Images/particles.png"), Rect(0,0,32,32)); + system->setTextureWithRect(Director::getInstance()->getTextureCache()->addImage("Images/particles.png"), Rect(0,0,32,32)); addChild(system, 10); _emitter = system; @@ -1452,7 +1452,7 @@ bool RainbowEffect::initWithTotalParticles(unsigned int numberOfParticles) _endColorVar.b = 0.0f; _endColorVar.a = 0.0f; - setTexture(TextureCache::getInstance()->addImage("Images/particles.png")); + setTexture(Director::getInstance()->getTextureCache()->addImage("Images/particles.png")); return true; } @@ -1504,7 +1504,7 @@ void MultipleParticleSystems::onEnter() removeChild(_background, true); _background = NULL; - TextureCache::getInstance()->addImage("Images/particles.png"); + Director::getInstance()->getTextureCache()->addImage("Images/particles.png"); for (int i = 0; i<5; i++) { auto particleSystem = ParticleSystemQuad::create("Particles/SpinningPeas.plist"); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp index b72ad00da5..b6878a5b22 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp @@ -187,8 +187,8 @@ void ParticleMainScene::createParticleSystem() removeChildByTag(kTagParticleSystem, true); // remove the "fire.png" from the TextureCache cache. - auto texture = TextureCache::getInstance()->addImage("Images/fire.png"); - TextureCache::getInstance()->removeTexture(texture); + auto texture = Director::getInstance()->getTextureCache()->addImage("Images/fire.png"); + Director::getInstance()->getTextureCache()->removeTexture(texture); //TODO: if (subtestNumber <= 3) // { @@ -204,42 +204,42 @@ void ParticleMainScene::createParticleSystem() case 1: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 2: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 3: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; // case 4: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[TextureCache sharedTextureCache] addImage:@"fire.pvr"]; -// particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); +// particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // break; case 4: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 5: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 6: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; // case 8: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[TextureCache sharedTextureCache] addImage:@"fire.pvr"]; -// particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); +// particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // break; default: particleSystem = NULL; diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 7e290e5e5b..ccf4ca602d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -52,7 +52,7 @@ void SubTest::initWithSubTest(int nSubTest, Node* p) */ // purge textures - auto mgr = TextureCache::getInstance(); + auto mgr = Director::getInstance()->getTextureCache(); // [mgr removeAllTextures]; mgr->removeTexture(mgr->addImage("Images/grossinis_sister1.png")); mgr->removeTexture(mgr->addImage("Images/grossini_dance_atlas.png")); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp index bcbae20aa1..0da9efd0ec 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp @@ -84,7 +84,7 @@ void TextureTest::performTestsPNG(const char* filename) { struct timeval now; Texture2D *texture; - auto cache = TextureCache::getInstance(); + auto cache = Director::getInstance()->getTextureCache(); log("RGBA 8888"); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); @@ -131,7 +131,7 @@ void TextureTest::performTests() { // Texture2D *texture; // struct timeval now; -// auto cache = TextureCache::getInstance(); +// auto cache = Director::getInstance()->getTextureCache(); log("--------"); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index baf174ac9b..987d8b8f05 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -156,7 +156,7 @@ void RenderTextureSave::saveImage(cocos2d::Object *sender) auto image = _target->newImage(); - auto tex = TextureCache::getInstance()->addImage(image, png); + auto tex = Director::getInstance()->getTextureCache()->addImage(image, png); CC_SAFE_DELETE(image); @@ -176,7 +176,7 @@ RenderTextureSave::~RenderTextureSave() { _brush->release(); _target->release(); - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } void RenderTextureSave::onTouchesMoved(const std::vector& touches, Event* event) diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 96ee66292b..d225e1c8f8 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -924,7 +924,7 @@ void SchedulerTimeScale::onEnter() kathia->runAction(Speed::create(action3, 1.0f)); auto emitter = ParticleFireworks::create(); - emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); addChild(emitter); _sliderCtl = sliderCtl(); diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 499b1b8dfe..09b2f61d9d 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -71aa9486e8535b9bd65cae247bb86de59c83f522 \ No newline at end of file +ddd085a82dc104bac66268a7ddcdf9b0c32cb4ee \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 8184bc1467..6245237ca8 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -129,18 +129,18 @@ void TextureDemo::onEnter() { BaseTest::onEnter(); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); auto col = LayerColor::create(Color4B(128,128,128,255)); addChild(col, -10); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } TextureDemo::~TextureDemo() { - TextureCache::getInstance()->removeUnusedTextures(); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } void TextureDemo::restartCallback(Object* sender) @@ -191,7 +191,7 @@ void TextureTIFF::onEnter() auto img = Sprite::create("Images/test_image.tiff"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); this->addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureTIFF::title() @@ -213,7 +213,7 @@ void TexturePNG::onEnter() auto img = Sprite::create("Images/test_image.png"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePNG::title() @@ -234,7 +234,7 @@ void TextureJPEG::onEnter() auto img = Sprite::create("Images/test_image.jpeg"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureJPEG::title() @@ -255,7 +255,7 @@ void TextureWEBP::onEnter() auto img = Sprite::create("Images/test_image.webp"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureWEBP::title() @@ -273,12 +273,12 @@ void TextureMipMap::onEnter() TextureDemo::onEnter(); auto s = Director::getInstance()->getWinSize(); - auto texture0 = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas.png"); + auto texture0 = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); texture0->generateMipmap(); Texture2D::TexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; texture0->setTexParameters(texParams); - auto texture1 = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas_nomipmap.png"); + auto texture1 = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas_nomipmap.png"); auto img0 = Sprite::createWithTexture(texture0); img0->setTextureRect(Rect(85, 121, 85, 121)); @@ -299,7 +299,7 @@ void TextureMipMap::onEnter() img0->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img1->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureMipMap::title() @@ -350,7 +350,7 @@ void TexturePVRMipMap::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRMipMap::title() @@ -392,7 +392,7 @@ void TexturePVRMipMap2::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRMipMap2::title() @@ -424,7 +424,7 @@ void TexturePVR2BPP::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVR2BPP::title() @@ -455,7 +455,7 @@ void TexturePVRTest::onEnter() { log("This test is not supported."); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } @@ -487,7 +487,7 @@ void TexturePVR4BPP::onEnter() { log("This test is not supported in cocos2d-mac"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVR4BPP::title() @@ -510,7 +510,7 @@ void TexturePVRRGBA8888::onEnter() auto img = Sprite::create("Images/test_image_rgba8888.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA8888::title() @@ -540,7 +540,7 @@ void TexturePVRBGRA8888::onEnter() { log("BGRA8888 images are not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRBGRA8888::title() @@ -563,7 +563,7 @@ void TexturePVRRGBA5551::onEnter() auto img = Sprite::create("Images/test_image_rgba5551.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA5551::title() @@ -586,7 +586,7 @@ void TexturePVRRGBA4444::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444::title() @@ -614,7 +614,7 @@ void TexturePVRRGBA4444GZ::onEnter() #endif img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444GZ::title() @@ -642,7 +642,7 @@ void TexturePVRRGBA4444CCZ::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr.ccz"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444CCZ::title() @@ -670,7 +670,7 @@ void TexturePVRRGB565::onEnter() auto img = Sprite::create("Images/test_image_rgb565.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGB565::title() @@ -693,7 +693,7 @@ void TexturePVRRGB888::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGB888::title() @@ -716,7 +716,7 @@ void TexturePVRA8::onEnter() auto img = Sprite::create("Images/test_image_a8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } @@ -740,7 +740,7 @@ void TexturePVRI8::onEnter() auto img = Sprite::create("Images/test_image_i8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRI8::title() @@ -763,7 +763,7 @@ void TexturePVRAI88::onEnter() auto img = Sprite::create("Images/test_image_ai88.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRAI88::title() @@ -785,7 +785,7 @@ void TexturePVR2BPPv3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVR2BPPv3::title() @@ -812,7 +812,7 @@ void TexturePVRII2BPPv3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRII2BPPv3::title() @@ -843,7 +843,7 @@ void TexturePVR4BPPv3::onEnter() log("This test is not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVR4BPPv3::title() @@ -878,7 +878,7 @@ void TexturePVRII4BPPv3::onEnter() log("This test is not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRII4BPPv3::title() @@ -905,7 +905,7 @@ void TexturePVRRGBA8888v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA8888v3::title() @@ -936,7 +936,7 @@ void TexturePVRBGRA8888v3::onEnter() log("BGRA images are not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRBGRA8888v3::title() @@ -963,7 +963,7 @@ void TexturePVRRGBA5551v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA5551v3::title() @@ -990,7 +990,7 @@ void TexturePVRRGBA4444v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA4444v3::title() @@ -1017,7 +1017,7 @@ void TexturePVRRGB565v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGB565v3::title() @@ -1044,7 +1044,7 @@ void TexturePVRRGB888v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGB888v3::title() @@ -1071,7 +1071,7 @@ void TexturePVRA8v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRA8v3::title() @@ -1098,7 +1098,7 @@ void TexturePVRI8v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRI8v3::title() @@ -1125,7 +1125,7 @@ void TexturePVRAI88v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRAI88v3::title() @@ -1181,7 +1181,7 @@ void TexturePVRNonSquare::onEnter() auto img = Sprite::create("Images/grossini_128x256_mipmap.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNonSquare::title() @@ -1210,7 +1210,7 @@ void TexturePVRNPOT4444::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNPOT4444::title() @@ -1239,7 +1239,7 @@ void TexturePVRNPOT8888::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNPOT8888::title() @@ -1293,7 +1293,7 @@ void TextureAlias::onEnter() sprite2->runAction(scaleforever); sprite->runAction(scaleToo); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureAlias::title() @@ -1334,7 +1334,7 @@ void TexturePixelFormat::onEnter() addChild(sprite1, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite1->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite1->getTexture()); // RGBA 4444 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); @@ -1343,7 +1343,7 @@ void TexturePixelFormat::onEnter() addChild(sprite2, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite2->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite2->getTexture()); // RGB5A1 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1); @@ -1352,7 +1352,7 @@ void TexturePixelFormat::onEnter() addChild(sprite3, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite3->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite3->getTexture()); // RGB888 image Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB888); @@ -1361,7 +1361,7 @@ void TexturePixelFormat::onEnter() addChild(sprite4, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite4->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite4->getTexture()); // RGB565 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB565); @@ -1370,7 +1370,7 @@ void TexturePixelFormat::onEnter() addChild(sprite5, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite5->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite5->getTexture()); // A8 image (8-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); @@ -1379,7 +1379,7 @@ void TexturePixelFormat::onEnter() addChild(sprite6, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite6->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite6->getTexture()); auto fadeout = FadeOut::create(2); auto fadein = FadeIn::create(2); @@ -1398,7 +1398,7 @@ void TexturePixelFormat::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePixelFormat::title() @@ -1486,7 +1486,7 @@ void TextureAsync::onEnter() TextureAsync::~TextureAsync() { - TextureCache::getInstance()->removeAllTextures(); + Director::getInstance()->getTextureCache()->removeAllTextures(); } void TextureAsync::loadImages(float dt) @@ -1495,15 +1495,15 @@ void TextureAsync::loadImages(float dt) for( int j=0;j < 8; j++) { char szSpriteName[100] = {0}; sprintf(szSpriteName, "Images/sprites_test/sprite-%d-%d.png", i, j); - TextureCache::getInstance()->addImageAsync(szSpriteName,this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync(szSpriteName,this, callfuncO_selector(TextureAsync::imageLoaded)); } } - TextureCache::getInstance()->addImageAsync("Images/background1.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/background2.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/background.png",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/atlastest.png",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_atlas.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background1.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background2.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/atlastest.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_atlas.png",this, callfuncO_selector(TextureAsync::imageLoaded)); } @@ -1576,7 +1576,7 @@ std::string TextureGlClamp::title() TextureGlClamp::~TextureGlClamp() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } //------------------------------------------------------------------ @@ -1613,7 +1613,7 @@ std::string TextureGlRepeat::title() TextureGlRepeat::~TextureGlRepeat() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } //------------------------------------------------------------------ @@ -1684,7 +1684,7 @@ void TextureCache1::onEnter() sprite->setScale(2); addChild(sprite); - TextureCache::getInstance()->removeTexture(sprite->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite->getTexture()); sprite = Sprite::create("Images/grossinis_sister1.png"); sprite->setPosition(Point(s.width/5*2, s.height/2)); @@ -1700,7 +1700,7 @@ void TextureCache1::onEnter() sprite->setScale(2); addChild(sprite); - TextureCache::getInstance()->removeTextureForKey("Images/grossinis_sister2.png"); + Director::getInstance()->getTextureCache()->removeTextureForKey("Images/grossinis_sister2.png"); sprite = Sprite::create("Images/grossinis_sister2.png"); sprite->setPosition(Point(s.width/5*4, s.height/2)); @@ -1724,8 +1724,8 @@ void TextureDrawAtPoint::onEnter() { TextureDemo::onEnter(); - _tex1 = TextureCache::getInstance()->addImage("Images/grossinis_sister1.png"); - _Tex2F = TextureCache::getInstance()->addImage("Images/grossinis_sister2.png"); + _tex1 = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister1.png"); + _Tex2F = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister2.png"); _tex1->retain(); _Tex2F->retain(); @@ -1763,8 +1763,8 @@ void TextureDrawAtPoint::draw() void TextureDrawInRect::onEnter() { TextureDemo::onEnter(); - _tex1 = TextureCache::getInstance()->addImage("Images/grossinis_sister1.png"); - _Tex2F = TextureCache::getInstance()->addImage("Images/grossinis_sister2.png"); + _tex1 = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister1.png"); + _Tex2F = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister2.png"); _tex1->retain(); _Tex2F->retain(); @@ -1871,7 +1871,7 @@ void TextureMemoryAlloc::updateImage(cocos2d::Object *sender) _background->removeFromParentAndCleanup(true); } - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); int tag = ((Node*)sender)->getTag(); string file; @@ -1952,7 +1952,7 @@ TexturePVRv3Premult::TexturePVRv3Premult() // PNG Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - TextureCache::getInstance()->removeTextureForKey("Images/grossinis_sister1-testalpha.png"); + Director::getInstance()->getTextureCache()->removeTextureForKey("Images/grossinis_sister1-testalpha.png"); auto png = Sprite::create("Images/grossinis_sister1-testalpha.png"); addChild(png, 0); png->setPosition(Point(size.width/4*3, size.height/2)); @@ -2132,7 +2132,7 @@ static void addImageToDemo(TextureDemo& demo, float x, float y, const char* path demo.addChild(sprite, 0); //remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite->getTexture()); } //TextureConvertRGB888 @@ -2157,7 +2157,7 @@ void TextureConvertRGB888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertRGB888::title() @@ -2191,7 +2191,7 @@ void TextureConvertRGBA8888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertRGBA8888::title() @@ -2225,7 +2225,7 @@ void TextureConvertI8::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertI8::title() @@ -2259,7 +2259,7 @@ void TextureConvertAI88::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertAI88::title() diff --git a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp b/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp index 32d9660ce4..698a2935fd 100644 --- a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp @@ -21,26 +21,26 @@ TextureCacheTest::TextureCacheTest() this->addChild(_labelPercent); // load textrues - TextureCache::getInstance()->addImageAsync("Images/HelloWorld.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_01.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_02.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_03.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_04.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_05.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_06.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_07.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_08.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_09.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_10.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_11.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_12.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_13.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_14.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background1.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background2.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background3.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/HelloWorld.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_01.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_02.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_03.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_04.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_05.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_06.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_07.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_08.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_09.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_10.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_11.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_12.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_13.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_14.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background1.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background2.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background3.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); } void TextureCacheTest::loadingCallBack(Object *obj) diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp b/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp index 6c57cac1b5..ef695368ff 100644 --- a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp @@ -39,13 +39,13 @@ PongLayer::PongLayer() { _ballStartingVelocity = Point(20.0f, -100.0f); - _ball = Ball::ballWithTexture( TextureCache::getInstance()->addImage(s_Ball) ); + _ball = Ball::ballWithTexture( Director::getInstance()->getTextureCache()->addImage(s_Ball) ); _ball->setPosition( VisibleRect::center() ); _ball->setVelocity( _ballStartingVelocity ); addChild( _ball ); _ball->retain(); - auto paddleTexture = TextureCache::getInstance()->addImage(s_Paddle); + auto paddleTexture = Director::getInstance()->getTextureCache()->addImage(s_Paddle); auto paddlesM = Array::createWithCapacity(4); From 916361af3f6cb0264201ad10834bd1c9d025710b Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 7 Nov 2013 23:40:33 +0800 Subject: [PATCH 132/197] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. --- cocos/base/CCGeometry.cpp | 9 +++++++++ cocos/base/CCGeometry.h | 19 +++++++++++++++++++ .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 1d5c4896c6..b6b59f5b03 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -284,6 +284,15 @@ Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, c } const Point Point::ZERO = Point(0, 0); +const Point Point::ANCHOR_MIDDLE = Point(0.5, 0.5); +const Point Point::ANCHOR_BOTTOM_LEFT = Point(0, 0); +const Point Point::ANCHOR_TOP_LEFT = Point(0, 1); +const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1, 0); +const Point Point::ANCHOR_TOP_RIGHT = Point(1, 1); +const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1, .5); +const Point Point::ANCHOR_MIDDLE_LEFT = Point(0, 0.5); +const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5, 1); +const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5, 0); // implementation of Size diff --git a/cocos/base/CCGeometry.h b/cocos/base/CCGeometry.h index 847557cb35..0b3e30d208 100644 --- a/cocos/base/CCGeometry.h +++ b/cocos/base/CCGeometry.h @@ -423,7 +423,26 @@ public: */ static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); + /** equals to Point(0,0) */ static const Point ZERO; + /** equals to Point(0.5, 0.5) */ + static const Point ANCHOR_MIDDLE; + /** equals to Point(0, 0) */ + static const Point ANCHOR_BOTTOM_LEFT; + /** equals to Point(0, 1) */ + static const Point ANCHOR_TOP_LEFT; + /** equals to Point(1, 0) */ + static const Point ANCHOR_BOTTOM_RIGHT; + /** equals to Point(1, 1) */ + static const Point ANCHOR_TOP_RIGHT; + /** equals to Point(1, 0.5) */ + static const Point ANCHOR_MIDDLE_RIGHT; + /** equals to Point(0, 0.5) */ + static const Point ANCHOR_MIDDLE_LEFT; + /** equals to Point(0.5, 1) */ + static const Point ANCHOR_MIDDLE_TOP; + /** equals to Point(0.5, 0) */ + static const Point ANCHOR_MIDDLE_BOTTOM; private: // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 499b1b8dfe..c01845edff 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -71aa9486e8535b9bd65cae247bb86de59c83f522 \ No newline at end of file +dd564ef17f9cc0281964247923ec24957cad7bd0 \ No newline at end of file From 006d32f883ff2d220823d56c342b5b057b2b319c Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 7 Nov 2013 23:51:01 +0800 Subject: [PATCH 133/197] rename jsb boot file. --- template/multi-platform-js/Classes/AppDelegate.cpp | 2 +- .../multi-platform-js/Resources/{main.js => cocos2d-jsb.js} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename template/multi-platform-js/Resources/{main.js => cocos2d-jsb.js} (100%) diff --git a/template/multi-platform-js/Classes/AppDelegate.cpp b/template/multi-platform-js/Classes/AppDelegate.cpp index 4c2fea3abf..e409b974b5 100644 --- a/template/multi-platform-js/Classes/AppDelegate.cpp +++ b/template/multi-platform-js/Classes/AppDelegate.cpp @@ -47,7 +47,7 @@ bool AppDelegate::applicationDidFinishLaunching() ScriptEngineProtocol *engine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); - ScriptingCore::getInstance()->runScript("main.js"); + ScriptingCore::getInstance()->runScript("cocos2d-jsb.js"); return true; } diff --git a/template/multi-platform-js/Resources/main.js b/template/multi-platform-js/Resources/cocos2d-jsb.js similarity index 100% rename from template/multi-platform-js/Resources/main.js rename to template/multi-platform-js/Resources/cocos2d-jsb.js From e4662b371ae04de9394b4df75d81f99c62e23642 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 11:58:48 -0800 Subject: [PATCH 134/197] TextField uses std::string& in the public API and uses std::string instead of std::string* internally --- cocos/2d/CCTextFieldTTF.cpp | 118 ++++++++++++++++-------------------- cocos/2d/CCTextFieldTTF.h | 28 ++++----- cocos/gui/UITextField.cpp | 4 +- 3 files changed, 68 insertions(+), 82 deletions(-) diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 934b88a091..01179ba523 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -53,8 +53,8 @@ static int _calcCharCount(const char * pszText) TextFieldTTF::TextFieldTTF() : _delegate(0) , _charCount(0) -, _inputText(new std::string) -, _placeHolder(new std::string) // prevent LabelTTF initWithString assertion +, _inputText("") +, _placeHolder("") // prevent LabelTTF initWithString assertion , _secureTextEntry(false) { _colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127; @@ -62,43 +62,41 @@ TextFieldTTF::TextFieldTTF() TextFieldTTF::~TextFieldTTF() { - CC_SAFE_DELETE(_inputText); - CC_SAFE_DELETE(_placeHolder); } ////////////////////////////////////////////////////////////////////////// // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize) +TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize) { - TextFieldTTF *pRet = new TextFieldTTF(); - if(pRet && pRet->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) + TextFieldTTF *ret = new TextFieldTTF(); + if(ret && ret->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) { - pRet->autorelease(); - if (placeholder) + ret->autorelease(); + if (placeholder.size()>0) { - pRet->setPlaceHolder(placeholder); + ret->setPlaceHolder(placeholder); } - return pRet; + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize) +TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { - TextFieldTTF *pRet = new TextFieldTTF(); - if(pRet && pRet->initWithString("", fontName, fontSize)) + TextFieldTTF *ret = new TextFieldTTF(); + if(ret && ret->initWithString("", fontName, fontSize)) { - pRet->autorelease(); - if (placeholder) + ret->autorelease(); + if (placeholder.size()>0) { - pRet->setPlaceHolder(placeholder); + ret->setPlaceHolder(placeholder); } - return pRet; + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -106,23 +104,15 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, c // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize) { - if (placeholder) - { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = new std::string(placeholder); - } - return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize, dimensions, alignment); + _placeHolder = placeholder; + return LabelTTF::initWithString(_placeHolder, fontName, fontSize, dimensions, alignment); } -bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { - if (placeholder) - { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = new std::string(placeholder); - } - return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize); + _placeHolder = std::string(placeholder); + return LabelTTF::initWithString(_placeHolder, fontName, fontSize); } ////////////////////////////////////////////////////////////////////////// @@ -190,9 +180,9 @@ void TextFieldTTF::insertText(const char * text, int len) } _charCount += _calcCharCount(sInsert.c_str()); - std::string sText(*_inputText); + std::string sText(_inputText); sText.append(sInsert); - setString(sText.c_str()); + setString(sText); } if ((int)sInsert.npos == nPos) { @@ -211,7 +201,7 @@ void TextFieldTTF::insertText(const char * text, int len) void TextFieldTTF::deleteBackward() { - int nStrLen = _inputText->length(); + int nStrLen = _inputText.length(); if (! nStrLen) { // there is no string @@ -221,12 +211,12 @@ void TextFieldTTF::deleteBackward() // get the delete byte number int nDeleteLen = 1; // default, erase 1 byte - while(0x80 == (0xC0 & _inputText->at(nStrLen - nDeleteLen))) + while(0x80 == (0xC0 & _inputText.at(nStrLen - nDeleteLen))) { ++nDeleteLen; } - if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText->c_str() + nStrLen - nDeleteLen, nDeleteLen)) + if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText.c_str() + nStrLen - nDeleteLen, nDeleteLen)) { // delegate doesn't wan't to delete backwards return; @@ -235,21 +225,20 @@ void TextFieldTTF::deleteBackward() // if all text deleted, show placeholder string if (nStrLen <= nDeleteLen) { - CC_SAFE_DELETE(_inputText); - _inputText = new std::string; + _inputText = ""; _charCount = 0; - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); return; } // set new input text - std::string sText(_inputText->c_str(), nStrLen - nDeleteLen); - setString(sText.c_str()); + std::string sText(_inputText.c_str(), nStrLen - nDeleteLen); + setString(sText); } const char * TextFieldTTF::getContentText() { - return _inputText->c_str(); + return _inputText.c_str(); } void TextFieldTTF::draw() @@ -258,7 +247,7 @@ void TextFieldTTF::draw() { return; } - if (_inputText->length()) + if (_inputText.length()) { LabelTTF::draw(); return; @@ -286,22 +275,20 @@ void TextFieldTTF::setColorSpaceHolder(const Color3B& color) ////////////////////////////////////////////////////////////////////////// // input text property -void TextFieldTTF::setString(const char *text) +void TextFieldTTF::setString(const std::string &text) { static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; std::string displayText; int length; - CC_SAFE_DELETE(_inputText); - - if (text) + if (text.length()>0) { - _inputText = new std::string(text); - displayText = *_inputText; + _inputText = text; + displayText = _inputText; if (_secureTextEntry) { displayText = ""; - length = _inputText->length(); + length = _inputText.length(); while (length) { displayText.append(bulletString); @@ -311,40 +298,39 @@ void TextFieldTTF::setString(const char *text) } else { - _inputText = new std::string; + _inputText = ""; } // if there is no input text, display placeholder instead - if (! _inputText->length()) + if (! _inputText.length()) { - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); } else { - LabelTTF::setString(displayText.c_str()); + LabelTTF::setString(displayText); } - _charCount = _calcCharCount(_inputText->c_str()); + _charCount = _calcCharCount(_inputText.c_str()); } const char* TextFieldTTF::getString(void) const { - return _inputText->c_str(); + return _inputText.c_str(); } // place holder text property -void TextFieldTTF::setPlaceHolder(const char * text) +void TextFieldTTF::setPlaceHolder(const std::string& text) { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = (text) ? new std::string(text) : new std::string; - if (! _inputText->length()) + _placeHolder = text; + if (! _inputText.length()) { - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); } } -const char * TextFieldTTF::getPlaceHolder(void) +const std::string& TextFieldTTF::getPlaceHolder() const { - return _placeHolder->c_str(); + return _placeHolder; } // secureTextEntry diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 79feb55d7c..28c74a7a9c 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -109,13 +109,13 @@ public: //char * description(); /** creates a TextFieldTTF from a fontname, alignment, dimension and font size */ - static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize); + static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize); /** creates a LabelTTF from a fontname and font size */ - static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); + static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); /** initializes the TextFieldTTF with a font name, alignment, dimension and font size */ - bool initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize); + bool initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize); /** initializes the TextFieldTTF with a font name and font size */ - bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); + bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); /** @brief Open keyboard and receive input text. @@ -147,21 +147,21 @@ public: // input text property public: - virtual void setString(const char *text); + virtual void setString(const std::string& text) override; virtual const char* getString(void) const; protected: TextFieldDelegate * _delegate; int _charCount; - std::string * _inputText; + std::string _inputText; // place holder text property // place holder text displayed when there is no text in the text field. public: - virtual void setPlaceHolder(const char * text); - virtual const char * getPlaceHolder(void); + virtual void setPlaceHolder(const std::string& text); + virtual const std::string& getPlaceHolder(void) const; protected: - std::string * _placeHolder; + std::string _placeHolder; Color3B _colorSpaceHolder; public: virtual void setSecureTextEntry(bool value); @@ -176,11 +176,11 @@ protected: // IMEDelegate interface ////////////////////////////////////////////////////////////////////////// - virtual bool canAttachWithIME(); - virtual bool canDetachWithIME(); - virtual void insertText(const char * text, int len); - virtual void deleteBackward(); - virtual const char * getContentText(); + virtual bool canAttachWithIME() override; + virtual bool canDetachWithIME() override; + virtual void insertText(const char * text, int len) override; + virtual void deleteBackward() override; + virtual const char * getContentText() override; private: class LengthStack; LengthStack * _lens; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 7eb30518cd..da79a1590b 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -139,7 +139,7 @@ void UICCTextField::insertText(const char * text, int len) { if (cocos2d::TextFieldTTF::getCharCount() > 0) { - setPasswordText(_inputText->c_str()); + setPasswordText(_inputText.c_str()); } } } @@ -153,7 +153,7 @@ void UICCTextField::deleteBackward() // password if (_passwordEnabled) { - setPasswordText(_inputText->c_str()); + setPasswordText(_inputText.c_str()); } } } From ffd434254800645a6d0fe44f0bffa7da90940cb4 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 12:42:16 -0800 Subject: [PATCH 135/197] Adds more strings and more `override` and fixes some indetentation issues --- cocos/2d/CCLabel.h | 46 +++++++++++----------- cocos/2d/CCLabelAtlas.cpp | 4 +- cocos/2d/CCLabelAtlas.h | 7 ++-- cocos/2d/CCLabelBMFont.cpp | 4 +- cocos/2d/CCLabelBMFont.h | 4 +- cocos/2d/CCLabelTTF.cpp | 4 +- cocos/2d/CCLabelTTF.h | 4 +- cocos/2d/CCProtocols.h | 2 +- cocos/2d/CCTextFieldTTF.cpp | 4 +- cocos/2d/CCTextFieldTTF.h | 2 +- cocos/gui/UIButton.cpp | 4 +- cocos/gui/UIButton.h | 4 +- cocos/gui/UILabel.cpp | 17 ++++---- cocos/gui/UILabel.h | 6 +-- cocos/gui/UILabelAtlas.cpp | 12 +++--- cocos/gui/UILabelAtlas.h | 10 ++--- cocos/gui/UITextField.cpp | 18 ++++----- cocos/gui/UITextField.h | 8 ++-- samples/Cpp/TestCpp/Classes/controller.cpp | 7 +++- 19 files changed, 84 insertions(+), 83 deletions(-) diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index a4c9a127e2..d781196777 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -83,38 +83,38 @@ public: // CCLabelTextFormat protocol implementation virtual std::vector *getLettersInfo() override { return &_lettersInfo; }; - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; - virtual bool recordPlaceholderInfo(int spriteIndex) override; - virtual float getLetterPosXLeft( int index ) const override; - virtual float getLetterPosXRight( int index ) const override; + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; + virtual bool recordPlaceholderInfo(int spriteIndex) override; + virtual float getLetterPosXLeft( int index ) const override; + virtual float getLetterPosXRight( int index ) const override; - virtual Sprite * getLetter(int ID) override; + virtual Sprite * getLetter(int ID) override; // font related stuff - virtual int getCommonLineHeight() const override; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; - virtual int getXOffsetForChar(unsigned short c) const override; - virtual int getYOffsetForChar(unsigned short c) const override; - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; - virtual Rect getRectForChar(unsigned short c) const override; + virtual int getCommonLineHeight() const override; + virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; + virtual int getXOffsetForChar(unsigned short c) const override; + virtual int getYOffsetForChar(unsigned short c) const override; + virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; + virtual Rect getRectForChar(unsigned short c) const override; // string related stuff - virtual int getStringNumLines() const override; - virtual int getStringLenght() const override; - virtual unsigned short getCharAtStringPosition(int position) const override; - virtual unsigned short * getUTF8String() const override; - virtual void assignNewUTF8String(unsigned short *newString) override; - virtual TextHAlignment getTextAlignment() const override; + virtual int getStringNumLines() const override; + virtual int getStringLenght() const override; + virtual unsigned short getCharAtStringPosition(int position) const override; + virtual unsigned short * getUTF8String() const override; + virtual void assignNewUTF8String(unsigned short *newString) override; + virtual TextHAlignment getTextAlignment() const override; // label related stuff - virtual float getMaxLineWidth() const override; - virtual bool breakLineWithoutSpace() const override; - virtual Size getLabelContentSize() const override; - virtual void setLabelContentSize(const Size &newSize) override; + virtual float getMaxLineWidth() const override; + virtual bool breakLineWithoutSpace() const override; + virtual Size getLabelContentSize() const override; + virtual void setLabelContentSize(const Size &newSize) override; // carloX - const char * getString() const { return "not implemented"; } - void addChild(Node * child, int zOrder=0, int tag=0); + virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; } + void addChild(Node * child, int zOrder=0, int tag=0) override; private: /** diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 56a6ff723b..262c5f2dd9 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -203,9 +203,9 @@ void LabelAtlas::setString(const std::string &label) _quadsToDraw = len; } -const char* LabelAtlas::getString(void) const +const std::string& LabelAtlas::getString(void) const { - return _string.c_str(); + return _string; } //CCLabelAtlas - draw diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index eb8d06f4be..8fd81b9bda 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -87,11 +87,12 @@ public: // super methods virtual void updateAtlasValues(); - virtual void setString(const std::string &label); - virtual const char* getString(void) const; + + virtual void setString(const std::string &label) override; + virtual const std::string& getString(void) const override; #if CC_LABELATLAS_DEBUG_DRAW - virtual void draw(); + virtual void draw() override; #endif protected: diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index e28d4d0afc..fe6026abfe 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -767,9 +767,9 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel) } } -const char* LabelBMFont::getString(void) const +const std::string& LabelBMFont::getString() const { - return _initialStringUTF8.c_str(); + return _initialStringUTF8; } void LabelBMFont::setCString(const char *label) diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index cc49dd0806..a825d28ed6 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -228,10 +228,10 @@ public: /** updates the font chars based on the string to render */ void createFontChars(); // super method - virtual void setString(const std::string& newString); + virtual void setString(const std::string& newString) override; virtual void setString(const std::string& newString, bool needUpdateLabel); - virtual const char* getString() const; + virtual const std::string& getString() const override; virtual void setCString(const char *label); virtual void setAnchorPoint(const Point& var); virtual void updateLabel(); diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 3eec437d09..179f079e50 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -180,9 +180,9 @@ void LabelTTF::setString(const std::string &string) } } -const char* LabelTTF::getString(void) const +const std::string& LabelTTF::getString() const { - return _string.c_str(); + return _string; } const char* LabelTTF::description() const diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 029a125def..8c5689e3d0 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -144,8 +144,8 @@ public: /** changes the string to render * @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas */ - virtual void setString(const std::string &label); - virtual const char* getString(void) const; + virtual void setString(const std::string &label) override; + virtual const std::string& getString(void) const override; TextHAlignment getHorizontalAlignment() const; void setHorizontalAlignment(TextHAlignment alignment); diff --git a/cocos/2d/CCProtocols.h b/cocos/2d/CCProtocols.h index 17249816c0..993d1fa161 100644 --- a/cocos/2d/CCProtocols.h +++ b/cocos/2d/CCProtocols.h @@ -238,7 +238,7 @@ public: * @js NA * @lua NA */ - virtual const char* getString() const = 0; + virtual const std::string& getString() const = 0; }; /** diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 01179ba523..895aab58de 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -313,9 +313,9 @@ void TextFieldTTF::setString(const std::string &text) _charCount = _calcCharCount(_inputText.c_str()); } -const char* TextFieldTTF::getString(void) const +const std::string& TextFieldTTF::getString() const { - return _inputText.c_str(); + return _inputText; } // place holder text property diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 28c74a7a9c..a6ae42dc8e 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -148,7 +148,7 @@ public: // input text property public: virtual void setString(const std::string& text) override; - virtual const char* getString(void) const; + virtual const std::string& getString() const override; protected: TextFieldDelegate * _delegate; int _charCount; diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 43d6b27ecf..d18627be1e 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -565,12 +565,12 @@ void UIButton::setPressedActionEnabled(bool enabled) _pressedActionEnabled = enabled; } -void UIButton::setTitleText(const char* text) +void UIButton::setTitleText(const std::string& text) { _titleRenderer->setString(text); } -const char* UIButton::getTitleText() const +const std::string& UIButton::getTitleText() const { return _titleRenderer->getString(); } diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index bc6958c3e4..b069cbf5e0 100644 --- a/cocos/gui/UIButton.h +++ b/cocos/gui/UIButton.h @@ -171,8 +171,8 @@ public: */ virtual const char* getDescription() const; - void setTitleText(const char* text); - const char* getTitleText() const; + void setTitleText(const std::string& text); + const std::string& getTitleText() const; void setTitleColor(const cocos2d::Color3B& color); const cocos2d::Color3B& getTitleColor() const; void setTitleFontSize(float size); diff --git a/cocos/gui/UILabel.cpp b/cocos/gui/UILabel.cpp index 4c8779c9eb..cdf32c49c1 100644 --- a/cocos/gui/UILabel.cpp +++ b/cocos/gui/UILabel.cpp @@ -70,26 +70,23 @@ void UILabel::initRenderer() _renderer->addChild(_labelRenderer); } -void UILabel::setText(const char* text) +void UILabel::setText(const std::string& text) { - if (!text) - { + if (text.size()==0) return; - } - std::string strText(text); - _labelRenderer->setString(strText.c_str()); + + _labelRenderer->setString(text); labelScaleChangedWithSize(); } -const char* UILabel::getStringValue() +const std::string& UILabel::getStringValue() { return _labelRenderer->getString(); } int UILabel::getStringLength() { - const char* str = _labelRenderer->getString(); - return strlen(str); + return _labelRenderer->getString().size(); } void UILabel::setFontSize(int size) @@ -99,7 +96,7 @@ void UILabel::setFontSize(int size) labelScaleChangedWithSize(); } -void UILabel::setFontName(const char* name) +void UILabel::setFontName(const std::string& name) { _fontName = name; _labelRenderer->setFontName(name); diff --git a/cocos/gui/UILabel.h b/cocos/gui/UILabel.h index 5c6a4a105b..c38945bb9a 100644 --- a/cocos/gui/UILabel.h +++ b/cocos/gui/UILabel.h @@ -57,14 +57,14 @@ public: * * @param text string value. */ - void setText(const char* text); + void setText(const std::string& text); /** * Gets the string value of label. * * @return text string value. */ - const char* getStringValue(); + const std::string& getStringValue(); /** * Gets the string length of label. @@ -85,7 +85,7 @@ public: * * @param font name. */ - void setFontName(const char* name); + void setFontName(const std::string& name); /** * Sets the touch scale enabled of label. diff --git a/cocos/gui/UILabelAtlas.cpp b/cocos/gui/UILabelAtlas.cpp index 8e8db6c422..17963f595f 100644 --- a/cocos/gui/UILabelAtlas.cpp +++ b/cocos/gui/UILabelAtlas.cpp @@ -50,12 +50,12 @@ UICCLabelAtlas* UICCLabelAtlas::create() return NULL; } -void UICCLabelAtlas::setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap); } -void UICCLabelAtlas::setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const std::string& string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, texture, itemWidth, itemHeight, startCharMap); } @@ -113,7 +113,7 @@ void UILabelAtlas::initRenderer() _renderer->addChild(_laberAtlasRenderer); } -void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap) +void UILabelAtlas::setProperty(const std::string& stringValue, const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap) { _stringValue = stringValue; _charMapFileName = charMapFile; @@ -125,14 +125,14 @@ void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, labelAtlasScaleChangedWithSize(); } -void UILabelAtlas::setStringValue(const char *value) +void UILabelAtlas::setStringValue(const std::string& value) { _stringValue = value; _laberAtlasRenderer->setString(value); labelAtlasScaleChangedWithSize(); } -const char* UILabelAtlas::getStringValue() +const std::string& UILabelAtlas::getStringValue() const { return _laberAtlasRenderer->getString(); } @@ -195,7 +195,7 @@ void UILabelAtlas::copySpecialProperties(UIWidget *widget) UILabelAtlas* labelAtlas = dynamic_cast(widget); if (labelAtlas) { - setProperty(labelAtlas->_stringValue.c_str(), labelAtlas->_charMapFileName.c_str(), labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap.c_str()); + setProperty(labelAtlas->_stringValue, labelAtlas->_charMapFileName, labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap); } } diff --git a/cocos/gui/UILabelAtlas.h b/cocos/gui/UILabelAtlas.h index 73b902633f..a33872ef0c 100644 --- a/cocos/gui/UILabelAtlas.h +++ b/cocos/gui/UILabelAtlas.h @@ -50,8 +50,8 @@ public: * Allocates and initializes. */ static UICCLabelAtlas* create(); - void setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); - void setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); virtual void updateDisplayedOpacity(GLubyte opacity); virtual void draw(void); }; @@ -78,13 +78,13 @@ public: static UILabelAtlas* create(); /** initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap); + void setProperty(const std::string& stringValue,const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap); //set string value for labelatlas. - void setStringValue(const char* value); + void setStringValue(const std::string& value); //get string value for labelatlas. - const char* getStringValue(); + const std::string& getStringValue() const; //override "setAnchorPoint" method of widget. virtual void setAnchorPoint(const cocos2d::Point &pt); diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index da79a1590b..311c0adfaa 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -105,7 +105,7 @@ bool UICCTextField::onTextFieldDetachWithIME(cocos2d::TextFieldTTF *pSender) void UICCTextField::insertText(const char * text, int len) { std::string str_text = text; - int str_len = strlen(cocos2d::TextFieldTTF::getString()); + int str_len = cocos2d::TextFieldTTF::getString().size(); if (strcmp(text, "\n") != 0) { @@ -321,18 +321,16 @@ void UITextField::setTouchSize(const cocos2d::Size &size) _touchHeight = size.height; } -void UITextField::setText(const char* text) +void UITextField::setText(const std::string& text) { - if (!text) - { + if (text.size()==0) return; - } - std::string strText(text); - _textFieldRenderer->setString(strText.c_str()); + + _textFieldRenderer->setString(text); textfieldRendererScaleChangedWithSize(); } -void UITextField::setPlaceHolder(const char *value) +void UITextField::setPlaceHolder(const std::string& value) { _textFieldRenderer->setPlaceHolder(value); textfieldRendererScaleChangedWithSize(); @@ -344,7 +342,7 @@ void UITextField::setFontSize(int size) textfieldRendererScaleChangedWithSize(); } -void UITextField::setFontName(const char *name) +void UITextField::setFontName(const std::string& name) { _textFieldRenderer->setFontName(name); textfieldRendererScaleChangedWithSize(); @@ -355,7 +353,7 @@ void UITextField::didNotSelectSelf() _textFieldRenderer->detachWithIME(); } -const char* UITextField::getStringValue() +const std::string& UITextField::getStringValue() { return _textFieldRenderer->getString(); } diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index ac5641114f..fc90ea9466 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -109,12 +109,12 @@ public: virtual bool init(); virtual void initRenderer(); void setTouchSize(const cocos2d::Size &size); - void setText(const char* text); - void setPlaceHolder(const char* value); + void setText(const std::string& text); + void setPlaceHolder(const std::string& value); void setFontSize(int size); - void setFontName(const char* name); + void setFontName(const std::string& name); virtual void didNotSelectSelf(); - const char* getStringValue(); + const std::string& getStringValue(); virtual bool onTouchBegan(const cocos2d::Point &touchPoint); void setMaxLengthEnabled(bool enable); bool isMaxLengthEnabled(); diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index fa87e4c9e5..1f18b31118 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -14,6 +14,11 @@ struct { const char *test_name; std::function callback; } g_aTestNames[] = { + + // + // TESTS MUST BE ORDERED ALPHABETICALLY + // violators will be prosecuted + // { "Accelerometer", []() { return new AccelerometerTestScene(); } }, { "ActionManagerTest", [](){return new ActionManagerTestScene(); } }, { "ActionsEaseTest", [](){return new ActionsEaseTestScene();} }, @@ -50,7 +55,6 @@ struct { { "FontTest", []() { return new FontTestScene(); } }, { "IntervalTest", [](){return new IntervalTestScene(); } }, { "KeyboardTest", []() { return new KeyboardTestScene(); } }, - { "MouseTest", []() { return new MouseTestScene(); } }, #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA) { "KeypadTest", []() { return new KeypadTestScene(); } }, #endif @@ -59,6 +63,7 @@ struct { { "LayerTest", [](){return new LayerTestScene();} }, { "MenuTest", [](){return new MenuTestScene();} }, { "MotionStreakTest", [](){return new MotionStreakTestScene();} }, + { "MouseTest", []() { return new MouseTestScene(); } }, { "MutiTouchTest", []() { return new MutiTouchTestScene(); } }, { "NodeTest", [](){return new CocosNodeTestScene();} }, { "ParallaxTest", [](){return new ParallaxTestScene(); } }, From 0fb85f88fbd058bd95f2b59a7d61713e6c485972 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 15:08:49 -0800 Subject: [PATCH 136/197] updates coding style. Everything is in MarkDown format. Much easier to read than in redmine --- docs/CODING_STYLE.md | 131 ---------------------------- docs/CODING_STYLE.md.REMOVED.git-id | 1 + 2 files changed, 1 insertion(+), 131 deletions(-) delete mode 100644 docs/CODING_STYLE.md create mode 100644 docs/CODING_STYLE.md.REMOVED.git-id diff --git a/docs/CODING_STYLE.md b/docs/CODING_STYLE.md deleted file mode 100644 index 4b7bf2a7c8..0000000000 --- a/docs/CODING_STYLE.md +++ /dev/null @@ -1,131 +0,0 @@ -# cocos2d-x C++ coding sytle - - -## Detailed information - -Please, refer to this document for a detailed version of the cocos2d-x C++ coding sytle: - -* [cocos2d-x c++ coding style](http://www.cocos2d-x.org/wiki/Cocos2d_c++_coding_style) - - -## Quick Sample - -Use this sample as a quick reference. But DO READ the detailed doc for more info. - -Header file: - -```c++ -/** - * We use Doxygen strings for documentation. - * All public classes, methods, structs should be documented using Doxygen Strings - */ -class CC_DLL Sprite : public NodeRGBA, public TextureProtocol -{ /* class braces start in a new line */ - -/* no indentation here for public, protected or private */ -/* First add all the "public" stuff, then all the "protected" stuff, and finally all the "private" stuff -public: - - /* we don't use tabs, we use spaces, and we use a 4 space identation */ - /* 1st add all static const */ - static const int INDEX_NOT_INITIALIZED = -1; - - /* then add all the creators and other relevant static methods */ - static Sprite* create(); - static Sprite* create(const char *filename); - static Sprite* create(const char *filename, const Rect& rect); - - /* if applicable, then add the consturctors / destructors */ - Sprite(); - virtual ~Sprite(void); - - /* then add all the initialization methods */ - /* notice that they are in the same order as the creators */ - virtual bool init(void); - virtual bool initWithTexture(Texture2D *texture); - virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - - - - /* then add the regular instace methods */ - virtual void updateTransform(void); - virtual SpriteBatchNode* getBatchNode(void); - virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - - - /* then add all the overriden methods */ - /* notice that all overriden methods must use the 'override' keyword */ - /* overriden methods are not forced to have doxygen strings UNLESS they change the behavior in a non obvios way */ - virtual void setPosition(const Point& pos) override; - virtual void setRotation(float rotation) override; - virtual void setRotationX(float rotationX) override; - - - /* once you finish with the 'public' methods, start with the 'protected' ones */ -protected: - - /* protected methods are not forced to have Doxygen strings, but if they have it, better */ - void updateColor(void); - virtual void setTextureCoords(Rect rect); - - /* After adding all the methods, add the ivars */ - /* all ivars must start with _ */ - /* Do not use Hungarian notation */ - TextureAtlas* _textureAtlas; - int _atlasIndex; - SpriteBatchNode* _batchNode; -}; - -``` - -Implementation file: - -```c++ -/* Do not use doxygen comments on the implementation file */ - -/* The methos MUST be in the same order as where declared in the header file */ - -Sprite* Sprite::create(const char *filename) -{ - /* Don't use tabs. Use spaces. Use 4-space indentation */ - Sprite *sprite = new Sprite(); - - /* put curly braces in the same line as in the 'if'*/ - /* leave a space between the 'if' and the '(' */ - /* don't leave spaces between '()' */ - if (sprite && sprite->initWithFile(filename)) { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -/* Initialization list can be indented to 0 spaces, or to 4 spaces. If in doubt, be consistent with the indentation already used in the file */ -/* Only use the Initialization lists for types that can't fail when initialized */ -Sprite::Sprite() -: _shouldBeHidden(false) -, _texture(nullptr) -, _physicsBody(nullptr) -{ -} - -/* use the 'initXXX' methods to initialize types that might fail */ -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) -{ - /* it ok not use use curly braces */ - if (something) - do_something(); - else - something_else(); - - /* but if you use curly branches in one branch, all the branches should use curly branches */ - if (something) { - do_something1(); - do_something2(); - } else { - so_something_else(); - } -} - -``` diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id new file mode 100644 index 0000000000..19a3855c35 --- /dev/null +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -0,0 +1 @@ +bf158b68747963e7f0b734954a407e63a30a69c3 \ No newline at end of file From 3300e46d0fa12edeb936c63d93a6016c7d690d00 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 15:37:41 -0800 Subject: [PATCH 137/197] More fixes to the C++ guide --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 19a3855c35..2238cbadfc 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -bf158b68747963e7f0b734954a407e63a30a69c3 \ No newline at end of file +1ab69691a01c1fe6e8d479756b556149e9726e35 \ No newline at end of file From 6d0be761eb7fbe65ec76449655f8df7a5cff3666 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 10:47:12 +0800 Subject: [PATCH 138/197] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 93e703edb1..f3dca88228 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -16,6 +16,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Armature: many bug fixed, add more samples, add function to skip some frames when playing animation [NEW] Arm64 support. [NEW] Added Mouse Support For Desktop Platforms. + [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From 21f8050a4d271a0b8fa74c6972554aa8e8858e52 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 10:50:28 +0800 Subject: [PATCH 139/197] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index f3dca88228..3df3b9aa44 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -38,6 +38,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] sys.localStorage.getItem() does not support non-ascii string. [FIX] cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device. [FIX] CCBReader can't play sequence automatically in JSB. + [NEW] main.js -> cocos2d-jsb.js [Lua Binding] [NEW] Added Armature lua binding and added test samples. From 61970934a241b32ca0d45cd68ea3527f23c69dba Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 10:55:49 +0800 Subject: [PATCH 140/197] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 3df3b9aa44..4582eee2eb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,6 +17,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Arm64 support. [NEW] Added Mouse Support For Desktop Platforms. [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. + [NEW] Sprite: Override setScale(float scaleX, float scaleY) [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From d936622070f4cef6791589014bd8b773c528255a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 19:00:31 -0800 Subject: [PATCH 141/197] Adds TOC to coding style --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 2238cbadfc..51a1dc866d 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -1ab69691a01c1fe6e8d479756b556149e9726e35 \ No newline at end of file +55fe4bd3605531a58a565c46eec20dee0f81ff97 \ No newline at end of file From d4f890a6ee32d57413757eaf431a2e3bc821005b Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 11:01:16 +0800 Subject: [PATCH 142/197] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 4582eee2eb..743d94f96f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -18,6 +18,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Added Mouse Support For Desktop Platforms. [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. [NEW] Sprite: Override setScale(float scaleX, float scaleY) + [NEW] External: added | operator for Control::EventType [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From 240fc2ade10226a2a57adaeeda2853a7fc8fc500 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 8 Nov 2013 03:10:36 +0000 Subject: [PATCH 143/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 52e968dfe0..32fcdc004b 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 52e968dfe02f077f56d4df6cc04e38c8b76e22b9 +Subproject commit 32fcdc004b3023c32b1ddc1fce6bcb86bbba9c41 From 935d472979e2900dab5537c040821ef874ad454a Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 8 Nov 2013 11:36:27 +0800 Subject: [PATCH 144/197] issue #3025: remove TextureCache::_sharedTextureCache --- cocos/2d/CCTextureCache.cpp | 4 ---- cocos/2d/CCTextureCache.h | 2 -- 2 files changed, 6 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index cf1e8887f9..840a110a77 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -51,8 +51,6 @@ NS_CC_BEGIN // implementation TextureCache -TextureCache* TextureCache::_sharedTextureCache = nullptr; - TextureCache * TextureCache::getInstance() { return Director::getInstance()->getTextureCache(); @@ -65,7 +63,6 @@ TextureCache::TextureCache() , _needQuit(false) , _asyncRefCount(0) { - CCASSERT(_sharedTextureCache == nullptr, "Attempted to allocate a second instance of a singleton."); } TextureCache::~TextureCache() @@ -76,7 +73,6 @@ TextureCache::~TextureCache() (it->second)->release(); CC_SAFE_DELETE(_loadingThread); - _sharedTextureCache = nullptr; } void TextureCache::destroyInstance() diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 7916696513..eaa4567e90 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -200,8 +200,6 @@ protected: int _asyncRefCount; std::unordered_map _textures; - - static TextureCache *_sharedTextureCache; }; #if CC_ENABLE_CACHE_TEXTURE_DATA From fd37d3e9734306fcf076673e80da40d6ada5c35e Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 8 Nov 2013 04:17:15 +0000 Subject: [PATCH 145/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 32fcdc004b..7199547f2f 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 32fcdc004b3023c32b1ddc1fce6bcb86bbba9c41 +Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 From 314f2ac62ed7da993b2571295ce0a3e21591562a Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 8 Nov 2013 14:13:39 +0800 Subject: [PATCH 146/197] use float instead for create point object --- cocos/base/CCGeometry.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 5f681914b0..fe5086cba9 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -293,16 +293,16 @@ Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, c return Point::ZERO; } -const Point Point::ZERO = Point(0, 0); -const Point Point::ANCHOR_MIDDLE = Point(0.5, 0.5); -const Point Point::ANCHOR_BOTTOM_LEFT = Point(0, 0); -const Point Point::ANCHOR_TOP_LEFT = Point(0, 1); -const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1, 0); -const Point Point::ANCHOR_TOP_RIGHT = Point(1, 1); -const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1, .5); -const Point Point::ANCHOR_MIDDLE_LEFT = Point(0, 0.5); -const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5, 1); -const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5, 0); +const Point Point::ZERO = Point(0.0f, 0.0f); +const Point Point::ANCHOR_MIDDLE = Point(0.5f, 0.5f); +const Point Point::ANCHOR_BOTTOM_LEFT = Point(0.0f, 0.0f); +const Point Point::ANCHOR_TOP_LEFT = Point(0.0f, 1.0f); +const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1.0f, 0.0f); +const Point Point::ANCHOR_TOP_RIGHT = Point(1.0f, 1.0f); +const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1.0f, 0.5f); +const Point Point::ANCHOR_MIDDLE_LEFT = Point(0.0f, 0.5f); +const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5f, 1.0f); +const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5f, 0.0f); // implementation of Size From da27169d4566ced6972c8561a9be1573bf91744b Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 8 Nov 2013 14:58:20 +0800 Subject: [PATCH 147/197] add "setUserObject" method --- cocos/gui/UICheckBox.cpp | 3 --- cocos/gui/UIPageView.cpp | 3 --- cocos/gui/UIScrollView.cpp | 3 --- cocos/gui/UISlider.cpp | 3 --- cocos/gui/UITextField.cpp | 3 --- cocos/gui/UIWidget.cpp | 14 ++++++++++---- cocos/gui/UIWidget.h | 20 ++++++++++++++++++++ 7 files changed, 30 insertions(+), 19 deletions(-) diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index c577a86fe6..e79be3d5f0 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -51,7 +51,6 @@ _frontCrossDisabledFileName("") UICheckBox::~UICheckBox() { - CC_SAFE_RELEASE(_selectedStateEventListener); _selectedStateEventListener = NULL; _selectedStateEventSelector = NULL; } @@ -302,9 +301,7 @@ void UICheckBox::unSelectedEvent() void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { - CC_SAFE_RELEASE(_selectedStateEventListener); _selectedStateEventListener = target; - CC_SAFE_RETAIN(_selectedStateEventListener); _selectedStateEventSelector = selector; } diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index bb88e6cb80..54b0713b7a 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -51,7 +51,6 @@ UIPageView::~UIPageView() { _pages->removeAllObjects(); CC_SAFE_RELEASE(_pages); - CC_SAFE_RELEASE(_eventListener); _eventListener = NULL; _eventSelector = NULL; } @@ -574,9 +573,7 @@ void UIPageView::pageTurningEvent() void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { - CC_SAFE_RELEASE(_eventListener); _eventListener = target; - CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 2654eeda53..ebf32514da 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -76,7 +76,6 @@ _eventSelector(NULL) UIScrollView::~UIScrollView() { - CC_SAFE_RELEASE(_eventListener); _eventListener = NULL; _eventSelector = NULL; } @@ -1531,9 +1530,7 @@ void UIScrollView::bounceRightEvent() void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { - CC_SAFE_RELEASE(_eventListener); _eventListener = target; - CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index d5e0eac9ae..b5c90ccfb8 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -58,7 +58,6 @@ _ballDTexType(UI_TEX_TYPE_LOCAL) UISlider::~UISlider() { - CC_SAFE_RELEASE(_slidPercentListener); _slidPercentListener = NULL; _slidPercentSelector = NULL; } @@ -414,9 +413,7 @@ float UISlider::getPercentWithBallPos(float px) void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { - CC_SAFE_RELEASE(_slidPercentListener); _slidPercentListener = target; - CC_SAFE_RETAIN(_slidPercentListener); _slidPercentSelector = selector; } diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 963d807ef1..6a95ac8605 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -283,7 +283,6 @@ _passwordStyleText("") UITextField::~UITextField() { - CC_SAFE_RELEASE(_eventListener); _eventListener = NULL; _eventSelector = NULL; } @@ -505,9 +504,7 @@ void UITextField::deleteBackwardEvent() void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { - CC_SAFE_RELEASE(_eventListener); _eventListener = target; - CC_SAFE_RETAIN(_eventListener); _eventSelector = selecor; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 7f2adc545a..ad63b28451 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -68,14 +68,14 @@ _sizeType(SIZE_ABSOLUTE), _sizePercent(cocos2d::Point::ZERO), _positionType(POSITION_ABSOLUTE), _positionPercent(cocos2d::Point::ZERO), -_isRunning(false) +_isRunning(false), +_userObject(NULL) { } UIWidget::~UIWidget() { - CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = NULL; _touchEventSelector = NULL; removeAllChildren(); @@ -87,6 +87,7 @@ UIWidget::~UIWidget() _layoutParameterDictionary->removeAllObjects(); CC_SAFE_RELEASE(_layoutParameterDictionary); CC_SAFE_RELEASE(_scheduler); + CC_SAFE_RELEASE(_userObject); } UIWidget* UIWidget::create() @@ -135,6 +136,13 @@ void UIWidget::onExit() _isRunning = false; arrayMakeObjectsPerformSelector(_children, onExit, UIWidget*); } + +void UIWidget::setUserObject(cocos2d::Object *pUserObject) +{ + CC_SAFE_RETAIN(pUserObject); + CC_SAFE_RELEASE(_userObject); + _userObject = pUserObject; +} bool UIWidget::addChild(UIWidget *child) { @@ -698,9 +706,7 @@ void UIWidget::longClickEvent() void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { - CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = target; - CC_SAFE_RETAIN(_touchEventListener); _touchEventSelector = selector; } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index f4f48f2a94..02db42e731 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -880,6 +880,25 @@ public: virtual void onEnter(); virtual void onExit(); + + virtual Object* getUserObject() { return _userObject; } + /** + * @js NA + * @lua NA + */ + virtual const Object* getUserObject() const { return _userObject; } + + /** + * Returns a user assigned Object + * + * Similar to UserData, but instead of holding a void* it holds an object. + * The UserObject will be retained once in this method, + * and the previous UserObject (if existed) will be relese. + * The UserObject will be released in Node's destructure. + * + * @param userObject A user assigned Object + */ + virtual void setUserObject(Object *userObject); /*temp action*/ void setActionTag(int tag); int getActionTag(); @@ -952,6 +971,7 @@ protected: PositionType _positionType; cocos2d::Point _positionPercent; bool _isRunning; + cocos2d::Object* _userObject; }; /** * @js NA From b726c6fd2c1f07dd7fac51fe8eb43b421c00def8 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 8 Nov 2013 16:47:33 +0800 Subject: [PATCH 148/197] issue #3025: move VolatileTexture static function to VolatileTextureMgr --- cocos/2d/CCRenderTexture.cpp | 4 +-- cocos/2d/CCTexture2D.cpp | 10 ++++---- cocos/2d/CCTextureCache.cpp | 48 ++++++++++++++++++------------------ cocos/2d/CCTextureCache.h | 41 ++++++++++++++++-------------- 4 files changed, 53 insertions(+), 50 deletions(-) diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 17697c9de5..8fa56c282d 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -102,11 +102,11 @@ void RenderTexture::listenToBackground(cocos2d::Object *obj) if (_UITextureImage) { const Size& s = _texture->getContentSizeInPixels(); - VolatileTexture::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); + VolatileTextureMgr::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); if ( _textureCopy ) { - VolatileTexture::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); + VolatileTextureMgr::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); } } else diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 397bdbf68a..2f0665afb4 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -434,7 +434,7 @@ Texture2D::Texture2D() Texture2D::~Texture2D() { #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::removeTexture(this); + VolatileTextureMgr::removeTexture(this); #endif CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name); @@ -1041,7 +1041,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin { #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture data - VolatileTexture::addStringTexture(this, text, textDefinition); + VolatileTextureMgr::addStringTexture(this, text, textDefinition); #endif bool bRet = false; @@ -1267,7 +1267,7 @@ void Texture2D::setTexParameters(const TexParams &texParams) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT ); #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } @@ -1287,7 +1287,7 @@ void Texture2D::setAliasTexParameters() glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); #if CC_ENABLE_CACHE_TEXTURE_DATA TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE}; - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } @@ -1307,7 +1307,7 @@ void Texture2D::setAntiAliasTexParameters() glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); #if CC_ENABLE_CACHE_TEXTURE_DATA TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE}; - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 840a110a77..7a5e835653 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -239,7 +239,7 @@ void TextureCache::addImageAsyncCallBack(float dt) #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture file name - VolatileTexture::addImageTexture(texture, filename); + VolatileTextureMgr::addImageTexture(texture, filename); #endif // cache the texture. retain it, since it is added in the map _textures.insert( std::make_pair(filename, texture) ); @@ -299,7 +299,7 @@ Texture2D * TextureCache::addImage(const std::string &path) { #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture file name - VolatileTexture::addImageTexture(texture, fullpath.c_str()); + VolatileTextureMgr::addImageTexture(texture, fullpath.c_str()); #endif // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); @@ -349,7 +349,7 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) } while (0); #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::addImage(texture, image); + VolatileTextureMgr::addImage(texture, image); #endif return texture; @@ -418,7 +418,7 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const void TextureCache::reloadAllTextures() { #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::reloadAllTextures(); + VolatileTextureMgr::reloadAllTextures(); #endif } @@ -458,8 +458,8 @@ void TextureCache::dumpCachedTextureInfo() const #if CC_ENABLE_CACHE_TEXTURE_DATA -std::list VolatileTexture::_textures; -bool VolatileTexture::_isReloading = false; +std::list VolatileTextureMgr::_textures; +bool VolatileTextureMgr::_isReloading = false; VolatileTexture::VolatileTexture(Texture2D *t) : _texture(t) @@ -474,16 +474,14 @@ VolatileTexture::VolatileTexture(Texture2D *t) _texParams.magFilter = GL_LINEAR; _texParams.wrapS = GL_CLAMP_TO_EDGE; _texParams.wrapT = GL_CLAMP_TO_EDGE; - _textures.push_back(this); } VolatileTexture::~VolatileTexture() { - _textures.remove(this); CC_SAFE_RELEASE(_uiImage); } -void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) +void VolatileTextureMgr::addImageTexture(Texture2D *tt, const char* imageFileName) { if (_isReloading) { @@ -492,20 +490,20 @@ void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kImageFile; + vt->_cashedImageType = VolatileTexture::kImageFile; vt->_fileName = imageFileName; vt->_pixelFormat = tt->getPixelFormat(); } -void VolatileTexture::addImage(Texture2D *tt, Image *image) +void VolatileTextureMgr::addImage(Texture2D *tt, Image *image) { VolatileTexture *vt = findVolotileTexture(tt); image->retain(); vt->_uiImage = image; - vt->_cashedImageType = kImage; + vt->_cashedImageType = VolatileTexture::kImage; } -VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) +VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt) { VolatileTexture *vt = 0; auto i = _textures.begin(); @@ -522,12 +520,13 @@ VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) if (! vt) { vt = new VolatileTexture(tt); + _textures.push_back(vt); } return vt; } -void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize) +void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize) { if (_isReloading) { @@ -536,14 +535,14 @@ void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Tex VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kImageData; + vt->_cashedImageType = VolatileTexture::kImageData; vt->_textureData = data; vt->_dataLen = dataLen; vt->_pixelFormat = pixelFormat; vt->_textureSize = contentSize; } -void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition) +void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition) { if (_isReloading) { @@ -552,12 +551,12 @@ void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const Fo VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kString; + vt->_cashedImageType = VolatileTexture::kString; vt->_text = text; vt->_fontDefinition = fontDefinition; } -void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams) +void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams) { VolatileTexture *vt = findVolotileTexture(t); @@ -571,7 +570,7 @@ void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams vt->_texParams.wrapT = texParams.wrapT; } -void VolatileTexture::removeTexture(Texture2D *t) +void VolatileTextureMgr::removeTexture(Texture2D *t) { auto i = _textures.begin(); while (i != _textures.end()) @@ -579,13 +578,14 @@ void VolatileTexture::removeTexture(Texture2D *t) VolatileTexture *vt = *i++; if (vt->_texture == t) { + _textures.remove(vt); delete vt; break; } } } -void VolatileTexture::reloadAllTextures() +void VolatileTextureMgr::reloadAllTextures() { _isReloading = true; @@ -598,7 +598,7 @@ void VolatileTexture::reloadAllTextures() switch (vt->_cashedImageType) { - case kImageFile: + case VolatileTexture::kImageFile: { Image* image = new Image(); long size = 0; @@ -616,7 +616,7 @@ void VolatileTexture::reloadAllTextures() CC_SAFE_RELEASE(image); } break; - case kImageData: + case VolatileTexture::kImageData: { vt->_texture->initWithData(vt->_textureData, vt->_dataLen, @@ -626,12 +626,12 @@ void VolatileTexture::reloadAllTextures() vt->_textureSize); } break; - case kString: + case VolatileTexture::kString: { vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition); } break; - case kImage: + case VolatileTexture::kImage: { vt->_texture->initWithImage(vt->_uiImage); } diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index eaa4567e90..8c988ff4c3 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -214,7 +214,7 @@ class VolatileTexture kImage, }ccCachedImageType; -public: +private: VolatileTexture(Texture2D *t); /** * @js NA @@ -222,25 +222,8 @@ public: */ ~VolatileTexture(); - static void addImageTexture(Texture2D *tt, const char* imageFileName); - static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition); - static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize); - static void addImage(Texture2D *tt, Image *image); - - static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams); - static void removeTexture(Texture2D *t); - static void reloadAllTextures(); - -public: - static std::list _textures; - static bool _isReloading; - -private: - // find VolatileTexture by Texture2D* - // if not found, create a new one - static VolatileTexture* findVolotileTexture(Texture2D *tt); - protected: + friend class VolatileTextureMgr; Texture2D *_texture; Image *_uiImage; @@ -259,6 +242,26 @@ protected: FontDefinition _fontDefinition; }; +class VolatileTextureMgr +{ +public: + static void addImageTexture(Texture2D *tt, const char* imageFileName); + static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition); + static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize); + static void addImage(Texture2D *tt, Image *image); + + static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams); + static void removeTexture(Texture2D *t); + static void reloadAllTextures(); +public: + static std::list _textures; + static bool _isReloading; +private: + // find VolatileTexture by Texture2D* + // if not found, create a new one + static VolatileTexture* findVolotileTexture(Texture2D *tt); +}; + #endif // end of textures group From eeedab78b2485c9b317fb8beabf8c9b24896a6e2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 8 Nov 2013 18:13:24 +0800 Subject: [PATCH 149/197] [LINUX] Adding template CMake files for linux. --- template/multi-platform-cpp/CMakeLists.txt | 143 ++++++++++++++++++++ template/multi-platform-lua/CMakeLists.txt | 149 +++++++++++++++++++++ tools/travis-scripts/run-script.sh | 7 + 3 files changed, 299 insertions(+) create mode 100644 template/multi-platform-cpp/CMakeLists.txt create mode 100644 template/multi-platform-lua/CMakeLists.txt diff --git a/template/multi-platform-cpp/CMakeLists.txt b/template/multi-platform-cpp/CMakeLists.txt new file mode 100644 index 0000000000..88299d0d83 --- /dev/null +++ b/template/multi-platform-cpp/CMakeLists.txt @@ -0,0 +1,143 @@ +cmake_minimum_required(VERSION 2.6) + +set(APP_NAME HelloCpp) +project (${APP_NAME}) + +include(../../build/BuildHelpers.CMakeLists.txt) + +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(USE_BOX2D "Use box2d for physics library" OFF) +option(DEBUG_MODE "Debug or release?" ON) + +if(DEBUG_MODE) + set(CMAKE_BUILD_TYPE DEBUG) +else(DEBUG_MODE) + set(CMAKE_BUILD_TYPE RELEASE) +endif(DEBUG_MODE) + +set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") + +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1) +else(USE_CHIPMUNK) + message(FATAL_ERROR "Must choose a physics library.") +endif(USE_CHIPMUNK) + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + + +set(GAME_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp + Classes/HelloWorldScene.cpp +) + +set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/../..) + +include_directories( + ${COCOS2D_ROOT} + ${COCOS2D_ROOT}/cocos + ${COCOS2D_ROOT}/cocos/audio/include + ${COCOS2D_ROOT}/cocos/2d + ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/linux + ${COCOS2D_ROOT}/cocos/base + ${COCOS2D_ROOT}/cocos/physics + ${COCOS2D_ROOT}/cocos/editor-support + ${COCOS2D_ROOT}/cocos/math/kazmath/include + ${COCOS2D_ROOT}/extensions + ${COCOS2D_ROOT}/external + ${COCOS2D_ROOT}/external/jpeg/include/linux + ${COCOS2D_ROOT}/external/tiff/include/linux + ${COCOS2D_ROOT}/external/webp/include/linux + ${COCOS2D_ROOT}/external/glfw3/include/linux + ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tinyxml2 + ${COCOS2D_ROOT}/external/unzip + ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk + ${COCOS2D_ROOT}/external/freetype2/include/linux + ${COCOS2D_ROOT}/external/linux-specific/fmod/include/${ARCH_DIR} +) + +link_directories( + /usr/local/lib + ${COCOS2D_ROOT}/lib + ${COCOS2D_ROOT}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} +) + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(${APP_NAME} + gui + network + curl + ldap + lber + idn + rtmp + spine + cocostudio + jsoncpp + cocosbuilder + extensions + box2d + audio + ${FMOD_LIB} + cocos2d + cocosbase + chipmunk + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + pthread + glfw + GLEW + GL + X11 + rt + z + ) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/template/multi-platform-lua/CMakeLists.txt b/template/multi-platform-lua/CMakeLists.txt new file mode 100644 index 0000000000..a3cf368403 --- /dev/null +++ b/template/multi-platform-lua/CMakeLists.txt @@ -0,0 +1,149 @@ +cmake_minimum_required(VERSION 2.6) + +set(APP_NAME HelloLua) +project (${APP_NAME}) + +include(../../build/BuildHelpers.CMakeLists.txt) + +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(USE_BOX2D "Use box2d for physics library" OFF) +option(DEBUG_MODE "Debug or release?" ON) + +if(DEBUG_MODE) + set(CMAKE_BUILD_TYPE DEBUG) +else(DEBUG_MODE) + set(CMAKE_BUILD_TYPE RELEASE) +endif(DEBUG_MODE) + +set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") + +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1) +else(USE_CHIPMUNK) + message(FATAL_ERROR "Must choose a physics library.") +endif(USE_CHIPMUNK) + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + + +set(GAME_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/../..) + +include_directories( + Classes + ${COCOS2D_ROOT}/cocos/scripting/lua/bindings + ${COCOS2D_ROOT}/external/lua/lua + ${COCOS2D_ROOT}/external/lua/tolua + ${COCOS2D_ROOT} + ${COCOS2D_ROOT}/cocos + ${COCOS2D_ROOT}/cocos/audio/include + ${COCOS2D_ROOT}/cocos/2d + ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/linux + ${COCOS2D_ROOT}/cocos/base + ${COCOS2D_ROOT}/cocos/physics + ${COCOS2D_ROOT}/cocos/editor-support + ${COCOS2D_ROOT}/cocos/math/kazmath/include + ${COCOS2D_ROOT}/extensions + ${COCOS2D_ROOT}/external + ${COCOS2D_ROOT}/external/jpeg/include/linux + ${COCOS2D_ROOT}/external/tiff/include/linux + ${COCOS2D_ROOT}/external/webp/include/linux + ${COCOS2D_ROOT}/external/glfw3/include/linux + ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tinyxml2 + ${COCOS2D_ROOT}/external/unzip + ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk + ${COCOS2D_ROOT}/external/freetype2/include/linux + ${COCOS2D_ROOT}/external/linux-specific/fmod/include/${ARCH_DIR} +) + +link_directories( + /usr/local/lib + ${COCOS2D_ROOT}/lib + ${COCOS2D_ROOT}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} +) + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(${APP_NAME} + luabinding + tolua + lua + gui + network + curl + ldap + lber + idn + rtmp + spine + cocostudio + jsoncpp + cocosbuilder + extensions + box2d + audio + ${FMOD_LIB} + cocos2d + cocosbase + chipmunk + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + pthread + glfw + GLEW + GL + X11 + rt + z + ) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index e8d45a1415..4852ab01f9 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -76,6 +76,13 @@ elif [ "$PLATFORM"x = "linux"x ]; then cd linux-build cmake ../.. make -j10 + cd ../../multi-platform-cpp + cmake . + make -j10 + cd ../multi-platform-lua + cmake . + make -j10 + elif [ "$PLATFORM"x = "emscripten"x ]; then # Generate binding glue codes echo "Generating bindings glue codes ..." From 74497e18ec6ca5f439b1c1ead052e13a8d426341 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 8 Nov 2013 18:25:58 +0800 Subject: [PATCH 150/197] [CMake template] Fix compilation errors. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 4852ab01f9..b609c7cc43 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -76,7 +76,7 @@ elif [ "$PLATFORM"x = "linux"x ]; then cd linux-build cmake ../.. make -j10 - cd ../../multi-platform-cpp + cd ../../template/multi-platform-cpp cmake . make -j10 cd ../multi-platform-lua From 5faae4a51ea262b911e40320c481feb69c505c0a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 11:30:50 -0800 Subject: [PATCH 152/197] removes exe bit from text files --- .../android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java | 0 .../android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java | 0 .../platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java | 0 cocos/2d/platform/ios/EAGLView.h | 0 cocos/2d/platform/ios/OpenGL_Internal.h | 0 cocos/2d/platform/mac/EAGLView.h | 0 cocos/audio/mac/CDXMacOSXSupport.h | 0 cocos/audio/mac/CDXMacOSXSupport.mm | 0 cocos/audio/proj.linux/.cproject | 0 cocos/audio/proj.linux/.project | 0 cocos/editor-support/cocostudio/CCSGUIReader.cpp | 0 cocos/editor-support/cocostudio/CCSGUIReader.h | 0 cocos/scripting/lua/script/json.lua | 0 13 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java mode change 100755 => 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java mode change 100755 => 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java mode change 100755 => 100644 cocos/2d/platform/ios/EAGLView.h mode change 100755 => 100644 cocos/2d/platform/ios/OpenGL_Internal.h mode change 100755 => 100644 cocos/2d/platform/mac/EAGLView.h mode change 100755 => 100644 cocos/audio/mac/CDXMacOSXSupport.h mode change 100755 => 100644 cocos/audio/mac/CDXMacOSXSupport.mm mode change 100755 => 100644 cocos/audio/proj.linux/.cproject mode change 100755 => 100644 cocos/audio/proj.linux/.project mode change 100755 => 100644 cocos/editor-support/cocostudio/CCSGUIReader.cpp mode change 100755 => 100644 cocos/editor-support/cocostudio/CCSGUIReader.h mode change 100755 => 100644 cocos/scripting/lua/script/json.lua diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/ios/EAGLView.h b/cocos/2d/platform/ios/EAGLView.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/ios/OpenGL_Internal.h b/cocos/2d/platform/ios/OpenGL_Internal.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/mac/EAGLView.h b/cocos/2d/platform/mac/EAGLView.h old mode 100755 new mode 100644 diff --git a/cocos/audio/mac/CDXMacOSXSupport.h b/cocos/audio/mac/CDXMacOSXSupport.h old mode 100755 new mode 100644 diff --git a/cocos/audio/mac/CDXMacOSXSupport.mm b/cocos/audio/mac/CDXMacOSXSupport.mm old mode 100755 new mode 100644 diff --git a/cocos/audio/proj.linux/.cproject b/cocos/audio/proj.linux/.cproject old mode 100755 new mode 100644 diff --git a/cocos/audio/proj.linux/.project b/cocos/audio/proj.linux/.project old mode 100755 new mode 100644 diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp old mode 100755 new mode 100644 diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h old mode 100755 new mode 100644 diff --git a/cocos/scripting/lua/script/json.lua b/cocos/scripting/lua/script/json.lua old mode 100755 new mode 100644 From f7bae6e6cb3f43391db5b54f2b6f3304d80844f6 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 19:09:21 -0800 Subject: [PATCH 153/197] coding style migrated to version 3.274 --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 51a1dc866d..57c2f6e178 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -55fe4bd3605531a58a565c46eec20dee0f81ff97 \ No newline at end of file +b8582573e1c08366c74eb53e1b9d47abb7b87f31 \ No newline at end of file From 614c6469ff930e68a242791a252c29fe7ab54531 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 19:10:38 -0800 Subject: [PATCH 154/197] Adds TOC --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 57c2f6e178..65198295ec 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -b8582573e1c08366c74eb53e1b9d47abb7b87f31 \ No newline at end of file +8944142222e4befc64d10add9f9efae2f8172191 \ No newline at end of file From 173b5f634932d94e9f7b300574d3d915985b907a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 19:13:50 -0800 Subject: [PATCH 155/197] fixes markdown --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 65198295ec..d995f1bb82 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -8944142222e4befc64d10add9f9efae2f8172191 \ No newline at end of file +53b75602e396f08d8700d154b7954d678c2d5894 \ No newline at end of file From 94ad801f3dfd9329423535a778d3a9d57dc993d2 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 20:53:34 -0800 Subject: [PATCH 156/197] Update CODING_STYLE.md --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index d995f1bb82..c8730de5d9 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -53b75602e396f08d8700d154b7954d678c2d5894 \ No newline at end of file +c563be83fa634d5f28d62f647ec099ece413b17a \ No newline at end of file From 9f16bfadd152e14ea60e24695fd7e3655753b46a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 20:59:27 -0800 Subject: [PATCH 157/197] updated TOC --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index c8730de5d9..2a00974e4b 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -c563be83fa634d5f28d62f647ec099ece413b17a \ No newline at end of file +f86eb12e6d4835f93bd6f59d860970bcd2f74128 \ No newline at end of file From f3a5245bfa9a0a36471b0248cc68b4b58ddfb103 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 9 Nov 2013 18:11:57 +0800 Subject: [PATCH 158/197] Triggers an assert only onTouchBegan is nullptr for EventListenerTouchOneByOne. Fixes comments for checkAvailable. --- cocos/2d/CCEventListenerTouch.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index 1367645452..20e620910a 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -75,10 +75,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::create() bool EventListenerTouchOneByOne::checkAvailable() { - if (onTouchBegan == nullptr && onTouchMoved == nullptr - && onTouchEnded == nullptr && onTouchCancelled == nullptr) + if (onTouchBegan == nullptr) { - CCASSERT(false, "Invalid TouchEventListener."); + CCASSERT(false, "Invalid EventListenerTouchOneByOne!"); return false; } @@ -150,7 +149,7 @@ bool EventListenerTouchAllAtOnce::checkAvailable() if (onTouchesBegan == nullptr && onTouchesMoved == nullptr && onTouchesEnded == nullptr && onTouchesCancelled == nullptr) { - CCASSERT(false, "Invalid TouchEventListener."); + CCASSERT(false, "Invalid EventListenerTouchAllAtOnce!"); return false; } From 4fba832fb1f9200923777a0f66a3f54e3d58d37b Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 9 Nov 2013 21:05:17 +0800 Subject: [PATCH 159/197] Return non-zero if ndk build fails. --- build/android-build.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index d1a272c2db..c630010ef8 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -95,7 +95,8 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param): command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) else: command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) - os.system(command) + if os.system(command) != 0: + raise Exception("Build project [ " + app_android_root + " ] fails!") def copy_files(src, dst): @@ -205,4 +206,8 @@ if __name__ == '__main__': if len(args) == 0: usage() else: - build_samples(args, opts.ndk_build_param) + try: + build_samples(args, opts.ndk_build_param) + except Exception as e: + print e + sys.exit(1) From 5e36021d54ecd0d08aaae6c8d1919246e1db72e6 Mon Sep 17 00:00:00 2001 From: "Lee, Jae-Hong" Date: Sat, 9 Nov 2013 23:44:15 +0900 Subject: [PATCH 160/197] [Win32] fix argument type. - argument of interface is a long type. --- cocos/2d/platform/win32/CCFileUtilsWin32.cpp | 2 +- cocos/2d/platform/win32/CCFileUtilsWin32.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp index a5c94dac90..216797bd9e 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp @@ -121,7 +121,7 @@ bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const return false; } -unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, unsigned long* size) +unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, long* size) { unsigned char * pBuffer = NULL; CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.h b/cocos/2d/platform/win32/CCFileUtilsWin32.h index 4f01adabeb..5c88d97cf9 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.h +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.h @@ -58,7 +58,7 @@ protected: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size) override; + virtual unsigned char* getFileData(const char* filename, const char* mode, long * size) override; /** * Gets full path for filename, resolution directory and search path. From 3d23ca328ee0629cd95aff366134ede33e62f92f Mon Sep 17 00:00:00 2001 From: "Lee, Jae-Hong" Date: Sat, 9 Nov 2013 23:56:24 +0900 Subject: [PATCH 161/197] [Win32] fix compile error. - fix C2552 error in VS2012. --- cocos/gui/UILayout.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 70b66a0b56..a7af98c1b8 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -953,7 +953,7 @@ bool UIRectClippingNode::init() rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); rect[3] = cocos2d::Point(0, _clippingSize.height); - cocos2d::Color4F green = {0, 1, 0, 1}; + cocos2d::Color4F green(0, 1, 0, 1); _innerStencil->drawPolygon(rect, 4, green, 0, green); if (cocos2d::ClippingNode::init(_innerStencil)) { @@ -971,7 +971,7 @@ void UIRectClippingNode::setClippingSize(const cocos2d::Size &size) rect[1] = cocos2d::Point(_clippingSize.width, 0); rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); rect[3] = cocos2d::Point(0, _clippingSize.height); - cocos2d::Color4F green = {0, 1, 0, 1}; + cocos2d::Color4F green(0, 1, 0, 1); _innerStencil->clear(); _innerStencil->drawPolygon(rect, 4, green, 0, green); } From e132142689e84e3caba7122902cdf426f0730e8e Mon Sep 17 00:00:00 2001 From: "Lee, Jae-Hong" Date: Sat, 9 Nov 2013 23:57:18 +0900 Subject: [PATCH 162/197] [Win32] Update libGUI project - Update files list. --- cocos/gui/proj.win32/libGUI.vcxproj | 10 +++---- cocos/gui/proj.win32/libGUI.vcxproj.filters | 30 +++++++++------------ 2 files changed, 16 insertions(+), 24 deletions(-) diff --git a/cocos/gui/proj.win32/libGUI.vcxproj b/cocos/gui/proj.win32/libGUI.vcxproj index b225eaa127..2712ae3900 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj +++ b/cocos/gui/proj.win32/libGUI.vcxproj @@ -12,11 +12,8 @@ - - - @@ -24,7 +21,9 @@ + + @@ -37,11 +36,8 @@ - - - @@ -49,7 +45,9 @@ + + diff --git a/cocos/gui/proj.win32/libGUI.vcxproj.filters b/cocos/gui/proj.win32/libGUI.vcxproj.filters index 12f0d385ab..092f28f7e0 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj.filters +++ b/cocos/gui/proj.win32/libGUI.vcxproj.filters @@ -24,9 +24,6 @@ UIWidgets\ScrollWidget - - UIWidgets\ScrollWidget - UIWidgets\ScrollWidget @@ -72,12 +69,6 @@ System - - Layouts - - - Layouts - Layouts @@ -87,14 +78,17 @@ BaseClasses + + Layouts + + + Layouts + UIWidgets\ScrollWidget - - UIWidgets\ScrollWidget - UIWidgets\ScrollWidget @@ -140,12 +134,6 @@ System - - Layouts - - - Layouts - Layouts @@ -155,5 +143,11 @@ BaseClasses + + Layouts + + + Layouts + \ No newline at end of file From d4dbc7a4424992d5bb308ea4ae08691e635a5ad1 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Sun, 10 Nov 2013 09:21:33 +0800 Subject: [PATCH 163/197] Add conversion config for long type --- .../lua/bindings/LuaBasicConversions.cpp | 24 +++++++++++++++++++ .../lua/bindings/LuaBasicConversions.h | 1 + tools/bindings-generator | 2 +- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index 1914d3a930..4c91daa42b 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -283,6 +283,30 @@ bool luaval_to_point(lua_State* L,int lo,Point* outValue) return ok; } +bool luaval_to_long(lua_State* L,int lo, long* outValue) +{ + if (NULL == L || NULL == outValue) + return false; + + bool ok = true; + + tolua_Error tolua_err; + if (!tolua_isnumber(L,lo,0,&tolua_err)) + { +#if COCOS2D_DEBUG >=1 + luaval_to_native_err(L,"#ferror:",&tolua_err); +#endif + ok = false; + } + + if (ok) + { + *outValue = (long)tolua_tonumber(L, lo, 0); + } + + return ok; +} + bool luaval_to_size(lua_State* L,int lo,Size* outValue) { if (NULL == L || NULL == outValue) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h index 20167170df..2e2e525993 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.h +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.h @@ -30,6 +30,7 @@ extern bool luaval_to_boolean(lua_State* L,int lo,bool* outValue); extern bool luaval_to_number(lua_State* L,int lo,double* outValue); extern bool luaval_to_long_long(lua_State* L,int lo,long long* outValue); extern bool luaval_to_std_string(lua_State* L, int lo, std::string* outValue); +extern bool luaval_to_long(lua_State* L,int lo, long* outValue); extern bool luaval_to_point(lua_State* L,int lo,Point* outValue); extern bool luaval_to_size(lua_State* L,int lo,Size* outValue); diff --git a/tools/bindings-generator b/tools/bindings-generator index d41959ab0b..bf34fb73c4 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit d41959ab0b15c20aa0802ab5c9ef92be7b742bd4 +Subproject commit bf34fb73c4adece7b0c8194aa8ab57c5ce60fc58 From fa1a5c3735b122b145d08e3563e234257421c741 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Sun, 10 Nov 2013 11:03:27 +0800 Subject: [PATCH 164/197] Add conversion config for long type --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index bf34fb73c4..7ccbabbaa6 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit bf34fb73c4adece7b0c8194aa8ab57c5ce60fc58 +Subproject commit 7ccbabbaa677607048c511b33cb6d83b2081220e From 6e6c63e1112df6a7e2187f8114a0db1a86786f5a Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Sun, 10 Nov 2013 03:29:03 +0000 Subject: [PATCH 165/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 7199547f2f..c46cc8ed45 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 +Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 From c75c20de043a30c9383d25384cf75623c7baa1a0 Mon Sep 17 00:00:00 2001 From: dualface Date: Sun, 10 Nov 2013 11:49:52 +0800 Subject: [PATCH 166/197] fix Lua 5.2 compatibility --- cocos/scripting/lua/bindings/tolua_fix.c | 48 ++++++++++++------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/cocos/scripting/lua/bindings/tolua_fix.c b/cocos/scripting/lua/bindings/tolua_fix.c index 259a05242e..f03dd59b5f 100644 --- a/cocos/scripting/lua/bindings/tolua_fix.c +++ b/cocos/scripting/lua/bindings/tolua_fix.c @@ -9,7 +9,7 @@ TOLUA_API void toluafix_open(lua_State* L) lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); - + lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); @@ -30,29 +30,29 @@ TOLUA_API int toluafix_pushusertype_ccobject(lua_State* L, lua_pushnil(L); return -1; } - + if (*p_refid == 0) { *p_refid = refid; - + lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushlightuserdata(L, ptr); /* stack: refid_ptr refid ptr */ - + lua_rawset(L, -3); /* refid_ptr[refid] = ptr, stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ - + lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushstring(L, type); /* stack: refid_type refid type */ lua_rawset(L, -3); /* refid_type[refid] = type, stack: refid_type */ lua_pop(L, 1); /* stack: - */ - + //printf("[LUA] push CCObject OK - refid: %d, ptr: %x, type: %s\n", *p_refid, (int)ptr, type); } - + tolua_pushusertype(L, ptr, type); return 0; } @@ -63,7 +63,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) const char* type = NULL; void** ud = NULL; if (refid == 0) return -1; - + // get ptr from tolua_refid_ptr_mapping lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ @@ -78,14 +78,14 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) // printf("[LUA ERROR] remove CCObject with NULL ptr, refid: %d\n", refid); return -2; } - + // remove ptr from tolua_refid_ptr_mapping lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushnil(L); /* stack: refid_ptr refid nil */ lua_rawset(L, -3); /* delete refid_ptr[refid], stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ - - + + // get type from tolua_refid_type_mapping lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ @@ -97,16 +97,16 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) printf("[LUA ERROR] remove CCObject with NULL type, refid: %d, ptr: %p\n", refid, ptr); return -1; } - + type = lua_tostring(L, -1); lua_pop(L, 1); /* stack: refid_type */ - + // remove type from tolua_refid_type_mapping lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushnil(L); /* stack: refid_type refid nil */ lua_rawset(L, -3); /* delete refid_type[refid], stack: refid_type */ lua_pop(L, 1); /* stack: - */ - + // get ubox luaL_getmetatable(L, type); /* stack: mt */ lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ @@ -118,7 +118,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ lua_rawget(L, LUA_REGISTRYINDEX); /* stack: mt ubox */ }; - + lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_rawget(L,-2); /* stack: mt ubox ud */ if (lua_isnil(L, -1)) @@ -130,7 +130,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) } // cleanup peertable - lua_pushvalue(L, TOLUA_NOPEER); + lua_pushvalue(L, LUA_REGISTRYINDEX); lua_setfenv(L, -2); ud = (void**)lua_touserdata(L, -1); @@ -141,14 +141,14 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pop(L, 2); return -1; } - + // clean userdata *ud = NULL; - + lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_pushnil(L); /* stack: mt ubox ptr nil */ lua_rawset(L, -3); /* ubox[ptr] = nil, stack: mt ubox */ - + lua_pop(L, 2); //printf("[LUA] remove CCObject, refid: %d, ptr: %x, type: %s\n", refid, (int)ptr, type); return 0; @@ -158,19 +158,19 @@ TOLUA_API int toluafix_ref_function(lua_State* L, int lo, int def) { // function at lo if (!lua_isfunction(L, lo)) return 0; - + s_function_ref_id++; - + lua_pushstring(L, TOLUA_REFID_FUNCTION_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: fun ... refid_fun */ lua_pushinteger(L, s_function_ref_id); /* stack: fun ... refid_fun refid */ lua_pushvalue(L, lo); /* stack: fun ... refid_fun refid fun */ - + lua_rawset(L, -3); /* refid_fun[refid] = fun, stack: fun ... refid_ptr */ lua_pop(L, 1); /* stack: fun ... */ - + return s_function_ref_id; - + // lua_pushvalue(L, lo); /* stack: ... func */ // return luaL_ref(L, LUA_REGISTRYINDEX); } From 90df6fc763c3a29f0e90b94a46ffb71394ef6ffa Mon Sep 17 00:00:00 2001 From: Luis Parravicini Date: Sun, 10 Nov 2013 08:25:01 -0300 Subject: [PATCH 167/197] fixed typos --- tools/project-creator/create_project.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/project-creator/create_project.py b/tools/project-creator/create_project.py index be6e38babc..640fa4e038 100755 --- a/tools/project-creator/create_project.py +++ b/tools/project-creator/create_project.py @@ -30,7 +30,7 @@ def checkParams(): metavar="PROGRAMMING_NAME", type="choice", choices=["cpp", "lua", "javascript"], - help="Major programing language you want to used, should be [cpp | lua | javascript]") + help="Major programming language you want to use, should be [cpp | lua | javascript]") #parse the params (opts, args) = parser.parse_args() From 1f742b66756dabaf8e66f421741cb2a76259a0ad Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 10 Nov 2013 20:56:40 +0800 Subject: [PATCH 168/197] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 37e302de05..71b6680d05 100644 --- a/AUTHORS +++ b/AUTHORS @@ -643,6 +643,9 @@ Developers: Fixed a bug that EventListeners can't be removed sometimes. Fixed a bug that the data size has to be specified when parsing XML using TinyXML. + Luis Parravicini (luisparravicini) + Fixed typos in create_project.py. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From a6c85a3906b22a5ae38436cd08557e30d3a105d3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 10:23:05 +0800 Subject: [PATCH 169/197] issue #3137: Disabling Accelerometer when layer is destroyed. --- cocos/editor-support/cocostudio/CCInputDelegate.cpp | 3 +++ .../Classes/AccelerometerTest/AccelerometerTest.cpp | 1 + samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 10 ++++++++++ samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h | 2 ++ .../Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp | 2 ++ .../Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 5 +++++ samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h | 1 + 7 files changed, 24 insertions(+) diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index a134e3cdfe..03ac5030a7 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -47,6 +47,7 @@ InputDelegate::~InputDelegate(void) dispatcher->removeEventListener(_touchListener); dispatcher->removeEventListener(_keyboardListener); dispatcher->removeEventListener(_accelerometerListener); + Device::setAccelerometerEnabled(false); } bool InputDelegate::onTouchBegan(Touch *pTouch, Event *pEvent) @@ -196,6 +197,8 @@ void InputDelegate::setAccelerometerEnabled(bool enabled) dispatcher->removeEventListener(_accelerometerListener); _accelerometerListener = nullptr; + Device::setAccelerometerEnabled(enabled); + if (enabled) { auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(InputDelegate::onAcceleration, this)); diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index 5bc3d6a7ed..b1a8dcfcf9 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -21,6 +21,7 @@ AccelerometerTest::AccelerometerTest(void) AccelerometerTest::~AccelerometerTest(void) { _ball->release(); + Device::setAccelerometerEnabled(false); } std::string AccelerometerTest::title() diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index b7a60bb7a8..7fa35c81d1 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -10,6 +10,11 @@ // Bug624Layer // //////////////////////////////////////////////////////// +Bug624Layer::~Bug624Layer() +{ + Device::setAccelerometerEnabled(false); +} + bool Bug624Layer::init() { if(BugsTestBaseLayer::init()) @@ -51,6 +56,11 @@ void Bug624Layer::onAcceleration(Acceleration* acc, Event* event) // Bug624Layer2 // //////////////////////////////////////////////////////// +Bug624Layer2::~Bug624Layer2() +{ + Device::setAccelerometerEnabled(false); +} + bool Bug624Layer2::init() { if(BugsTestBaseLayer::init()) diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h index b5db348e67..6542ad95ba 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h @@ -6,6 +6,7 @@ class Bug624Layer : public BugsTestBaseLayer { public: + virtual ~Bug624Layer(); virtual bool init(); void switchLayer(float dt); virtual void onAcceleration(Acceleration* acc, Event* event); @@ -16,6 +17,7 @@ public: class Bug624Layer2 : public BugsTestBaseLayer { public: + virtual ~Bug624Layer2(); virtual bool init(); void switchLayer(float dt); virtual void onAcceleration(Acceleration* acc, Event* event); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 4a4cd5e027..99c01dec70 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -91,6 +91,8 @@ ChipmunkTestLayer::~ChipmunkTestLayer() } cpSpaceFree( _space ); + + Device::setAccelerometerEnabled(false); } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index cdc909b306..29f4b68e6d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -199,6 +199,11 @@ void PhysicsDemo::toggleDebugCallback(Object* sender) #endif } +PhysicsDemoClickAdd::~PhysicsDemoClickAdd() +{ + Device::setAccelerometerEnabled(false); +} + void PhysicsDemoClickAdd::onEnter() { PhysicsDemo::onEnter(); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 4ca37bd77b..a3ccc76e57 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -56,6 +56,7 @@ protected: class PhysicsDemoClickAdd : public PhysicsDemo { public: + virtual ~PhysicsDemoClickAdd(); void onEnter() override; std::string subtitle() override; From 0c4b6e7a3700853a1637310b38b87963a7926e78 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 10:40:51 +0800 Subject: [PATCH 170/197] Removing JSB Version since JSB source codes will be updated with cocos2d-x. Also, remove some unused codes. --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 2 +- .../javascript/bindings/js_bindings_core.cpp | 11 ----------- .../scripting/javascript/bindings/js_bindings_core.h | 5 ----- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 580a3b845e..263e2c0fae 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -246,7 +246,7 @@ JSBool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) } char version[256]; - snprintf(version, sizeof(version)-1, "%s - %s", cocos2dVersion(), JSB_version); + snprintf(version, sizeof(version)-1, "%s", cocos2dVersion()); JSString * js_version = JS_InternString(cx, version); jsval ret = STRING_TO_JSVAL(js_version); diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index fbb6e808fb..645f9fa94b 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -43,17 +43,6 @@ typedef struct _hashJSObject static tHashJSObject *hash = NULL; static tHashJSObject *reverse_hash = NULL; -// Globals -char* JSB_association_proxy_key = NULL; - -const char* JSB_version = "0.3-beta"; - - -static void its_finalize(JSFreeOp *fop, JSObject *obj) -{ - CCLOGINFO("Finalizing global class"); -} - //#pragma mark JSBCore - Helper free functions static void reportError(JSContext *cx, const char *message, JSErrorReport *report) { diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.h b/cocos/scripting/javascript/bindings/js_bindings_core.h index 958b969b2a..33553a9287 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.h +++ b/cocos/scripting/javascript/bindings/js_bindings_core.h @@ -30,10 +30,6 @@ #include "chipmunk.h" #include "SimpleAudioEngine.h" -// Globals -// one shared key for associations -extern char * JSB_association_proxy_key; - #ifdef __cplusplus extern "C" { #endif @@ -77,7 +73,6 @@ extern "C" { // needed for callbacks. It does nothing. JSBool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp); - extern const char* JSB_version; #ifdef __cplusplus } #endif From 27b82f8f67c4a0c82523a2d4f3a113ec10f118e4 Mon Sep 17 00:00:00 2001 From: Marc Lepage Date: Sun, 10 Nov 2013 22:00:50 -0500 Subject: [PATCH 171/197] Fix typos and other trivial cleanup --- cocos/2d/CCSprite.h | 162 ++++++++++++++++++++++---------------------- 1 file changed, 81 insertions(+), 81 deletions(-) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 0c0b652972..317effad84 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -24,8 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __SPITE_NODE_CCSPRITE_H__ -#define __SPITE_NODE_CCSPRITE_H__ +#ifndef __SPRITE_NODE_CCSPRITE_H__ +#define __SPRITE_NODE_CCSPRITE_H__ #include "CCNode.h" #include "CCProtocols.h" @@ -54,7 +54,7 @@ struct transformValues_; * @{ */ -/** +/** * Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) * * Sprite can be created with an image, or with a sub-rectangle of an image. @@ -88,14 +88,14 @@ public: /// @{ /// @name Creators - + /** * Creates an empty sprite without texture. You can call setTexture method subsequently. * * @return An empty sprite object that is marked as autoreleased. */ static Sprite* create(); - + /** * Creates a sprite with an image filename. * @@ -106,7 +106,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* create(const std::string& filename); - + /** * Creates a sprite with an image filename and a rect. * @@ -115,7 +115,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* create(const std::string& filename, const Rect& rect); - + /** * Creates a sprite with an exsiting texture contained in a Texture2D object * After creation, the rect will be the size of the texture, and the offset will be (0,0). @@ -124,7 +124,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithTexture(Texture2D *texture); - + /** * Creates a sprite with a texture and a rect. * @@ -136,7 +136,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithTexture(Texture2D *texture, const Rect& rect); - + /** * Creates a sprite with an sprite frame. * @@ -144,7 +144,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithSpriteFrame(SpriteFrame *pSpriteFrame); - + /** * Creates a sprite with an sprite frame name. * @@ -155,31 +155,31 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); - + /// @} end of creators group - - + + /// @{ /// @name Initializers - + /** * Default constructor * @js ctor */ Sprite(void); - + /** * Default destructor * @js NA * @lua NA */ virtual ~Sprite(void); - + /** * Initializes an empty sprite with nothing init. */ virtual bool init(void); - + /** * Initializes a sprite with a texture. * @@ -190,7 +190,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture); - + /** * Initializes a sprite with a texture and a rect. * @@ -202,7 +202,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - + /** * Initializes a sprite with a texture and a rect in points, optionally rotated. * @@ -215,7 +215,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated); - + /** * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite * @@ -223,7 +223,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); - + /** * Initializes a sprite with an sprite frame name. * @@ -234,7 +234,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); - + /** * Initializes a sprite with an image filename. * @@ -248,7 +248,7 @@ public: * @lua init */ virtual bool initWithFile(const std::string& filename); - + /** * Initializes a sprite with an image filename, and a rect. * @@ -263,17 +263,17 @@ public: * @lua init */ virtual bool initWithFile(const std::string& filename, const Rect& rect); - + /// @} end of initializers /// @{ /// @name BatchNode methods - + /** - * Updates the quad according the rotation, position, scale values. + * Updates the quad according the rotation, position, scale values. */ virtual void updateTransform(void); - + /** * Returns the batch node object if this sprite is rendered by SpriteBatchNode * @@ -292,26 +292,26 @@ public: * @endcode */ virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - + /// @} end of BatchNode methods - - - + + + /// @{ /// @name Texture methods - + /** * Updates the texture rect of the Sprite in points. * It will call setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) with \p rotated = false, and \p utrimmedSize = rect.size. */ virtual void setTextureRect(const Rect& rect); - + /** * Sets the texture rect, rectRotated and untrimmed size of the Sprite in points. * It will update the texture coordinates and the vertex rectangle. */ virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize); - + /** * Sets the vertex rect. * It will be called internally by setTextureRect. @@ -319,34 +319,34 @@ public: * Do not call it manually. Use setTextureRect instead. */ virtual void setVertexRect(const Rect& rect); - - /// @} end of texture methods - - + /// @} end of texture methods + + + /// @{ /// @name Frames methods - + /** * Sets a new display frame to the Sprite. */ virtual void setDisplayFrame(SpriteFrame *pNewFrame); - + /** * Returns whether or not a SpriteFrame is being displayed */ virtual bool isFrameDisplayed(SpriteFrame *pFrame) const; - + /** @deprecated Use getDisplayFrame() instead */ CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); }; - + /** * Returns the current displayed frame. */ virtual SpriteFrame* getDisplayFrame(); - + /// @} End of frames methods - + /// @{ /// @name Animation methods @@ -356,23 +356,23 @@ public: */ virtual void setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex); /// @} - - + + /// @{ /// @name Sprite Properties' setter/getters - - /** + + /** * Whether or not the Sprite needs to be updated in the Atlas. * * @return true if the sprite needs to be updated in the Atlas, false otherwise. */ virtual bool isDirty(void) const { return _dirty; } - - /** + + /** * Makes the Sprite to be updated in the Atlas. */ virtual void setDirty(bool bDirty) { _dirty = bDirty; } - + /** * Returns the quad (tex coords, vertex coords and color) information. * @js NA @@ -380,24 +380,24 @@ public: */ inline V3F_C4B_T2F_Quad getQuad(void) const { return _quad; } - /** + /** * Returns whether or not the texture rectangle is rotated. */ inline bool isTextureRectRotated(void) const { return _rectRotated; } - - /** - * Returns the index used on the TextureAtlas. + + /** + * Returns the index used on the TextureAtlas. */ inline int getAtlasIndex(void) const { return _atlasIndex; } - - /** + + /** * Sets the index used on the TextureAtlas. * @warning Don't modify this value unless you know what you are doing */ inline void setAtlasIndex(int atlasIndex) { _atlasIndex = atlasIndex; } - /** - * Returns the rect of the Sprite in points + /** + * Returns the rect of the Sprite in points */ inline const Rect& getTextureRect(void) { return _rect; } @@ -405,19 +405,19 @@ public: * Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode */ inline TextureAtlas* getTextureAtlas(void) { return _textureAtlas; } - + /** * Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode */ inline void setTextureAtlas(TextureAtlas *pobTextureAtlas) { _textureAtlas = pobTextureAtlas; } - /** + /** * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. */ inline const Point& getOffsetPosition(void) const { return _offsetPosition; } - /** + /** * Returns the flag which indicates whether the sprite is flipped horizontally or not. * * It only flips the texture of the sprite, and not the texture of the sprite's children. @@ -425,48 +425,48 @@ public: * If you want to flip the anchorPoint too, and/or to flip the children too use: * sprite->setScaleX(sprite->getScaleX() * -1); * - * @return true if the sprite is flipped horizaontally, false otherwise. + * @return true if the sprite is flipped horizontally, false otherwise. */ bool isFlippedX(void) const; /** * Sets whether the sprite should be flipped horizontally or not. * - * @param bFlipX true if the sprite should be flipped horizaontally, false otherwise. + * @param flippedX true if the sprite should be flipped horizontally, false otherwise. */ void setFlippedX(bool flippedX); - - /** @deprecated Use isFlippedX() instead + + /** @deprecated Use isFlippedX() instead * @js NA * @lua NA */ CC_DEPRECATED_ATTRIBUTE bool isFlipX() { return isFlippedX(); }; /** @deprecated Use setFlippedX() instead */ - CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); }; - - /** + CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); }; + + /** * Return the flag which indicates whether the sprite is flipped vertically or not. - * + * * It only flips the texture of the sprite, and not the texture of the sprite's children. * Also, flipping the texture doesn't alter the anchorPoint. * If you want to flip the anchorPoint too, and/or to flip the children too use: * sprite->setScaleY(sprite->getScaleY() * -1); - * - * @return true if the sprite is flipped vertically, flase otherwise. + * + * @return true if the sprite is flipped vertically, false otherwise. */ bool isFlippedY(void) const; /** * Sets whether the sprite should be flipped vertically or not. * - * @param bFlipY true if the sprite should be flipped vertically, flase otherwise. + * @param flippedY true if the sprite should be flipped vertically, false otherwise. */ void setFlippedY(bool flippedY); - + /// @} End of Sprite properties getter/setters - + /** @deprecated Use isFlippedY() instead */ CC_DEPRECATED_ATTRIBUTE bool isFlipY() { return isFlippedY(); }; /** @deprecated Use setFlippedY() instead */ - CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; + CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; // // Overrides @@ -543,13 +543,13 @@ protected: TextureAtlas* _textureAtlas; /// SpriteBatchNode texture atlas (weak reference) int _atlasIndex; /// Absolute (real) Index on the SpriteSheet SpriteBatchNode* _batchNode; /// Used batch node (weak reference) - + bool _dirty; /// Whether the sprite needs to be updated bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated bool _hasChildren; /// Whether the sprite contains children bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible AffineTransform _transformToBatch; - + // // Data used when the sprite is self-rendered // @@ -575,8 +575,8 @@ protected: bool _opacityModifyRGB; // image is flipped - bool _flippedX; /// Whether the sprite is flipped horizaontally or not. - bool _flippedY; /// Whether the sprite is flipped vertically or not. + bool _flippedX; /// Whether the sprite is flipped horizontally or not + bool _flippedY; /// Whether the sprite is flipped vertically or not }; @@ -585,4 +585,4 @@ protected: NS_CC_END -#endif // __SPITE_NODE_CCSPRITE_H__ +#endif // __SPRITE_NODE_CCSPRITE_H__ From 02da3a29ccf68a99756c082d77644a4cf45e777b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 11:38:02 +0800 Subject: [PATCH 172/197] issue #3025: deprecate TextureCache::reloadAllTextures, call VolatileTextureMgr::reloadAllTextures instead --- cocos/2d/CCTextureCache.cpp | 7 ++++--- cocos/2d/CCTextureCache.h | 5 +++-- cocos/2d/platform/android/nativeactivity.cpp | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 7a5e835653..780e0330aa 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -417,9 +417,10 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const void TextureCache::reloadAllTextures() { -#if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTextureMgr::reloadAllTextures(); -#endif +//will do nothing +// #if CC_ENABLE_CACHE_TEXTURE_DATA +// VolatileTextureMgr::reloadAllTextures(); +// #endif } void TextureCache::waitForQuit() diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 8c988ff4c3..c4c14bad53 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -73,9 +73,10 @@ public: CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } /** Reload all textures - It's only useful when the value of CC_ENABLE_CACHE_TEXTURE_DATA is 1 + should not call it, called by frame work + now the function do nothing, use VolatileTextureMgr::reloadAllTextures */ - static void reloadAllTextures(); + CC_DEPRECATED_ATTRIBUTE static void reloadAllTextures(); public: /** diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index 12e25d597d..f0e52140ff 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -127,7 +127,7 @@ static void cocos_init(cocos_dimensions d, struct android_app* app) { cocos2d::GL::invalidateStateCache(); cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); cocos2d::DrawPrimitives::init(); - cocos2d::TextureCache::reloadAllTextures(); + cocos2d::VolatileTextureMgr::reloadAllTextures(); cocos2d::NotificationCenter::getInstance()->postNotification(EVNET_COME_TO_FOREGROUND, NULL); cocos2d::Director::getInstance()->setGLDefaultValues(); } From 6c1144ee796608a97733b723fe734fafd650c4ac Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 11 Nov 2013 12:49:38 +0800 Subject: [PATCH 173/197] issue #2770: fix some warning --- cocos/2d/CCLabelBMFont.cpp | 4 +- cocos/2d/CCLabelTextFormatter.cpp | 4 +- cocos/2d/CCProfiling.cpp | 2 +- cocos/2d/CCScene.cpp | 6 +- cocos/2d/CCScheduler.cpp | 64 +++++++++---------- cocos/2d/CCSpriteBatchNode.cpp | 4 +- cocos/base/atitc.cpp | 2 +- cocos/base/s3tc.cpp | 2 +- .../editor-support/cocosbuilder/CCBReader.cpp | 6 +- .../cocostudio/CCDataReaderHelper.cpp | 15 ++--- .../cocostudio/CCSSceneReader.cpp | 4 +- cocos/editor-support/spine/Animation.cpp | 12 ++-- cocos/editor-support/spine/SkeletonJson.cpp | 4 +- extensions/GUI/CCScrollView/CCSorting.cpp | 2 +- extensions/assets-manager/AssetsManager.cpp | 6 +- extensions/assets-manager/AssetsManager.h | 2 +- 16 files changed, 69 insertions(+), 70 deletions(-) diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index fe6026abfe..8eda86469e 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -1073,9 +1073,9 @@ void LabelBMFont::updateLabel() int size = multiline_string.size(); unsigned short* str_new = new unsigned short[size + 1]; - for (int i = 0; i < size; ++i) + for (int j = 0; j < size; ++j) { - str_new[i] = multiline_string[i]; + str_new[j] = multiline_string[j]; } str_new[size] = '\0'; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 87dd3cf7cd..6f85e1495a 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -200,9 +200,9 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) int size = multiline_string.size(); unsigned short* strNew = new unsigned short[size + 1]; - for (int i = 0; i < size; ++i) + for (int j = 0; j < size; ++j) { - strNew[i] = multiline_string[i]; + strNew[j] = multiline_string[j]; } strNew[size] = 0; diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 1db8ba0678..3c90394d58 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName) CCASSERT(timer, "CCProfilingTimer not found"); - long duration = chrono::duration_cast(now - timer->_startTime).count(); + long duration = static_cast(chrono::duration_cast(now - timer->_startTime).count()); timer->totalTime += duration; timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f; diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 3f05e43c83..9c636382dd 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -133,12 +133,12 @@ void Scene::addChildToPhysicsWorld(Node* child) if (_physicsWorld) { std::function addToPhysicsWorldFunc = nullptr; - addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void + addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void { - if (dynamic_cast(child) != nullptr) + if (dynamic_cast(obj) != nullptr) { - Node* node = dynamic_cast(child); + Node* node = dynamic_cast(obj); if (node->getPhysicsBody()) { diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 3f9c9da9f8..230e453a7f 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -601,31 +601,31 @@ void Scheduler::unscheduleAllWithMinPriority(int nMinPriority) } // Updates selectors - tListEntry *pEntry, *pTmp; + tListEntry *entry, *tmp; if(nMinPriority < 0) { - DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesNegList, entry, tmp) { - if(pEntry->priority >= nMinPriority) + if(entry->priority >= nMinPriority) { - unscheduleUpdateForTarget(pEntry->target); + unscheduleUpdateForTarget(entry->target); } } } if(nMinPriority <= 0) { - DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) + DL_FOREACH_SAFE(_updates0List, entry, tmp) { - unscheduleUpdateForTarget(pEntry->target); + unscheduleUpdateForTarget(entry->target); } } - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if(pEntry->priority >= nMinPriority) + if(entry->priority >= nMinPriority) { - unscheduleUpdateForTarget(pEntry->target); + unscheduleUpdateForTarget(entry->target); } } @@ -836,32 +836,32 @@ void Scheduler::update(float dt) } // Iterate over all the Updates' selectors - tListEntry *pEntry, *pTmp; + tListEntry *entry, *tmp; // updates with priority < 0 - DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesNegList, entry, tmp) { - if ((! pEntry->paused) && (! pEntry->markedForDeletion)) + if ((! entry->paused) && (! entry->markedForDeletion)) { - pEntry->target->update(dt); + entry->target->update(dt); } } // updates with priority == 0 - DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) + DL_FOREACH_SAFE(_updates0List, entry, tmp) { - if ((! pEntry->paused) && (! pEntry->markedForDeletion)) + if ((! entry->paused) && (! entry->markedForDeletion)) { - pEntry->target->update(dt); + entry->target->update(dt); } } // updates with priority > 0 - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if ((! pEntry->paused) && (! pEntry->markedForDeletion)) + if ((! entry->paused) && (! entry->markedForDeletion)) { - pEntry->target->update(dt); + entry->target->update(dt); } } @@ -909,43 +909,43 @@ void Scheduler::update(float dt) { for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) { - SchedulerScriptHandlerEntry* pEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); - if (pEntry->isMarkedForDeletion()) + SchedulerScriptHandlerEntry* eachEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + if (eachEntry->isMarkedForDeletion()) { _scriptHandlerEntries->removeObjectAtIndex(i); } - else if (!pEntry->isPaused()) + else if (!eachEntry->isPaused()) { - pEntry->getTimer()->update(dt); + eachEntry->getTimer()->update(dt); } } } // delete all updates that are marked for deletion // updates with priority < 0 - DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesNegList, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } // updates with priority == 0 - DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) + DL_FOREACH_SAFE(_updates0List, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } // updates with priority > 0 - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 820a999401..17198c8cce 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -598,8 +598,8 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) { auto next = std::next(it); - std::for_each(next, _descendants.end(), [](Sprite *sprite) { - sprite->setAtlasIndex( sprite->getAtlasIndex() - 1 ); + std::for_each(next, _descendants.end(), [](Sprite *spr) { + spr->setAtlasIndex( spr->getAtlasIndex() - 1 ); }); _descendants.erase(it); diff --git a/cocos/base/atitc.cpp b/cocos/base/atitc.cpp index 3a60d6d2f7..e93cb801b2 100644 --- a/cocos/base/atitc.cpp +++ b/cocos/base/atitc.cpp @@ -138,7 +138,7 @@ static void atitc_decode_block(uint8_t **blockData, { for (int x = 0; x < 4; ++x) { - initAlpha = (alpha & 0x0f) << 28; + initAlpha = (static_cast(alpha) & 0x0f) << 28; initAlpha += initAlpha >> 4; decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; pixelsIndex >>= 2; diff --git a/cocos/base/s3tc.cpp b/cocos/base/s3tc.cpp index e7869df631..2995849603 100644 --- a/cocos/base/s3tc.cpp +++ b/cocos/base/s3tc.cpp @@ -126,7 +126,7 @@ static void s3tc_decode_block(uint8_t **blockData, { for (int x = 0; x < 4; ++x) { - initAlpha = (alpha & 0x0f) << 28; + initAlpha = (static_cast(alpha) & 0x0f) << 28; initAlpha += initAlpha >> 4; decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; pixelsIndex >>= 2; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 154d2b0b36..d0a70c225b 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -482,12 +482,12 @@ int CCBReader::readInt(bool pSigned) { if(pSigned) { int s = current % 2; if(s) { - num = (int)(current / 2); + num = static_cast(current / 2); } else { - num = (int)(-current / 2); + num = static_cast(-current / 2); } } else { - num = current - 1; + num = static_cast(current - 1); } this->alignBits(); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index defb268ada..17f10067ed 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -579,8 +579,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML ArmatureData *armatureData = new ArmatureData(); armatureData->init(); - const char *name = armatureXML->Attribute(A_NAME); - armatureData->name = name; + armatureData->name = armatureXML->Attribute(A_NAME); tinyxml2::XMLElement *boneXML = armatureXML->FirstChildElement(BONE); @@ -888,21 +887,21 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) + for (int j = movBoneData->frameList.count() - 1; j >= 0; j--) { - if (i > 0) + if (j > 0) { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + float difSkewX = frames[j]->skewX - frames[j - 1]->skewX; + float difSkewY = frames[j]->skewY - frames[j - 1]->skewY; if (difSkewX < -M_PI || difSkewX > M_PI) { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + frames[j - 1]->skewX = difSkewX < 0 ? frames[j - 1]->skewX - 2 * M_PI : frames[j - 1]->skewX + 2 * M_PI; } if (difSkewY < -M_PI || difSkewY > M_PI) { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + frames[j - 1]->skewY = difSkewY < 0 ? frames[j - 1]->skewY - 2 * M_PI : frames[j - 1]->skewY + 2 * M_PI; } } } diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index f26b337d6a..25c84fd773 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -227,9 +227,9 @@ namespace cocostudio { const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); - for (long i = 0; i < childrenCount; ++i) + for (long j = 0; j < childrenCount; ++j) { - const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", i); + const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", j); std::string plistpath; plistpath += file_path; plistpath.append(plist); diff --git a/cocos/editor-support/spine/Animation.cpp b/cocos/editor-support/spine/Animation.cpp index 655e80be06..0cded9e16a 100644 --- a/cocos/editor-support/spine/Animation.cpp +++ b/cocos/editor-support/spine/Animation.cpp @@ -248,12 +248,12 @@ void _RotateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float bone = skeleton->bones[self->boneIndex]; if (time >= self->frames[self->framesLength - 2]) { /* Time is after last frame. */ - float amount = bone->data->rotation + self->frames[self->framesLength - 1] - bone->rotation; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - bone->rotation += amount * alpha; + float count = bone->data->rotation + self->frames[self->framesLength - 1] - bone->rotation; + while (count > 180) + count -= 360; + while (count < -180) + count += 360; + bone->rotation += count * alpha; return; } diff --git a/cocos/editor-support/spine/SkeletonJson.cpp b/cocos/editor-support/spine/SkeletonJson.cpp index 98e4be4334..6bfeeb24e7 100644 --- a/cocos/editor-support/spine/SkeletonJson.cpp +++ b/cocos/editor-support/spine/SkeletonJson.cpp @@ -118,7 +118,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S skeletonData->animationCount++; for (i = 0; i < boneCount; ++i) { - int timelineCount; + timelineCount = 0; Json* boneMap = Json_getItemAt(bones, i); const char* boneName = boneMap->name; @@ -175,7 +175,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S } for (i = 0; i < slotCount; ++i) { - int timelineCount; + timelineCount = 0; Json* slotMap = Json_getItemAt(slots, i); const char* slotName = slotMap->name; diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp index fd9d80f32c..412aa157e1 100644 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ b/extensions/GUI/CCScrollView/CCSorting.cpp @@ -33,7 +33,7 @@ class SortedObject : public Object, public SortableObject { public: SortedObject() : objectID(0) {} - virtual void setObjectID(unsigned int objectID) { this->objectID = objectID; } + virtual void setObjectID(unsigned int id) { this->objectID = id; } virtual unsigned int getObjectID() { return objectID; } private: unsigned int objectID; diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 31795c4f39..06e5bd11c6 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -214,7 +214,7 @@ void AssetsManager::downloadAndUncompress() _isDownloading = false; } -void AssetsManager::update() +void AssetsManager::update(float delta) { if (_isDownloading) return; @@ -651,8 +651,8 @@ AssetsManager* AssetsManager::create(const char* packageUrl, const char* version class DelegateProtocolImpl : public AssetsManagerDelegateProtocol { public : - DelegateProtocolImpl(ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback) - : errorCallback(errorCallback), progressCallback(progressCallback), successCallback(successCallback) + DelegateProtocolImpl(ErrorCallback aErrorCallback, ProgressCallback aProgressCallback, SuccessCallback aSuccessCallback) + : errorCallback(aErrorCallback), progressCallback(aProgressCallback), successCallback(aSuccessCallback) {} virtual void onError(AssetsManager::ErrorCode errorCode) { errorCallback(int(errorCode)); } diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index f3e413f4bd..5608084c76 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -98,7 +98,7 @@ public: /* @brief Download new package if there is a new version, and uncompress downloaded zip file. * Ofcourse it will set search path that stores downloaded files. */ - virtual void update(); + virtual void update(float delta) override; /* @brief Gets url of package. */ From 058cd9d896db46de077ad5ddd3fb2615fc14628f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 13:51:44 +0800 Subject: [PATCH 174/197] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 71b6680d05..d553c07d24 100644 --- a/AUTHORS +++ b/AUTHORS @@ -646,6 +646,9 @@ Developers: Luis Parravicini (luisparravicini) Fixed typos in create_project.py. + xhcnb + Device::setAccelerometerEnabled needs to be invoked before adding ACC listener. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From 55b9462b17eaa740a9cb2f831de025273f2412a5 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 14:21:41 +0800 Subject: [PATCH 175/197] issue #3025: directly use _textureCache in Director --- cocos/2d/CCDirector.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 5a10d83d1e..f948b099bf 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -867,14 +867,13 @@ void Director::getFPSImageData(unsigned char** datapointer, long* length) void Director::createStatsLabel() { Texture2D *texture = nullptr; - TextureCache *textureCache = _textureCache; if (_FPSLabel && _SPFLabel) { CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_SPFLabel); CC_SAFE_RELEASE_NULL(_drawsLabel); - textureCache->removeTextureForKey("/cc_fps_images"); + _textureCache->removeTextureForKey("/cc_fps_images"); FileUtils::getInstance()->purgeCachedEntries(); } @@ -891,7 +890,7 @@ void Director::createStatsLabel() return; } - texture = textureCache->addImage(image, "/cc_fps_images"); + texture = _textureCache->addImage(image, "/cc_fps_images"); CC_SAFE_RELEASE(image); /* From 9d5813b7d9fe2e449d94a63bd4848ed49cb26668 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 10 Nov 2013 11:23:34 +0800 Subject: [PATCH 176/197] =?UTF-8?q?Some=20fixes:=201)=20Moving=20the=20imp?= =?UTF-8?q?lementation=20of=20JSStringWrapper=20to=20.cpp=20file.=20Removi?= =?UTF-8?q?ng=20override=20operator()=20which=20will=20be=20easy=20to=20ma?= =?UTF-8?q?ke=20errors.=202)=20Deleting=20JSCallFuncWrapper=20since=20it?= =?UTF-8?q?=20isn=E2=80=99t=20needed=20after=20using=20std::function=20for?= =?UTF-8?q?=20MenuItem=E2=80=99s=20Callback.=203)=20Fixing=20ChipmunkTest?= =?UTF-8?q?=20crash=20sometimes=20on=20MAC=20platform(64bit).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../javascript/bindings/ScriptingCore.cpp | 82 +++++++++++++++---- .../javascript/bindings/ScriptingCore.h | 57 +++---------- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../javascript/bindings/cocos2d_specifics.hpp | 13 --- .../javascript/bindings/js_bindings_core.cpp | 12 +-- .../bindings/network/XMLHTTPRequest.cpp | 8 +- 6 files changed, 90 insertions(+), 84 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 263e2c0fae..22de38a70b 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -60,7 +60,7 @@ static std::vector g_queue; static std::mutex g_qMutex; static std::mutex g_rwMutex; static int clientSocket = -1; -static unsigned long s_nestedLoopLevel = 0; +static uint32_t s_nestedLoopLevel = 0; // server entry point for the bg thread static void serverEntryPoint(void); @@ -377,7 +377,7 @@ void ScriptingCore::string_report(jsval val) { LOGD("val : return string is NULL"); } else { JSStringWrapper wrapper(str); - LOGD("val : return string =\n%s\n", (char *)wrapper); + LOGD("val : return string =\n%s\n", wrapper.get()); } } else if (JSVAL_IS_NUMBER(val)) { double number; @@ -631,7 +631,7 @@ JSBool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &string); if (string) { JSStringWrapper wrapper(string); - js_log("%s", (char *)wrapper); + js_log("%s", wrapper.get()); } } return JS_TRUE; @@ -671,14 +671,14 @@ JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) // js::RootedObject* rootedGlobal = globals[name]; JSObject* debugObj = ScriptingCore::getInstance()->getDebugGlobal(); if (debugObj) { - res = ScriptingCore::getInstance()->runScript(path, debugObj); + res = ScriptingCore::getInstance()->runScript(path.get(), debugObj); } else { - JS_ReportError(cx, "Invalid global object: %s", (char*)name); + JS_ReportError(cx, "Invalid global object: %s", name.get()); return JS_FALSE; } } else { JSObject* glob = JS::CurrentGlobalOrNull(cx); - res = ScriptingCore::getInstance()->runScript(path, glob); + res = ScriptingCore::getInstance()->runScript(path.get(), glob); } return res; } @@ -764,12 +764,7 @@ void ScriptingCore::resumeSchedulesAndActions(js_proxy_t* p) void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) { - Array * arr = JSCallFuncWrapper::getTargetForNativeNode((Node*)p->ptr); - if (arr) { - arr->removeAllObjects(); - } - - arr = JSScheduleWrapper::getTargetForJSObject(p->obj); + Array* arr = JSScheduleWrapper::getTargetForJSObject(p->obj); if (arr) { Scheduler* pScheduler = Director::getInstance()->getScheduler(); Object* pObj = NULL; @@ -1297,7 +1292,7 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r else if (JSVAL_IS_STRING(*vp)) { JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); - pArray->addObject(String::create(str)); + pArray->addObject(String::create(str.get())); } else { @@ -2373,9 +2368,11 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "fontName", &jsr); JS_ValueToString(cx, jsr); JSStringWrapper wrapper(jsr); - if ( wrapper ) + const char* fontName = wrapper.get(); + + if (fontName && strlen(fontName) > 0) { - out->_fontName = (char*)wrapper; + out->_fontName = fontName; } else { @@ -2539,3 +2536,58 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) // we are done here return JS_TRUE; } + +// JSStringWrapper +JSStringWrapper::JSStringWrapper() +{ + _buffer = NULL; +} + +JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) +{ + set(str, cx); +} + +JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) +{ + set(val, cx); +} + +JSStringWrapper::~JSStringWrapper() +{ + if (_buffer) + { + //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); + delete[] _buffer; + } +} +void JSStringWrapper::set(jsval val, JSContext* cx) +{ + if (val.isString()) + { + this->set(val.toString(), cx); + } + else + { + _buffer = NULL; + } +} + +void JSStringWrapper::set(JSString* str, JSContext* cx) +{ + _string = str; + if (!cx) + { + cx = ScriptingCore::getInstance()->getGlobalContext(); + } + // JS_EncodeString isn't supported in SpiderMonkey ff19.0. + //buffer = JS_EncodeString(cx, string); + unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); + _buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); +} + +const char* JSStringWrapper::get() +{ + return _buffer ? _buffer : ""; +} + diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 992569afc9..6a78f827fe 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -248,54 +248,21 @@ JSObject* NewGlobalObject(JSContext* cx, bool debug = false); // just a simple utility to avoid mem leaking when using JSString class JSStringWrapper { - JSString* string; - const char* buffer; public: - JSStringWrapper() { - buffer = NULL; - } - JSStringWrapper(JSString* str, JSContext* cx = NULL) { - set(str, cx); - } - JSStringWrapper(jsval val, JSContext* cx = NULL) { - set(val, cx); - } - ~JSStringWrapper() { - if (buffer) { - //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); - delete[] buffer; - } - } - void set(jsval val, JSContext* cx) { - if (val.isString()) { - this->set(val.toString(), cx); - } else { - buffer = NULL; - } - } - void set(JSString* str, JSContext* cx) { - string = str; - if (!cx) { - cx = ScriptingCore::getInstance()->getGlobalContext(); - - } - // JS_EncodeString isn't supported in SpiderMonkey ff19.0. - //buffer = JS_EncodeString(cx, string); - unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); - buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); - } - std::string get() { - return buffer; - } + JSStringWrapper(); + JSStringWrapper(JSString* str, JSContext* cx = NULL); + JSStringWrapper(jsval val, JSContext* cx = NULL); + ~JSStringWrapper(); + + void set(jsval val, JSContext* cx); + void set(JSString* str, JSContext* cx); + const char* get(); - operator std::string() { - return std::string(buffer); - } - operator char*() { - return (char*)buffer; - } private: - /* Copy and assignment are not supported. */ + JSString* _string; + const char* _buffer; + + /* Copy and assignment are not supported. */ JSStringWrapper(const JSStringWrapper &another); JSStringWrapper &operator=(const JSStringWrapper &another); }; diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index bc82fe5227..141c335bfe 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -927efea93a520eeb9db9f62c8d8eb7a7b93b08dc \ No newline at end of file +3ba4ef8fa21631bee450ece05841803624c2e636 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index f7e9f2bdb4..3e98123689 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -101,19 +101,6 @@ protected: jsval _extraData; }; -class JSCallFuncWrapper: public JSCallbackWrapper { -public: - JSCallFuncWrapper() {} - virtual ~JSCallFuncWrapper(void) { - return; - } - - static void setTargetForNativeNode(Node *pNode, JSCallFuncWrapper *target); - static Array * getTargetForNativeNode(Node *pNode); - - void callbackFunc(Node *node); -}; - class JSScheduleWrapper: public JSCallbackWrapper { diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index 645f9fa94b..19d63c30e3 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -57,7 +57,7 @@ static void reportError(JSContext *cx, const char *message, JSErrorReport *repor void* jsb_get_proxy_for_jsobject(JSObject *obj) { tHashJSObject *element = NULL; - HASH_FIND_INT(hash, &obj, element); + HASH_FIND_PTR(hash, &obj, element); if( element ) return element->proxy; @@ -77,13 +77,13 @@ void jsb_set_proxy_for_jsobject(void *proxy, JSObject *obj) element->proxy = proxy; element->jsObject = obj; - HASH_ADD_INT( hash, jsObject, element ); + HASH_ADD_PTR( hash, jsObject, element ); } void jsb_del_proxy_for_jsobject(JSObject *obj) { tHashJSObject *element = NULL; - HASH_FIND_INT(hash, &obj, element); + HASH_FIND_PTR(hash, &obj, element); if( element ) { HASH_DEL(hash, element); free(element); @@ -96,7 +96,7 @@ void jsb_del_proxy_for_jsobject(JSObject *obj) JSObject* jsb_get_jsobject_for_proxy(void *proxy) { tHashJSObject *element = NULL; - HASH_FIND_INT(reverse_hash, &proxy, element); + HASH_FIND_PTR(reverse_hash, &proxy, element); if( element ) return element->jsObject; @@ -112,13 +112,13 @@ void jsb_set_jsobject_for_proxy(JSObject *jsobj, void* proxy) element->proxy = proxy; element->jsObject = jsobj; - HASH_ADD_INT( reverse_hash, proxy, element ); + HASH_ADD_PTR( reverse_hash, proxy, element ); } void jsb_del_jsobject_for_proxy(void* proxy) { tHashJSObject *element = NULL; - HASH_FIND_INT(reverse_hash, &proxy, element); + HASH_FIND_PTR(reverse_hash, &proxy, element); if( element ) { HASH_DEL(reverse_hash, element); free(element); diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index e3a0ba5b18..cb33e9d413 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -609,8 +609,8 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) JSStringWrapper w1(jsMethod); JSStringWrapper w2(jsURL); - method = w1; - urlstr = w2; + method = w1.get(); + urlstr = w2.get(); _url = urlstr; _meth = method; @@ -771,8 +771,8 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) JSStringWrapper w1(jsField); JSStringWrapper w2(jsValue); - field = w1; - value = w2; + field = w1.get(); + value = w2.get(); // Populate the request_header map. _setRequestHeader(field, value); From fe88f7c9414ef17fd272bba8ced625384b19c79f Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 10 Nov 2013 13:03:24 +0800 Subject: [PATCH 177/197] Fixing memory leak of JSStringWrapper::set . --- .../javascript/bindings/ScriptingCore.cpp | 17 +++++++++-------- .../javascript/bindings/ScriptingCore.h | 1 - 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 22de38a70b..bca4e18f53 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -2539,28 +2539,27 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) // JSStringWrapper JSStringWrapper::JSStringWrapper() +: _buffer(nullptr) { - _buffer = NULL; } JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) +: JSStringWrapper() { set(str, cx); } JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) +: JSStringWrapper() { set(val, cx); } JSStringWrapper::~JSStringWrapper() { - if (_buffer) - { - //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); - delete[] _buffer; - } + CC_SAFE_DELETE_ARRAY(_buffer); } + void JSStringWrapper::set(jsval val, JSContext* cx) { if (val.isString()) @@ -2569,13 +2568,14 @@ void JSStringWrapper::set(jsval val, JSContext* cx) } else { - _buffer = NULL; + CC_SAFE_DELETE_ARRAY(_buffer); } } void JSStringWrapper::set(JSString* str, JSContext* cx) { - _string = str; + CC_SAFE_DELETE_ARRAY(_buffer); + if (!cx) { cx = ScriptingCore::getInstance()->getGlobalContext(); @@ -2583,6 +2583,7 @@ void JSStringWrapper::set(JSString* str, JSContext* cx) // JS_EncodeString isn't supported in SpiderMonkey ff19.0. //buffer = JS_EncodeString(cx, string); unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); + _buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); } diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 6a78f827fe..7f0e367d92 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -259,7 +259,6 @@ public: const char* get(); private: - JSString* _string; const char* _buffer; /* Copy and assignment are not supported. */ From 5a0df8d2e893cfbb6ee42d494275f1a65a82befa Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 10:29:30 +0800 Subject: [PATCH 178/197] =?UTF-8?q?VS2012=20doesn=E2=80=99t=20support=20in?= =?UTF-8?q?voke=20another=20constructor=20method=20in=20current=20construc?= =?UTF-8?q?tor.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index bca4e18f53..1ce7234d88 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -2544,13 +2544,13 @@ JSStringWrapper::JSStringWrapper() } JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) -: JSStringWrapper() +: _buffer(nullptr) { set(str, cx); } JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) -: JSStringWrapper() +: _buffer(nullptr) { set(val, cx); } From 55cf30b7c8a494779e475ee7fae7d4ce871cef2f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 12:47:48 +0800 Subject: [PATCH 179/197] =?UTF-8?q?HASH=5FFIND=5FINT=20=E2=80=94>=20HASH?= =?UTF-8?q?=5FFIND=5FPTR=20for=20CCAcitonManager.cpp=20and=20CCScheduler.c?= =?UTF-8?q?pp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCActionManager.cpp | 18 +++++++++--------- cocos/2d/CCScheduler.cpp | 32 ++++++++++++++++---------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 4a01fd7663..0b258f4a6e 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -123,7 +123,7 @@ void ActionManager::removeActionAtIndex(long index, tHashElement *element) void ActionManager::pauseTarget(Object *target) { tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { element->paused = true; @@ -133,7 +133,7 @@ void ActionManager::pauseTarget(Object *target) void ActionManager::resumeTarget(Object *target) { tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { element->paused = false; @@ -176,14 +176,14 @@ void ActionManager::addAction(Action *action, Node *target, bool paused) tHashElement *element = NULL; // we should convert it to Object*, because we save it as Object* Object *tmp = target; - HASH_FIND_INT(_targets, &tmp, element); + HASH_FIND_PTR(_targets, &tmp, element); if (! element) { element = (tHashElement*)calloc(sizeof(*element), 1); element->paused = paused; target->retain(); element->target = target; - HASH_ADD_INT(_targets, target, element); + HASH_ADD_PTR(_targets, target, element); } actionAllocWithHashElement(element); @@ -215,7 +215,7 @@ void ActionManager::removeAllActionsFromTarget(Object *target) } tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged)) @@ -250,7 +250,7 @@ void ActionManager::removeAction(Action *action) tHashElement *element = NULL; Object *target = action->getOriginalTarget(); - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { long i = ccArrayGetIndexOfObject(element->actions, action); @@ -271,7 +271,7 @@ void ActionManager::removeActionByTag(int tag, Object *target) CCASSERT(target != NULL, ""); tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -298,7 +298,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const CCASSERT(tag != Action::INVALID_TAG, ""); tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -330,7 +330,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const { tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { return element->actions ? element->actions->num : 0; diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 230e453a7f..efc80847d0 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -294,7 +294,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in CCASSERT(target, "Argument target must be non-NULL"); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (! element) { @@ -304,7 +304,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in { target->retain(); } - HASH_ADD_INT(_hashForTimers, target, element); + HASH_ADD_PTR(_hashForTimers, target, element); // Is this the 1st element ? Then set the pause level to all the selectors of this target element->paused = paused; @@ -352,7 +352,7 @@ void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Object *target) //CCASSERT(selector); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { @@ -448,7 +448,7 @@ void Scheduler::priorityIn(tListEntry **list, Object *target, int priority, bool target->retain(); pHashElement->list = list; pHashElement->entry = listElement; - HASH_ADD_INT(_hashForUpdates, target, pHashElement); + HASH_ADD_PTR(_hashForUpdates, target, pHashElement); } void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) @@ -467,14 +467,14 @@ void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) target->retain(); pHashElement->list = list; pHashElement->entry = listElement; - HASH_ADD_INT(_hashForUpdates, target, pHashElement); + HASH_ADD_PTR(_hashForUpdates, target, pHashElement); } void Scheduler::scheduleUpdateForTarget(Object *target, int priority, bool paused) { tHashUpdateEntry *pHashElement = NULL; - HASH_FIND_INT(_hashForUpdates, &target, pHashElement); + HASH_FIND_PTR(_hashForUpdates, &target, pHashElement); if (pHashElement) { #if COCOS2D_DEBUG >= 1 @@ -509,7 +509,7 @@ bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Object *target) CCASSERT(target, "Argument target must be non-NULL"); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (!element) { @@ -541,7 +541,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry) { tHashUpdateEntry *element = NULL; - HASH_FIND_INT(_hashForUpdates, &entry->target, element); + HASH_FIND_PTR(_hashForUpdates, &entry->target, element); if (element) { // list entry @@ -567,7 +567,7 @@ void Scheduler::unscheduleUpdateForTarget(const Object *target) } tHashUpdateEntry *element = NULL; - HASH_FIND_INT(_hashForUpdates, &target, element); + HASH_FIND_PTR(_hashForUpdates, &target, element); if (element) { if (_updateHashLocked) @@ -645,7 +645,7 @@ void Scheduler::unscheduleAllForTarget(Object *target) // Custom Selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { @@ -702,7 +702,7 @@ void Scheduler::resumeTarget(Object *target) // custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { element->paused = false; @@ -710,7 +710,7 @@ void Scheduler::resumeTarget(Object *target) // update selector tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { CCASSERT(elementUpdate->entry != NULL, ""); @@ -724,7 +724,7 @@ void Scheduler::pauseTarget(Object *target) // custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { element->paused = true; @@ -732,7 +732,7 @@ void Scheduler::pauseTarget(Object *target) // update selector tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { CCASSERT(elementUpdate->entry != NULL, ""); @@ -746,7 +746,7 @@ bool Scheduler::isTargetPaused(Object *target) // Custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if( element ) { return element->paused; @@ -754,7 +754,7 @@ bool Scheduler::isTargetPaused(Object *target) // We should check update selectors if target does not have custom selectors tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if ( elementUpdate ) { return elementUpdate->entry->paused; From ff3bfbe8a27fc23580738a0d0e2aefa3be6cb641 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 12:54:36 +0800 Subject: [PATCH 180/197] Using std::unordered_map instead of UTHASH for js_type_class_t. Since xxx.hash_code() return size_t which is 8bytes on 64bit system, we should not use HASH_ADD_INT and HASH_FIND_INT for js_type_class_t. --- .../javascript/bindings/ScriptingCore.cpp | 14 +- .../chipmunk/js_bindings_chipmunk_manual.cpp | 137 +++++++++++------- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../javascript/bindings/cocos2d_specifics.hpp | 19 ++- .../bindings/js_bindings_opengl.cpp | 28 ++-- .../bindings/spidermonkey_specifics.h | 7 +- 6 files changed, 121 insertions(+), 86 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 1ce7234d88..462debba9d 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -67,7 +67,8 @@ static void serverEntryPoint(void); js_proxy_t *_native_js_global_ht = NULL; js_proxy_t *_js_native_global_ht = NULL; -js_type_class_t *_js_global_type_ht = NULL; +std::unordered_map _js_global_type_map; + static char *_js_log_buf = NULL; static std::vector registrationList; @@ -605,14 +606,13 @@ void ScriptingCore::cleanup() _js_log_buf = NULL; } - js_type_class_t* current, *tmp; - HASH_ITER(hh, _js_global_type_ht, current, tmp) + for (auto iter = _js_global_type_map.begin(); iter != _js_global_type_map.end(); ++iter) { - HASH_DEL(_js_global_type_ht, current); - free(current->jsclass); - free(current); + free(iter->second->jsclass); + free(iter->second); } - HASH_CLEAR(hh, _js_global_type_ht); + + _js_global_type_map.clear(); } void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorReport *report) diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index 903b777fde..d7c9f94f57 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -42,9 +42,13 @@ static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { T* cobj = new T(); cobj->autorelease(); js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - assert(p); + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + p = typeMapIter->second; + CCASSERT(p, "The value is null."); + JSObject *_tmp = JS_NewObject(cx, p->jsclass, p->proto, p->parentProto); js_proxy_t *pp = jsb_new_proxy(cobj, _tmp); JS_AddObjectRoot(cx, &pp->obj); @@ -179,10 +183,14 @@ JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_ do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -265,24 +273,27 @@ void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, cons }; TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t1.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSB_CCPhysicsDebugNode_object = JS_InitClass(cx, globalObj, typeClass->proto, JSB_CCPhysicsDebugNode_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); TypeTest t; js_type_class_t *p; typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = JSB_CCPhysicsDebugNode_class; p->proto = JSB_CCPhysicsDebugNode_object; p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } @@ -305,10 +316,13 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -331,10 +345,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -370,10 +386,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -393,29 +411,35 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, JSBool ok = JS_TRUE; const char* arg0; std::string arg0_tmp; - if (argc >= 1) { + if (argc == 1) { ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - } - PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return JS_FALSE; } void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) @@ -450,24 +474,25 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) }; TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t1.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSPROXY_CCPhysicsSprite_object = JS_InitClass(cx, globalObj, typeClass->proto, JSPROXY_CCPhysicsSprite_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); TypeTest t; js_type_class_t *p; typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = JSPROXY_CCPhysicsSprite_class; p->proto = JSPROXY_CCPhysicsSprite_object; p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 141c335bfe..bbc36bbe5b 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -3ba4ef8fa21631bee450ece05841803624c2e636 \ No newline at end of file +36a6cc6177c059364c6ccc3b1151b6475219b396 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index 3e98123689..9c03489007 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -39,14 +39,23 @@ extern callfuncTarget_proxy_t *_callfuncTarget_native_ht; */ template inline js_type_class_t *js_get_type_from_native(T* native_obj) { - js_type_class_t *typeProxy; + bool found = false; long typeId = typeid(*native_obj).hash_code(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeProxy); - if (!typeProxy) { + auto typeProxyIter = _js_global_type_map.find(typeId); + if (typeProxyIter == _js_global_type_map.end()) + { typeId = typeid(T).hash_code(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeProxy); + typeProxyIter = _js_global_type_map.find(typeId); + if (typeProxyIter != _js_global_type_map.end()) + { + found = true; + } } - return typeProxy; + else + { + found = true; + } + return found ? typeProxyIter->second : nullptr; } /** diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp index 9fbf145647..3a35eab630 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp @@ -32,24 +32,27 @@ JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) if (argc == 0) { GLNode* cobj = new GLNode(); -#ifdef COCOS2D_JAVASCRIPT cocos2d::Object *_ccobj = dynamic_cast(cobj); if (_ccobj) { _ccobj->autorelease(); } -#endif + TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); // link the native object with the javascript object js_proxy_t *p = jsb_new_proxy(cobj, obj); -#ifdef COCOS2D_JAVASCRIPT + JS_AddNamedObjectRoot(cx, &p->obj, "cocos2d::GLNode"); -#endif + return JS_TRUE; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); @@ -131,14 +134,13 @@ void js_register_cocos2dx_GLNode(JSContext *cx, JSObject *global) { // add the proto and JSClass to the type->js info hash table TypeTest t; js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + long typeId = t.s_id(); + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = js_cocos2dx_GLNode_class; p->proto = js_cocos2dx_GLNode_prototype; p->parentProto = jsb_Node_prototype; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } diff --git a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h index be9c709c49..e526ad7e7a 100644 --- a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h +++ b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h @@ -3,6 +3,7 @@ #include "jsapi.h" #include "uthash.h" +#include typedef struct js_proxy { void *ptr; @@ -14,20 +15,18 @@ extern js_proxy_t *_native_js_global_ht; extern js_proxy_t *_js_native_global_ht; typedef struct js_type_class { - uint32_t type; JSClass *jsclass; JSObject *proto; JSObject *parentProto; - UT_hash_handle hh; } js_type_class_t; -extern js_type_class_t *_js_global_type_ht; +extern std::unordered_map _js_global_type_map; template< typename DERIVED > class TypeTest { public: - static int s_id() + static long s_id() { // return id unique for DERIVED // NOT SURE IT WILL BE REALLY UNIQUE FOR EACH CLASS!! From 8f8d0f86d773a8a11b60bacadf2a7b0779e127e3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 13:02:20 +0800 Subject: [PATCH 181/197] Updating Bindings-generator. --- cocos/scripting/auto-generated | 2 +- tools/bindings-generator | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c46cc8ed45..7199547f2f 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 +Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 diff --git a/tools/bindings-generator b/tools/bindings-generator index 7ccbabbaa6..22520b8b34 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 7ccbabbaa677607048c511b33cb6d83b2081220e +Subproject commit 22520b8b34bcc73c2adfdf234798908a7dd563b4 From 9d7a8c44f94ff78c6907d0e75829f544a43bbc78 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 14:40:23 +0800 Subject: [PATCH 182/197] Reverts auto-generated. --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 7199547f2f..c46cc8ed45 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 +Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 From 00b477e7563fc4b427069e179d9a346423af7431 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 15:11:28 +0800 Subject: [PATCH 183/197] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 743d94f96f..e9e1da977c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -19,6 +19,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. [NEW] Sprite: Override setScale(float scaleX, float scaleY) [NEW] External: added | operator for Control::EventType + [NEW] Android & iOS screen size change support [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From 3fc16256ab2869eeb02e65b4684c629798e026d3 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 15:40:12 +0800 Subject: [PATCH 184/197] issue #3025: move deprecated texture cache implementation to cpp file --- cocos/2d/CCTextureCache.cpp | 10 ++++++++++ cocos/2d/CCTextureCache.h | 8 ++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 780e0330aa..c4276757c6 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -79,6 +79,16 @@ void TextureCache::destroyInstance() { } +TextureCache * TextureCache::sharedTextureCache() +{ + return TextureCache::getInstance(); +} + +void TextureCache::purgeSharedTextureCache() +{ + return TextureCache::destroyInstance(); +} + const char* TextureCache::description() const { return String::createWithFormat("", _textures.size() )->getCString(); diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index c4c14bad53..eb6ca47a22 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -50,6 +50,10 @@ NS_CC_BEGIN * @addtogroup textures * @{ */ +/* +* from version 3.0, TextureCache will never to treated as a singleton, it will be owned by director. +* all call by TextureCache::getInstance() should be replaced by Director::getInstance()->getTextureCache() +*/ /** @brief Singleton that handles the loading of textures * Once the texture is loaded, the next time it will return @@ -62,7 +66,7 @@ public: CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance(); /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache() { return TextureCache::getInstance(); } + CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache(); /** purges the cache. It releases the retained instance. @since v0.99.0 @@ -70,7 +74,7 @@ public: CC_DEPRECATED_ATTRIBUTE static void destroyInstance(); /** @deprecated Use destroyInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } + CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache(); /** Reload all textures should not call it, called by frame work From 796c75f834570277d7fc78f3cb1bcb16fe217898 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 15:56:15 +0800 Subject: [PATCH 185/197] [ci skip]change the building commands of linux --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1cfd3a014d..2b1a5fa297 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,12 @@ $ open samples.xcodeproj * For Linux ``` -$ cd cocos2d-x -$ cmake CMakeLists.txt -$ make +$ cd cocos2d-x/build +$ ./make-all-linux-project.sh ``` +You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. + * For Windows Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln` From 272afaa7d9d4cd11df732d63e3cb9f1ecfd7c273 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:57:15 +0800 Subject: [PATCH 186/197] Updating Bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 22520b8b34..a943736554 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 22520b8b34bcc73c2adfdf234798908a7dd563b4 +Subproject commit a94373655409f756b33d8a58cc798dcb00be257c From dfcae4ed0d6a1dd8d116c251a204d7c59bfcadec Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 16:04:34 +0800 Subject: [PATCH 187/197] issue #3025: change TextureCache::purgeSharedTextureCache() and TextureCache::sharedTextureCache() to do not call deprecate function anymore --- cocos/2d/CCTextureCache.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index c4276757c6..ab1e0c0eec 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -81,12 +81,11 @@ void TextureCache::destroyInstance() TextureCache * TextureCache::sharedTextureCache() { - return TextureCache::getInstance(); + return Director::getInstance()->getTextureCache(); } void TextureCache::purgeSharedTextureCache() { - return TextureCache::destroyInstance(); } const char* TextureCache::description() const From 2e52dd49050812625d1b9db5972121534276a2c2 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 11 Nov 2013 08:05:15 +0000 Subject: [PATCH 188/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c46cc8ed45..5788b25003 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 +Subproject commit 5788b2500339473ecc19acf1c2e43656a2537a6d From 0151ac60ba6cb69f45d8a7d32ac9b7fd58b21c6a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:26:25 +0800 Subject: [PATCH 189/197] =?UTF-8?q?fix=2064bit=20warning.=20unsigned=20int?= =?UTF-8?q?=20(int)=20=E2=80=94>=20long.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCActionInterval.cpp | 6 +++--- cocos/2d/CCActionManager.cpp | 2 +- cocos/2d/CCActionManager.h | 2 +- cocos/2d/CCAtlasNode.cpp | 4 ++-- cocos/2d/CCAtlasNode.h | 4 ++-- cocos/2d/CCTextureAtlas.cpp | 28 ++++++++++++++-------------- cocos/2d/CCTextureAtlas.h | 8 ++++---- cocos/2d/CCTextureCache.cpp | 2 +- 8 files changed, 28 insertions(+), 28 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 0fe7e055b9..14c0fec762 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -203,7 +203,7 @@ Sequence* Sequence::create(Array* arrayOfActions) Sequence* pRet = NULL; do { - unsigned int count = arrayOfActions->count(); + long count = arrayOfActions->count(); CC_BREAK_IF(count == 0); FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); @@ -576,7 +576,7 @@ Spawn* Spawn::create(Array *arrayOfActions) Spawn* pRet = NULL; do { - unsigned int count = arrayOfActions->count(); + long count = arrayOfActions->count(); CC_BREAK_IF(count == 0); FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); if (count > 1) @@ -2100,7 +2100,7 @@ void Animate::update(float t) } Array* frames = _animation->getFrames(); - int numberOfFrames = frames->count(); + long numberOfFrames = frames->count(); SpriteFrame *frameToDisplay = NULL; for( int i=_nextFrame; i < numberOfFrames; i++ ) { diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 0b258f4a6e..dd2b528bce 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -327,7 +327,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference -unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const +long ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 9e21a77125..8a2c077511 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -102,7 +102,7 @@ public: * - If you are running 1 Sequence of 7 actions, it will return 1. * - If you are running 7 Sequences of 2 actions, it will return 7. */ - unsigned int getNumberOfRunningActionsInTarget(const Object *target) const; + long getNumberOfRunningActionsInTarget(const Object *target) const; /** @deprecated use getNumberOfRunningActionsInTarget() instead */ CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); } diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 7ced2ffc9d..b756a36193 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -245,12 +245,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const return _textureAtlas; } -unsigned int AtlasNode::getQuadsToDraw() const +long AtlasNode::getQuadsToDraw() const { return _quadsToDraw; } -void AtlasNode::setQuadsToDraw(unsigned int uQuadsToDraw) +void AtlasNode::setQuadsToDraw(long uQuadsToDraw) { _quadsToDraw = uQuadsToDraw; } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 9f06456589..8c31496d41 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -77,8 +77,8 @@ public: void setTextureAtlas(TextureAtlas* textureAtlas); TextureAtlas* getTextureAtlas() const; - void setQuadsToDraw(unsigned int quadsToDraw); - unsigned int getQuadsToDraw() const; + void setQuadsToDraw(long quadsToDraw); + long getQuadsToDraw() const; // Overrides diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index f19a2f5f87..efb944db25 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -72,12 +72,12 @@ TextureAtlas::~TextureAtlas() #endif } -int TextureAtlas::getTotalQuads() const +long TextureAtlas::getTotalQuads() const { return _totalQuads; } -int TextureAtlas::getCapacity() const +long TextureAtlas::getCapacity() const { return _capacity; } @@ -216,7 +216,7 @@ void TextureAtlas::listenBackToForeground(Object *obj) const char* TextureAtlas::description() const { - return String::createWithFormat("", _totalQuads)->getCString(); + return String::createWithFormat("", _totalQuads)->getCString(); } @@ -357,7 +357,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); // issue #575. index can be > totalQuads - int remaining = (_totalQuads-1) - index - amount; + long remaining = (_totalQuads-1) - index - amount; // last object doesn't need to be moved if( remaining > 0) @@ -367,9 +367,9 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) } - int max = index + amount; + long max = index + amount; int j = 0; - for (int i = index; i < max ; i++) + for (long i = index; i < max ; i++) { _quads[index] = quads[j]; index++; @@ -390,9 +390,9 @@ void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) } // because it is ambiguous in iphone, so we implement abs ourselves // unsigned int howMany = abs( oldIndex - newIndex); - int howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); - int dst = oldIndex; - int src = oldIndex + 1; + long howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); + long dst = oldIndex; + long src = oldIndex + 1; if( oldIndex > newIndex) { dst = newIndex+1; @@ -412,7 +412,7 @@ void TextureAtlas::removeQuadAtIndex(long index) { CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); - int remaining = (_totalQuads-1) - index; + long remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining ) @@ -431,7 +431,7 @@ void TextureAtlas::removeQuadsAtIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); - int remaining = (_totalQuads) - (index + amount); + long remaining = (_totalQuads) - (index + amount); _totalQuads -= amount; @@ -456,7 +456,7 @@ bool TextureAtlas::resizeCapacity(long newCapacity) { return true; } - int oldCapactiy = _capacity; + long oldCapactiy = _capacity; // update capacity and totolQuads _totalQuads = MIN(_totalQuads, newCapacity); _capacity = newCapacity; @@ -575,8 +575,8 @@ void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount) V3F_C4B_T2F_Quad quad; memset(&quad, 0, sizeof(quad)); - int to = index + amount; - for (int i = index ; i < to ; i++) + long to = index + amount; + for (long i = index ; i < to ; i++) { _quads[i] = quad; } diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index 1e5ec742d7..42922ee80b 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -197,10 +197,10 @@ public: const char* description() const; /** Gets the quantity of quads that are going to be drawn */ - int getTotalQuads() const; + long getTotalQuads() const; /** Gets the quantity of quads that can be stored with the current texture atlas size */ - int getCapacity() const; + long getCapacity() const; /** Gets the texture of the texture atlas */ Texture2D* getTexture() const; @@ -231,9 +231,9 @@ protected: GLuint _buffersVBO[2]; //0: vertex 1: indices bool _dirty; //indicates whether or not the array buffer of the VBO needs to be updated /** quantity of quads that are going to be drawn */ - int _totalQuads; + long _totalQuads; /** quantity of quads that can be stored with the current texture atlas size */ - int _capacity; + long _capacity; /** Texture of the texture atlas */ Texture2D* _texture; /** Quads that are going to be rendered */ diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 780e0330aa..17aa00effb 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -441,7 +441,7 @@ void TextureCache::dumpCachedTextureInfo() const Texture2D* tex = it->second; unsigned int bpp = tex->getBitsPerPixelForFormat(); // Each texture takes up width * height * bytesPerPixel bytes. - unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; + long bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; totalBytes += bytes; count++; log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", From 20b350a58b00d29f1c91999a28aea819885da2df Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:27:58 +0800 Subject: [PATCH 190/197] Removing cocosjs_manual_conversions.h(.cpp). Put all jsval <-> native value conversion codes to js_manual_conversions.h(.cpp). --- .../project.pbxproj.REMOVED.git-id | 2 +- .../scripting/javascript/bindings/Android.mk | 1 - .../javascript/bindings/ScriptingCore.cpp | 1037 -------------- .../javascript/bindings/ScriptingCore.h | 40 +- ...s_chipmunk_auto_classes.cpp.REMOVED.git-id | 2 +- ...ings_chipmunk_functions.cpp.REMOVED.git-id | 2 +- .../chipmunk/js_bindings_chipmunk_manual.h | 1 - .../bindings/cocosjs_manual_conversions.cpp | 134 -- .../bindings/cocosjs_manual_conversions.h | 24 - .../bindings/js_manual_conversions.cpp | 1227 ++++++++++++++++- .../bindings/js_manual_conversions.h | 69 +- .../bindings/jsb_opengl_functions.cpp | 515 ++++--- .../javascript/bindings/jsb_opengl_manual.cpp | 1 - .../bindings/proj.win32/libJSBinding.vcxproj | 2 - .../proj.win32/libJSBinding.vcxproj.filters | 6 - 15 files changed, 1470 insertions(+), 1593 deletions(-) delete mode 100644 cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp delete mode 100644 cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 1ebbc707a8..5639c9df83 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -30ca6c02884f9bc20405b3e657b444c0153bead7 \ No newline at end of file +a70914e0a87ee8ced4d662bd6038fc955e77f6ca \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 8195fde121..ffb0167ce1 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -9,7 +9,6 @@ LOCAL_MODULE_FILENAME := libcocos2dxjsb LOCAL_SRC_FILES := ScriptingCore.cpp \ cocos2d_specifics.cpp \ js_manual_conversions.cpp \ - cocosjs_manual_conversions.cpp \ js_bindings_core.cpp \ js_bindings_opengl.cpp \ jsb_opengl_functions.cpp \ diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 462debba9d..86ddb4bd2e 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -1159,803 +1159,6 @@ int ScriptingCore::sendEvent(ScriptEvent* evt) return 0; } -#pragma mark - Conversion Routines -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (int32_t)dp; - - return ok; -} - -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (uint32_t)dp; - - return ok; -} - -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (uint16_t)dp; - - return ok; -} - -JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { - JSObject *tmp_arg; - JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); - JSB_PRECONDITION3( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); - - uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); - long long ret = arg_array[0]; - ret = ret << 32; - ret |= arg_array[1]; - - *r = ret; - return JS_TRUE; -} - -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { - JSString *tmp = JS_ValueToString(cx, v); - JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); - - JSStringWrapper str(tmp); - *ret = str.get(); - return JS_TRUE; -} - -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - double x, y; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->x = (float)x; - ret->y = (float)y; - return JS_TRUE; -} - -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - JS::RootedValue jsz(cx); - JS::RootedValue jstimestamp(cx); - - double x, y, timestamp, z; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_GetProperty(cx, tmp, "z", &jsz) && - JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jsz, &z) && - JS_ValueToNumber(cx, jstimestamp, ×tamp); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->x = x; - ret->y = y; - ret->z = z; - ret->timestamp = timestamp; - return JS_TRUE; -} - -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) -{ - JSBool ok = JS_TRUE; - Array* pArray = Array::create(); - for( int i=0; i < argc; i++ ) - { - double num = 0.0; - // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number - if ( JSVAL_IS_NUMBER(*vp)) { - ok &= JS_ValueToNumber(cx, *vp, &num ); - if (!ok) { - break; - } - pArray->addObject(Integer::create((int)num)); - } - else if (JSVAL_IS_STRING(*vp)) - { - JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); - pArray->addObject(String::create(str.get())); - } - else - { - js_proxy_t* p; - JSObject* obj = JSVAL_TO_OBJECT(*vp); - p = jsb_get_js_proxy(obj); - if (p) { - pArray->addObject((Object*)p->ptr); - } - } - // next - vp++; - } - *ret = pArray; - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - return ok; -} - -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - JS::RootedValue jswidth(cx); - JS::RootedValue jsheight(cx); - - double x, y, width, height; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_GetProperty(cx, tmp, "width", &jswidth) && - JS_GetProperty(cx, tmp, "height", &jsheight) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jswidth, &width) && - JS_ValueToNumber(cx, jsheight, &height); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->origin.x = x; - ret->origin.y = y; - ret->size.width = width; - ret->size.height = height; - return JS_TRUE; -} - -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { - JSObject *tmp; - JS::RootedValue jsw(cx); - JS::RootedValue jsh(cx); - double w, h; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "width", &jsw) && - JS_GetProperty(cx, tmp, "height", &jsh) && - JS_ValueToNumber(cx, jsw, &w) && - JS_ValueToNumber(cx, jsh, &h); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ret->width = w; - ret->height = h; - return JS_TRUE; -} - -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsa(cx); - - double r, g, b, a; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "r", &jsr) && - JS_GetProperty(cx, tmp, "g", &jsg) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->r = r; - ret->g = g; - ret->b = b; - ret->a = a; - return JS_TRUE; -} - -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsa(cx); - double r, g, b, a; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "r", &jsr) && - JS_GetProperty(cx, tmp, "g", &jsg) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ret->r = r; - ret->g = g; - ret->b = b; - ret->a = a; - return JS_TRUE; -} - -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - double r, g, b; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "r", &jsr) && - JS_GetProperty(cx, tmp, "g", &jsg) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->r = r; - ret->g = g; - ret->b = b; - return JS_TRUE; -} - -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { - // Parsing sequence - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); - - uint32_t len; - JS_GetArrayLength(cx, jsobj, &len); - - Point *array = (Point*)malloc( sizeof(Point) * len); - - for( uint32_t i=0; i< len;i++ ) { - jsval valarg; - JS_GetElement(cx, jsobj, i, &valarg); - - ok = jsval_to_ccpoint(cx, valarg, &array[i]); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - } - - *numPoints = len; - *points = array; - - return JS_TRUE; -} - - -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); - - uint32_t len = 0; - JS_GetArrayLength(cx, jsobj, &len); - Array* arr = Array::createWithCapacity(len); - for (uint32_t i=0; i < len; i++) { - jsval value; - if (JS_GetElement(cx, jsobj, i, &value)) { - if (value.isObject()) - { - js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); - proxy = jsb_get_js_proxy(tmp); - cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - // Don't test it. - //TEST_NATIVE_OBJECT(cx, cobj) - if (cobj) { - // It's a native js object. - arr->addObject(cobj); - } - else if (!JS_IsArrayObject(cx, tmp)){ - // It's a normal js object. - Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); - if (ok) { - arr->addObject(dictVal); - } - } - else { - // It's a js array object. - Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); - if (ok) { - arr->addObject(arrVal); - } - } - } - else if (JSVAL_IS_STRING(value)) { - JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); - arr->addObject(String::create(valueWapper.get())); -// CCLOG("iterate array: value = %s", valueWapper.get().c_str()); - } - else if (JSVAL_IS_NUMBER(value)) { - double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); - if (ok) { - arr->addObject(Double::create(number)); -// CCLOG("iterate array: value = %lf", number); - } - } - else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); - if (ok) { - arr->addObject(Bool::create(boolVal)); -// CCLOG("iterate object: value = %d", boolVal); - } - } - else { - CCASSERT(false, "not supported type"); - } - } - } - *ret = arr; - return JS_TRUE; -} - - -jsval ccarray_to_jsval(JSContext* cx, Array *arr) -{ - JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); - - Object* obj; - int i = 0; - CCARRAY_FOREACH(arr, obj) - { - jsval arrElement; - - //First, check whether object is associated with js object. - js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); - if (jsproxy) { - arrElement = OBJECT_TO_JSVAL(jsproxy->obj); - } - else { - String* strVal = NULL; - Dictionary* dictVal = NULL; - Array* arrVal = NULL; - Double* doubleVal = NULL; - Bool* boolVal = NULL; - Float* floatVal = NULL; - Integer* intVal = NULL; - - if ((strVal = dynamic_cast(obj))) { - arrElement = c_string_to_jsval(cx, strVal->getCString()); - } else if ((dictVal = dynamic_cast(obj))) { - arrElement = ccdictionary_to_jsval(cx, dictVal); - } else if ((arrVal = dynamic_cast(obj))) { - arrElement = ccarray_to_jsval(cx, arrVal); - } else if ((doubleVal = dynamic_cast(obj))) { - arrElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); - } else if ((floatVal = dynamic_cast(obj))) { - arrElement = DOUBLE_TO_JSVAL(floatVal->getValue()); - } else if ((intVal = dynamic_cast(obj))) { - arrElement = INT_TO_JSVAL(intVal->getValue()); - } else if ((boolVal = dynamic_cast(obj))) { - arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); - } else { - CCASSERT(false, "the type isn't suppored."); - } - } - if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { - break; - } - ++i; - } - return OBJECT_TO_JSVAL(jsretArr); -} - -jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) -{ - JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); - DictElement* pElement = NULL; - CCDICT_FOREACH(dict, pElement) - { - JS::RootedValue dictElement(cx); - Object* obj = pElement->getObject(); - //First, check whether object is associated with js object. - js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); - if (jsproxy) { - dictElement = OBJECT_TO_JSVAL(jsproxy->obj); - } - else { - String* strVal = NULL; - Dictionary* dictVal = NULL; - Array* arrVal = NULL; - Double* doubleVal = NULL; - Bool* boolVal = NULL; - Float* floatVal = NULL; - Integer* intVal = NULL; - - if ((strVal = dynamic_cast(obj))) { - dictElement = c_string_to_jsval(cx, strVal->getCString()); - } else if ((dictVal = dynamic_cast(obj))) { - dictElement = ccdictionary_to_jsval(cx, dictVal); - } else if ((arrVal = dynamic_cast(obj))) { - dictElement = ccarray_to_jsval(cx, arrVal); - } else if ((doubleVal = dynamic_cast(obj))) { - dictElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); - } else if ((floatVal = dynamic_cast(obj))) { - dictElement = DOUBLE_TO_JSVAL(floatVal->getValue()); - } else if ((intVal = dynamic_cast(obj))) { - dictElement = INT_TO_JSVAL(intVal->getValue()); - } else if ((boolVal = dynamic_cast(obj))) { - dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); - } else { - CCASSERT(false, "the type isn't suppored."); - } - } - const char* key = pElement->getStrKey(); - if (key && strlen(key) > 0) - { - JS_SetProperty(cx, jsRet, key, dictElement); - } - } - return OBJECT_TO_JSVAL(jsRet); -} - -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { - - if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) - { - *ret = NULL; - return JS_TRUE; - } - - JSObject* tmp = JSVAL_TO_OBJECT(v); - if (!tmp) { - LOGD("jsval_to_ccdictionary: the jsval is not an object."); - return JS_FALSE; - } - - JSObject* it = JS_NewPropertyIterator(cx, tmp); - Dictionary* dict = NULL; - - while (true) - { - jsid idp; - jsval key; - if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { - return JS_FALSE; // error - } - - if (key == JSVAL_VOID) { - break; // end of iteration - } - - if (!JSVAL_IS_STRING(key)) { - continue; // ignore integer properties - } - - JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); - if (!dict) { - dict = Dictionary::create(); - } - - JS::RootedValue value(cx); - JS_GetPropertyById(cx, tmp, idp, &value); - if (value.isObject()) - { - js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); - proxy = jsb_get_js_proxy(tmp); - cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - // Don't test it. - //TEST_NATIVE_OBJECT(cx, cobj) - if (cobj) { - // It's a native <-> js glue object. - dict->setObject(cobj, keyWrapper.get()); - } - else if (!JS_IsArrayObject(cx, tmp)){ - // It's a normal js object. - Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); - if (ok) { - dict->setObject(dictVal, keyWrapper.get()); - } - } - else { - // It's a js array object. - Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); - if (ok) { - dict->setObject(arrVal, keyWrapper.get()); - } - } - } - else if (JSVAL_IS_STRING(value)) { - JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); - dict->setObject(String::create(valueWapper.get()), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); - } - else if (JSVAL_IS_NUMBER(value)) { - double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); - if (ok) { - dict->setObject(Double::create(number), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); - } - } - else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); - if (ok) { - dict->setObject(Bool::create(boolVal), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); - } - } - else { - CCASSERT(false, "not supported type"); - } - } - - *ret = dict; - return JS_TRUE; -} - -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) -{ - JSObject *tmp; - JS::RootedValue jsa(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsc(cx); - JS::RootedValue jsd(cx); - JS::RootedValue jstx(cx); - JS::RootedValue jsty(cx); - double a, b, c, d, tx, ty; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "c", &jsc) && - JS_GetProperty(cx, tmp, "d", &jsd) && - JS_GetProperty(cx, tmp, "tx", &jstx) && - JS_GetProperty(cx, tmp, "ty", &jsty) && - JS_ValueToNumber(cx, jsa, &a) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsc, &c) && - JS_ValueToNumber(cx, jsd, &d) && - JS_ValueToNumber(cx, jstx, &tx) && - JS_ValueToNumber(cx, jsty, &ty); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *ret = AffineTransformMake(a, b, c, d, tx, ty); - return JS_TRUE; -} - -// From native type to jsval -jsval int32_to_jsval( JSContext *cx, int32_t number ) -{ - return INT_TO_JSVAL(number); -} - -jsval uint32_to_jsval( JSContext *cx, uint32_t number ) -{ - return UINT_TO_JSVAL(number); -} - -jsval long_long_to_jsval(JSContext* cx, long long v) { - JSObject *tmp = JS_NewUint32Array(cx, 2); - uint32_t *data = (uint32_t *)JS_GetArrayBufferViewData(tmp); - data[0] = ((uint32_t *)(&v))[0]; - data[1] = ((uint32_t *)(&v))[1]; - return OBJECT_TO_JSVAL(tmp); -} - -jsval std_string_to_jsval(JSContext* cx, const std::string& v) -{ - return c_string_to_jsval(cx, v.c_str(), v.size()); -} - -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) -{ - if (v == NULL) - { - return JSVAL_NULL; - } - - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - - if (0 == length) - { - auto emptyStr = JS_NewStringCopyZ(cx, ""); - return STRING_TO_JSVAL(emptyStr); - } - - jsval ret = JSVAL_NULL; - int utf16_size = 0; - jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); - - if (strUTF16 && utf16_size > 0) { - JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); - if (str) { - ret = STRING_TO_JSVAL(str); - } - delete[] strUTF16; - } - return ret; -} - -jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccsize_to_jsval(JSContext* cx, const Size& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) -{ - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "tx", DOUBLE_TO_JSVAL(t.tx), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "ty", DOUBLE_TO_JSVAL(t.ty), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) -{ - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_TRUE; - - ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontSize", int32_to_jsval(cx, t._fontSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontAlignmentH", int32_to_jsval(cx, (int32_t)t._alignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontAlignmentV", int32_to_jsval(cx, (int32_t)t._vertAlignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontFillColor", cccolor3b_to_jsval(cx, t._fontFillColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontDimensions", ccsize_to_jsval(cx, t._dimensions), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - // Shadow - ok &= JS_DefineProperty(cx, tmp, "shadowEnabled", BOOLEAN_TO_JSVAL(t._shadow._shadowEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowOffset", ccsize_to_jsval(cx, t._shadow._shadowOffset), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowBlur", DOUBLE_TO_JSVAL(t._shadow._shadowBlur), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowOpacity", DOUBLE_TO_JSVAL(t._shadow._shadowOpacity), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - // Stroke - ok &= JS_DefineProperty(cx, tmp, "strokeEnabled", BOOLEAN_TO_JSVAL(t._stroke._strokeEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "strokeColor", cccolor3b_to_jsval(cx, t._stroke._strokeColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "strokeSize", DOUBLE_TO_JSVAL(t._stroke._strokeSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - #pragma mark - Debug void SimpleRunLoop::update(float dt) @@ -2297,246 +1500,6 @@ void jsb_remove_proxy(js_proxy_t* nativeProxy, js_proxy_t* jsProxy) JS_REMOVE_PROXY(nativeProxy, jsProxy); } -static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) -{ - JS::RootedValue jsr(cx); - Color3B out; - JS_GetProperty(cx, colorObject, "r", &jsr); - double fontR = 0.0; - JS_ValueToNumber(cx, jsr, &fontR); - - JS_GetProperty(cx, colorObject, "g", &jsr); - double fontG = 0.0; - JS_ValueToNumber(cx, jsr, &fontG); - - JS_GetProperty(cx, colorObject, "b", &jsr); - double fontB = 0.0; - JS_ValueToNumber(cx, jsr, &fontB); - - // the out - out.r = (unsigned char)fontR; - out.g = (unsigned char)fontG; - out.b = (unsigned char)fontB; - - return out; -} - -Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) -{ - JS::RootedValue jsr(cx); - Size out; - JS_GetProperty(cx, sizeObject, "width", &jsr); - double width = 0.0; - JS_ValueToNumber(cx, jsr, &width); - - JS_GetProperty(cx, sizeObject, "height", &jsr); - double height = 0.0; - JS_ValueToNumber(cx, jsr, &height); - - - // the out - out.width = width; - out.height = height; - - return out; -} - -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) -{ - JSObject *jsobj; - - if (!JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - // defaul values - const char * defautlFontName = "Arial"; - const int defaultFontSize = 32; - TextHAlignment defaultTextAlignment = TextHAlignment::LEFT; - TextVAlignment defaultTextVAlignment = TextVAlignment::TOP; - - // by default shadow and stroke are off - out->_shadow._shadowEnabled = false; - out->_stroke._strokeEnabled = false; - - // white text by default - out->_fontFillColor = Color3B::WHITE; - - // font name - JS::RootedValue jsr(cx); - JS_GetProperty(cx, jsobj, "fontName", &jsr); - JS_ValueToString(cx, jsr); - JSStringWrapper wrapper(jsr); - const char* fontName = wrapper.get(); - - if (fontName && strlen(fontName) > 0) - { - out->_fontName = fontName; - } - else - { - out->_fontName = defautlFontName; - } - - // font size - JSBool hasProperty; - JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontSize", &jsr); - double fontSize = 0.0; - JS_ValueToNumber(cx, jsr, &fontSize); - out->_fontSize = fontSize; - } - else - { - out->_fontSize = defaultFontSize; - } - - // font alignment horizontal - JS_HasProperty(cx, jsobj, "fontAlignmentH", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); - double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); - out->_alignment = (TextHAlignment)(int)fontAlign; - } - else - { - out->_alignment = defaultTextAlignment; - } - - // font alignment vertical - JS_HasProperty(cx, jsobj, "fontAlignmentV", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); - double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); - out->_vertAlignment = (TextVAlignment)(int)fontAlign; - } - else - { - out->_vertAlignment = defaultTextVAlignment; - } - - // font fill color - JS_HasProperty(cx, jsobj, "fontFillColor", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); - - JSObject *jsobjColor; - if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) - return JS_FALSE; - - out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); - } - - // font rendering box dimensions - JS_HasProperty(cx, jsobj, "fontDimensions", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); - - JSObject *jsobjSize; - if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) - return JS_FALSE; - - out->_dimensions = getSizeFromJSObject(cx, jsobjSize); - } - - // shadow - JS_HasProperty(cx, jsobj, "shadowEnabled", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); - out->_shadow._shadowEnabled = ToBoolean(jsr); - - if ( out->_shadow._shadowEnabled ) - { - // default shadow values - out->_shadow._shadowOffset = Size(5, 5); - out->_shadow._shadowBlur = 1; - out->_shadow._shadowOpacity = 1; - - // shado offset - JS_HasProperty(cx, jsobj, "shadowOffset", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); - - JSObject *jsobjShadowOffset; - if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) - return JS_FALSE; - out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); - } - - // shadow blur - JS_HasProperty(cx, jsobj, "shadowBlur", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); - double shadowBlur = 0.0; - JS_ValueToNumber(cx, jsr, &shadowBlur); - out->_shadow._shadowBlur = shadowBlur; - } - - // shadow intensity - JS_HasProperty(cx, jsobj, "shadowOpacity", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); - double shadowOpacity = 0.0; - JS_ValueToNumber(cx, jsr, &shadowOpacity); - out->_shadow._shadowOpacity = shadowOpacity; - } - } - } - - // stroke - JS_HasProperty(cx, jsobj, "strokeEnabled", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); - out->_stroke._strokeEnabled = ToBoolean(jsr); - - if ( out->_stroke._strokeEnabled ) - { - // default stroke values - out->_stroke._strokeSize = 1; - out->_stroke._strokeColor = Color3B::BLUE; - - // stroke color - JS_HasProperty(cx, jsobj, "strokeColor", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeColor", &jsr); - - JSObject *jsobjStrokeColor; - if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) - return JS_FALSE; - out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); - } - - // stroke size - JS_HasProperty(cx, jsobj, "strokeSize", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeSize", &jsr); - double strokeSize = 0.0; - JS_ValueToNumber(cx, jsr, &strokeSize); - out->_stroke._strokeSize = strokeSize; - } - } - } - - // we are done here - return JS_TRUE; -} - // JSStringWrapper JSStringWrapper::JSStringWrapper() : _buffer(nullptr) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 7f0e367d92..b0c6c45acb 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -17,6 +17,7 @@ #include "jsapi.h" #include "jsfriendapi.h" #include "spidermonkey_specifics.h" +#include "js_manual_conversions.h" void js_log(const char *format, ...); @@ -204,45 +205,6 @@ public: int handleKeypadEvent(void* data); }; -// some utility functions -// to native -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); -JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret); -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret); -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret); -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret); -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret); -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret); -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints); -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret); -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret); -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret); -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret); -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret); -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition* ret ); - -// from native -jsval int32_to_jsval( JSContext *cx, int32_t l); -jsval uint32_to_jsval( JSContext *cx, uint32_t number ); -jsval long_long_to_jsval(JSContext* cx, long long v); -jsval std_string_to_jsval(JSContext* cx, const std::string& v); -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); -jsval ccpoint_to_jsval(JSContext* cx, const Point& v); -jsval ccrect_to_jsval(JSContext* cx, const Rect& v); -jsval ccsize_to_jsval(JSContext* cx, const Size& v); -jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v); -jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v); -jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v); -jsval ccdictionary_to_jsval(JSContext* cx, Dictionary *dict); -jsval ccarray_to_jsval(JSContext* cx, Array *arr); -jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v); -jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t); -jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t); - JSObject* NewGlobalObject(JSContext* cx, bool debug = false); // just a simple utility to avoid mem leaking when using JSString diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id index c8c345c32c..0e67c34489 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id @@ -1 +1 @@ -6558be4f421be9227dc4fabf1b682d479825bd18 \ No newline at end of file +2a8f07a22574900290f772ad5a580ef9fc57a9b8 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id index 5cf2a4495d..264696d780 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id @@ -1 +1 @@ -1c5eb9cd58c82de77374cdfa5c9ff647cc8b2f02 \ No newline at end of file +ac3eca550f3b923d03d042ed63edf3b66cc183b7 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h index c6b40ca757..6807bd63e1 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h @@ -27,7 +27,6 @@ #define __js_bindings_chipmunk_manual #include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" #include "js_manual_conversions.h" #include "ScriptingCore.h" #ifdef JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp deleted file mode 100644 index 56bd017069..0000000000 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include "jsapi.h" -#include "jsfriendapi.h" -#include "ScriptingCore.h" -#include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" - -#define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - -using namespace cocos2d; - -JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) -{ -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - JS::RootedValue valx(cx); - JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "x", &valx); - ok &= JS_GetProperty(cx, jsobj, "y", &valy); - - if( ! ok ) - return JS_FALSE; - - double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); - - if( ! ok ) - return JS_FALSE; - - ret->x = x; - ret->y = y; - - return JS_TRUE; - -#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *tmp_arg; - if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; - - JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); - - JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); - - *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); - - return JS_TRUE; -#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} - - -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) -{ -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - JS::RootedValue valx(cx); - JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "x", &valx); - ok &= JS_GetProperty(cx, jsobj, "y", &valy); - - if( ! ok ) - return JS_FALSE; - - double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); - - if( ! ok ) - return JS_FALSE; - - ret->x = x; - ret->y = y; - - return JS_TRUE; - -#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *tmp_arg; - if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; - - JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); - - JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); - - *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); - - return JS_TRUE; -#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} - - -jsval CGPoint_to_jsval( JSContext *cx, cpVect p) -{ - -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); - if (!object) - return JSVAL_VOID; - - if (!JS_DefineProperty(cx, object, "x", DOUBLE_TO_JSVAL(p.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || - !JS_DefineProperty(cx, object, "y", DOUBLE_TO_JSVAL(p.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) - return JSVAL_VOID; - - return OBJECT_TO_JSVAL(object); - -#else // JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - -#ifdef __LP64__ - JSObject *typedArray = JS_NewFloat64Array( cx, 2 ); -#else - JSObject *typedArray = JS_NewFloat32Array( cx, 2 ); -#endif - - cpVect *buffer = (cpVect*)JS_GetArrayBufferViewData(typedArray, cx ); - *buffer = p; - return OBJECT_TO_JSVAL(typedArray); -#endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h deleted file mode 100644 index 339ac7da9c..0000000000 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef __COCOSJS_MANUAL_CONVERSIONS_H__ -#define __COCOSJS_MANUAL_CONVERSIONS_H__ - -#include "chipmunk.h" -#include "cocos2d.h" -#include "js_manual_conversions.h" - -//#ifdef __cplusplus -//extern "C" { -//#endif - -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *out ); -jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); - - -//#ifdef __cplusplus -//} -//#endif - -#define cpVect_to_jsval CGPoint_to_jsval -#define jsval_to_cpVect jsval_to_CGPoint - -#endif /* __COCOSJS_MANUAL_CONVERSIONS_H__ */ - diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp index 521d1be2aa..0e3e20b617 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp @@ -8,6 +8,53 @@ #include "ScriptingCore.h" #include "js_bindings_config.h" #include "js_manual_conversions.h" +#include "cocos2d_specifics.hpp" + +USING_NS_CC; + +static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) +{ + JS::RootedValue jsr(cx); + Color3B out; + JS_GetProperty(cx, colorObject, "r", &jsr); + double fontR = 0.0; + JS_ValueToNumber(cx, jsr, &fontR); + + JS_GetProperty(cx, colorObject, "g", &jsr); + double fontG = 0.0; + JS_ValueToNumber(cx, jsr, &fontG); + + JS_GetProperty(cx, colorObject, "b", &jsr); + double fontB = 0.0; + JS_ValueToNumber(cx, jsr, &fontB); + + // the out + out.r = (unsigned char)fontR; + out.g = (unsigned char)fontG; + out.b = (unsigned char)fontB; + + return out; +} + +static Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) +{ + JS::RootedValue jsr(cx); + Size out; + JS_GetProperty(cx, sizeObject, "width", &jsr); + double width = 0.0; + JS_ValueToNumber(cx, jsr, &width); + + JS_GetProperty(cx, sizeObject, "height", &jsr); + double height = 0.0; + JS_ValueToNumber(cx, jsr, &height); + + + // the out + out.width = width; + out.height = height; + + return out; +} JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **r) { @@ -74,24 +121,6 @@ JSBool jsval_to_long( JSContext *cx, jsval vp, long *r ) return JS_TRUE; } -JSBool jsval_to_longlong( JSContext *cx, jsval vp, long long *r ) -{ - JSObject *tmp_arg; - JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION2( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); - JSB_PRECONDITION2( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); - - uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); - long long ret = arg_array[0]; - ret = ret << 32; - ret |= arg_array[1]; - - *r = ret; - return JS_TRUE; -} - - jsval opaque_to_jsval( JSContext *cx, void *opaque ) { #ifdef __LP64__ @@ -147,53 +176,6 @@ JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *ret ) return jsval_to_int32(cx, vp, (int32_t*)ret); } - -JSBool JSB_jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (int32_t)dp; - } - return ret; -} - -JSBool JSB_jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (uint32_t)dp; - } - return ret; -} - -JSBool JSB_jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (uint16_t)dp; - } - return ret; -} - -jsval int_to_jsval( JSContext *cx, int number ) -{ - return INT_TO_JSVAL(number); -} - -jsval uint_to_jsval( JSContext *cx, unsigned int number ) -{ - return UINT_TO_JSVAL(number); -} - jsval long_to_jsval( JSContext *cx, long number ) { #ifdef __LP64__ @@ -249,12 +231,9 @@ JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **ret ) jsval charptr_to_jsval( JSContext *cx, const char *str) { - JSString *ret_obj = JS_NewStringCopyZ(cx, str); - return STRING_TO_JSVAL(ret_obj); + return c_string_to_jsval(cx, str); } - - JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t) { JSObject *jsobj; @@ -345,4 +324,1114 @@ JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, } +#pragma mark - Conversion Routines +JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (int32_t)dp; + + return ok; +} +JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (uint32_t)dp; + + return ok; +} + +JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (uint16_t)dp; + + return ok; +} + +JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { + JSObject *tmp_arg; + JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); + JSB_PRECONDITION3( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); + + uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); + long long ret = arg_array[0]; + ret = ret << 32; + ret |= arg_array[1]; + + *r = ret; + return JS_TRUE; +} + +JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { + JSString *tmp = JS_ValueToString(cx, v); + JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); + + JSStringWrapper str(tmp); + *ret = str.get(); + return JS_TRUE; +} + +JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + double x, y; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->x = (float)x; + ret->y = (float)y; + return JS_TRUE; +} + +JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jsz(cx); + JS::RootedValue jstimestamp(cx); + + double x, y, timestamp, z; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_GetProperty(cx, tmp, "z", &jsz) && + JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y) && + JS_ValueToNumber(cx, jsz, &z) && + JS_ValueToNumber(cx, jstimestamp, ×tamp); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->x = x; + ret->y = y; + ret->z = z; + ret->timestamp = timestamp; + return JS_TRUE; +} + +JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) +{ + JSBool ok = JS_TRUE; + Array* pArray = Array::create(); + for( int i=0; i < argc; i++ ) + { + double num = 0.0; + // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number + if ( JSVAL_IS_NUMBER(*vp)) { + ok &= JS_ValueToNumber(cx, *vp, &num ); + if (!ok) { + break; + } + pArray->addObject(Integer::create((int)num)); + } + else if (JSVAL_IS_STRING(*vp)) + { + JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); + pArray->addObject(String::create(str.get())); + } + else + { + js_proxy_t* p; + JSObject* obj = JSVAL_TO_OBJECT(*vp); + p = jsb_get_js_proxy(obj); + if (p) { + pArray->addObject((Object*)p->ptr); + } + } + // next + vp++; + } + *ret = pArray; + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + return ok; +} + +JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jswidth(cx); + JS::RootedValue jsheight(cx); + + double x, y, width, height; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_GetProperty(cx, tmp, "width", &jswidth) && + JS_GetProperty(cx, tmp, "height", &jsheight) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y) && + JS_ValueToNumber(cx, jswidth, &width) && + JS_ValueToNumber(cx, jsheight, &height); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->origin.x = x; + ret->origin.y = y; + ret->size.width = width; + ret->size.height = height; + return JS_TRUE; +} + +JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { + JSObject *tmp; + JS::RootedValue jsw(cx); + JS::RootedValue jsh(cx); + double w, h; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "width", &jsw) && + JS_GetProperty(cx, tmp, "height", &jsh) && + JS_ValueToNumber(cx, jsw, &w) && + JS_ValueToNumber(cx, jsh, &h); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ret->width = w; + ret->height = h; + return JS_TRUE; +} + +JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + + double r, g, b, a; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "r", &jsr) && + JS_GetProperty(cx, tmp, "g", &jsg) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsa, &a); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->r = r; + ret->g = g; + ret->b = b; + ret->a = a; + return JS_TRUE; +} + +JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + double r, g, b, a; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "r", &jsr) && + JS_GetProperty(cx, tmp, "g", &jsg) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsa, &a); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ret->r = r; + ret->g = g; + ret->b = b; + ret->a = a; + return JS_TRUE; +} + +JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + double r, g, b; + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "r", &jsr) && + JS_GetProperty(cx, tmp, "g", &jsg) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->r = r; + ret->g = g; + ret->b = b; + return JS_TRUE; +} + +JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { + // Parsing sequence + JSObject *jsobj; + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + + uint32_t len; + JS_GetArrayLength(cx, jsobj, &len); + + Point *array = (Point*)malloc( sizeof(Point) * len); + + for( uint32_t i=0; i< len;i++ ) { + jsval valarg; + JS_GetElement(cx, jsobj, i, &valarg); + + ok = jsval_to_ccpoint(cx, valarg, &array[i]); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + } + + *numPoints = len; + *points = array; + + return JS_TRUE; +} + + +JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { + JSObject *jsobj; + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + + uint32_t len = 0; + JS_GetArrayLength(cx, jsobj, &len); + Array* arr = Array::createWithCapacity(len); + for (uint32_t i=0; i < len; i++) { + jsval value; + if (JS_GetElement(cx, jsobj, i, &value)) { + if (value.isObject()) + { + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + // Don't test it. + //TEST_NATIVE_OBJECT(cx, cobj) + if (cobj) { + // It's a native js object. + arr->addObject(cobj); + } + else if (!JS_IsArrayObject(cx, tmp)){ + // It's a normal js object. + Dictionary* dictVal = NULL; + JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + if (ok) { + arr->addObject(dictVal); + } + } + else { + // It's a js array object. + Array* arrVal = NULL; + JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + if (ok) { + arr->addObject(arrVal); + } + } + } + else if (JSVAL_IS_STRING(value)) { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + arr->addObject(String::create(valueWapper.get())); + // CCLOG("iterate array: value = %s", valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + arr->addObject(Double::create(number)); + // CCLOG("iterate array: value = %lf", number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + arr->addObject(Bool::create(boolVal)); + // CCLOG("iterate object: value = %d", boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + } + *ret = arr; + return JS_TRUE; +} + + +jsval ccarray_to_jsval(JSContext* cx, Array *arr) +{ + JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); + + Object* obj; + int i = 0; + CCARRAY_FOREACH(arr, obj) + { + jsval arrElement; + + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + arrElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + else { + String* strVal = NULL; + Dictionary* dictVal = NULL; + Array* arrVal = NULL; + Double* doubleVal = NULL; + Bool* boolVal = NULL; + Float* floatVal = NULL; + Integer* intVal = NULL; + + if ((strVal = dynamic_cast(obj))) { + arrElement = c_string_to_jsval(cx, strVal->getCString()); + } else if ((dictVal = dynamic_cast(obj))) { + arrElement = ccdictionary_to_jsval(cx, dictVal); + } else if ((arrVal = dynamic_cast(obj))) { + arrElement = ccarray_to_jsval(cx, arrVal); + } else if ((doubleVal = dynamic_cast(obj))) { + arrElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); + } else if ((floatVal = dynamic_cast(obj))) { + arrElement = DOUBLE_TO_JSVAL(floatVal->getValue()); + } else if ((intVal = dynamic_cast(obj))) { + arrElement = INT_TO_JSVAL(intVal->getValue()); + } else if ((boolVal = dynamic_cast(obj))) { + arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + } else { + CCASSERT(false, "the type isn't suppored."); + } + } + if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { + break; + } + ++i; + } + return OBJECT_TO_JSVAL(jsretArr); +} + +jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) +{ + JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); + DictElement* pElement = NULL; + CCDICT_FOREACH(dict, pElement) + { + JS::RootedValue dictElement(cx); + Object* obj = pElement->getObject(); + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + dictElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + else { + String* strVal = NULL; + Dictionary* dictVal = NULL; + Array* arrVal = NULL; + Double* doubleVal = NULL; + Bool* boolVal = NULL; + Float* floatVal = NULL; + Integer* intVal = NULL; + + if ((strVal = dynamic_cast(obj))) { + dictElement = c_string_to_jsval(cx, strVal->getCString()); + } else if ((dictVal = dynamic_cast(obj))) { + dictElement = ccdictionary_to_jsval(cx, dictVal); + } else if ((arrVal = dynamic_cast(obj))) { + dictElement = ccarray_to_jsval(cx, arrVal); + } else if ((doubleVal = dynamic_cast(obj))) { + dictElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); + } else if ((floatVal = dynamic_cast(obj))) { + dictElement = DOUBLE_TO_JSVAL(floatVal->getValue()); + } else if ((intVal = dynamic_cast(obj))) { + dictElement = INT_TO_JSVAL(intVal->getValue()); + } else if ((boolVal = dynamic_cast(obj))) { + dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + } else { + CCASSERT(false, "the type isn't suppored."); + } + } + const char* key = pElement->getStrKey(); + if (key && strlen(key) > 0) + { + JS_SetProperty(cx, jsRet, key, dictElement); + } + } + return OBJECT_TO_JSVAL(jsRet); +} + +JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) +{ + if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) + { + *ret = NULL; + return JS_TRUE; + } + + JSObject* tmp = JSVAL_TO_OBJECT(v); + if (!tmp) { + CCLOG("%s", "jsval_to_ccdictionary: the jsval is not an object."); + return JS_FALSE; + } + + JSObject* it = JS_NewPropertyIterator(cx, tmp); + Dictionary* dict = NULL; + + while (true) + { + jsid idp; + jsval key; + if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { + return JS_FALSE; // error + } + + if (key == JSVAL_VOID) { + break; // end of iteration + } + + if (!JSVAL_IS_STRING(key)) { + continue; // ignore integer properties + } + + JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); + if (!dict) { + dict = Dictionary::create(); + } + + JS::RootedValue value(cx); + JS_GetPropertyById(cx, tmp, idp, &value); + if (value.isObject()) + { + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + // Don't test it. + //TEST_NATIVE_OBJECT(cx, cobj) + if (cobj) { + // It's a native <-> js glue object. + dict->setObject(cobj, keyWrapper.get()); + } + else if (!JS_IsArrayObject(cx, tmp)){ + // It's a normal js object. + Dictionary* dictVal = NULL; + JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + if (ok) { + dict->setObject(dictVal, keyWrapper.get()); + } + } + else { + // It's a js array object. + Array* arrVal = NULL; + JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + if (ok) { + dict->setObject(arrVal, keyWrapper.get()); + } + } + } + else if (JSVAL_IS_STRING(value)) { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + dict->setObject(String::create(valueWapper.get()), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + dict->setObject(Double::create(number), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + dict->setObject(Bool::create(boolVal), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + + *ret = dict; + return JS_TRUE; +} + +JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) +{ + JSObject *tmp; + JS::RootedValue jsa(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsc(cx); + JS::RootedValue jsd(cx); + JS::RootedValue jstx(cx); + JS::RootedValue jsty(cx); + double a, b, c, d, tx, ty; + JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "c", &jsc) && + JS_GetProperty(cx, tmp, "d", &jsd) && + JS_GetProperty(cx, tmp, "tx", &jstx) && + JS_GetProperty(cx, tmp, "ty", &jsty) && + JS_ValueToNumber(cx, jsa, &a) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsc, &c) && + JS_ValueToNumber(cx, jsd, &d) && + JS_ValueToNumber(cx, jstx, &tx) && + JS_ValueToNumber(cx, jsty, &ty); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *ret = AffineTransformMake(a, b, c, d, tx, ty); + return JS_TRUE; +} + +// From native type to jsval +jsval int32_to_jsval( JSContext *cx, int32_t number ) +{ + return INT_TO_JSVAL(number); +} + +jsval uint32_to_jsval( JSContext *cx, uint32_t number ) +{ + return UINT_TO_JSVAL(number); +} + +jsval std_string_to_jsval(JSContext* cx, const std::string& v) +{ + return c_string_to_jsval(cx, v.c_str(), v.size()); +} + +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) +{ + if (v == NULL) + { + return JSVAL_NULL; + } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + + if (0 == length) + { + auto emptyStr = JS_NewStringCopyZ(cx, ""); + return STRING_TO_JSVAL(emptyStr); + } + + jsval ret = JSVAL_NULL; + int utf16_size = 0; + jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); + + if (strUTF16 && utf16_size > 0) { + JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); + if (str) { + ret = STRING_TO_JSVAL(str); + } + delete[] strUTF16; + } + return ret; +} + +jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccsize_to_jsval(JSContext* cx, const Size& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) +{ + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "tx", DOUBLE_TO_JSVAL(t.tx), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "ty", DOUBLE_TO_JSVAL(t.ty), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) +{ + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_TRUE; + + ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontSize", int32_to_jsval(cx, t._fontSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontAlignmentH", int32_to_jsval(cx, (int32_t)t._alignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontAlignmentV", int32_to_jsval(cx, (int32_t)t._vertAlignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontFillColor", cccolor3b_to_jsval(cx, t._fontFillColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontDimensions", ccsize_to_jsval(cx, t._dimensions), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + // Shadow + ok &= JS_DefineProperty(cx, tmp, "shadowEnabled", BOOLEAN_TO_JSVAL(t._shadow._shadowEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowOffset", ccsize_to_jsval(cx, t._shadow._shadowOffset), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowBlur", DOUBLE_TO_JSVAL(t._shadow._shadowBlur), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowOpacity", DOUBLE_TO_JSVAL(t._shadow._shadowOpacity), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + // Stroke + ok &= JS_DefineProperty(cx, tmp, "strokeEnabled", BOOLEAN_TO_JSVAL(t._stroke._strokeEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "strokeColor", cccolor3b_to_jsval(cx, t._stroke._strokeColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "strokeSize", DOUBLE_TO_JSVAL(t._stroke._strokeSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) +{ + JSObject *jsobj; + + if (!JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + // defaul values + const char * defautlFontName = "Arial"; + const int defaultFontSize = 32; + TextHAlignment defaultTextAlignment = TextHAlignment::LEFT; + TextVAlignment defaultTextVAlignment = TextVAlignment::TOP; + + // by default shadow and stroke are off + out->_shadow._shadowEnabled = false; + out->_stroke._strokeEnabled = false; + + // white text by default + out->_fontFillColor = Color3B::WHITE; + + // font name + JS::RootedValue jsr(cx); + JS_GetProperty(cx, jsobj, "fontName", &jsr); + JS_ValueToString(cx, jsr); + JSStringWrapper wrapper(jsr); + const char* fontName = wrapper.get(); + + if (fontName && strlen(fontName) > 0) + { + out->_fontName = fontName; + } + else + { + out->_fontName = defautlFontName; + } + + // font size + JSBool hasProperty; + JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontSize", &jsr); + double fontSize = 0.0; + JS_ValueToNumber(cx, jsr, &fontSize); + out->_fontSize = fontSize; + } + else + { + out->_fontSize = defaultFontSize; + } + + // font alignment horizontal + JS_HasProperty(cx, jsobj, "fontAlignmentH", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); + double fontAlign = 0.0; + JS_ValueToNumber(cx, jsr, &fontAlign); + out->_alignment = (TextHAlignment)(int)fontAlign; + } + else + { + out->_alignment = defaultTextAlignment; + } + + // font alignment vertical + JS_HasProperty(cx, jsobj, "fontAlignmentV", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); + double fontAlign = 0.0; + JS_ValueToNumber(cx, jsr, &fontAlign); + out->_vertAlignment = (TextVAlignment)(int)fontAlign; + } + else + { + out->_vertAlignment = defaultTextVAlignment; + } + + // font fill color + JS_HasProperty(cx, jsobj, "fontFillColor", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); + + JSObject *jsobjColor; + if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) + return JS_FALSE; + + out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); + } + + // font rendering box dimensions + JS_HasProperty(cx, jsobj, "fontDimensions", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); + + JSObject *jsobjSize; + if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) + return JS_FALSE; + + out->_dimensions = getSizeFromJSObject(cx, jsobjSize); + } + + // shadow + JS_HasProperty(cx, jsobj, "shadowEnabled", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); + out->_shadow._shadowEnabled = ToBoolean(jsr); + + if ( out->_shadow._shadowEnabled ) + { + // default shadow values + out->_shadow._shadowOffset = Size(5, 5); + out->_shadow._shadowBlur = 1; + out->_shadow._shadowOpacity = 1; + + // shado offset + JS_HasProperty(cx, jsobj, "shadowOffset", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); + + JSObject *jsobjShadowOffset; + if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) + return JS_FALSE; + out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); + } + + // shadow blur + JS_HasProperty(cx, jsobj, "shadowBlur", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); + double shadowBlur = 0.0; + JS_ValueToNumber(cx, jsr, &shadowBlur); + out->_shadow._shadowBlur = shadowBlur; + } + + // shadow intensity + JS_HasProperty(cx, jsobj, "shadowOpacity", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); + double shadowOpacity = 0.0; + JS_ValueToNumber(cx, jsr, &shadowOpacity); + out->_shadow._shadowOpacity = shadowOpacity; + } + } + } + + // stroke + JS_HasProperty(cx, jsobj, "strokeEnabled", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); + out->_stroke._strokeEnabled = ToBoolean(jsr); + + if ( out->_stroke._strokeEnabled ) + { + // default stroke values + out->_stroke._strokeSize = 1; + out->_stroke._strokeColor = Color3B::BLUE; + + // stroke color + JS_HasProperty(cx, jsobj, "strokeColor", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeColor", &jsr); + + JSObject *jsobjStrokeColor; + if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) + return JS_FALSE; + out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); + } + + // stroke size + JS_HasProperty(cx, jsobj, "strokeSize", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeSize", &jsr); + double strokeSize = 0.0; + JS_ValueToNumber(cx, jsr, &strokeSize); + out->_stroke._strokeSize = strokeSize; + } + } + } + + // we are done here + return JS_TRUE; +} + +#define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + +JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) +{ +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *jsobj; + if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); + JSBool ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "x", &valx); + ok &= JS_GetProperty(cx, jsobj, "y", &valy); + + if( ! ok ) + return JS_FALSE; + + double x, y; + ok &= JS_ValueToNumber(cx, valx, &x); + ok &= JS_ValueToNumber(cx, valy, &y); + + if( ! ok ) + return JS_FALSE; + + ret->x = x; + ret->y = y; + + return JS_TRUE; + +#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *tmp_arg; + if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) + return JS_FALSE; + + JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); + + JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); + + *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); + + return JS_TRUE; +#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} + + +JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) +{ +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *jsobj; + if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); + JSBool ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "x", &valx); + ok &= JS_GetProperty(cx, jsobj, "y", &valy); + + if( ! ok ) + return JS_FALSE; + + double x, y; + ok &= JS_ValueToNumber(cx, valx, &x); + ok &= JS_ValueToNumber(cx, valy, &y); + + if( ! ok ) + return JS_FALSE; + + ret->x = x; + ret->y = y; + + return JS_TRUE; + +#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *tmp_arg; + if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) + return JS_FALSE; + + JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); + + JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); + + *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); + + return JS_TRUE; +#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} + + +jsval CGPoint_to_jsval( JSContext *cx, cpVect p) +{ + +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); + if (!object) + return JSVAL_VOID; + + if (!JS_DefineProperty(cx, object, "x", DOUBLE_TO_JSVAL(p.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || + !JS_DefineProperty(cx, object, "y", DOUBLE_TO_JSVAL(p.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) + return JSVAL_VOID; + + return OBJECT_TO_JSVAL(object); + +#else // JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + +#ifdef __LP64__ + JSObject *typedArray = JS_NewFloat64Array( cx, 2 ); +#else + JSObject *typedArray = JS_NewFloat32Array( cx, 2 ); +#endif + + cpVect *buffer = (cpVect*)JS_GetArrayBufferViewData(typedArray, cx ); + *buffer = p; + return OBJECT_TO_JSVAL(typedArray); +#endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.h b/cocos/scripting/javascript/bindings/js_manual_conversions.h index 7a4999ae80..b3d15c86e1 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.h +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.h @@ -7,37 +7,70 @@ #include "jsapi.h" #include "js_bindings_core.h" - -//#ifdef __cplusplus -//extern "C" { -//#endif +#include "cocos2d.h" extern JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); extern JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); extern JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); extern JSBool jsval_to_long( JSContext *cx, jsval vp, long *out); -extern JSBool jsval_to_longlong( JSContext *cx, jsval vp, long long *out); -extern jsval opaque_to_jsval( JSContext *cx, void* opaque); -extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); extern JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); -extern jsval int_to_jsval( JSContext *cx, int number ); -extern jsval uint_to_jsval( JSContext *cx, unsigned int number ); -extern jsval long_to_jsval( JSContext *cx, long number ); -extern jsval longlong_to_jsval( JSContext *cx, long long number ); /** converts a jsval (JS string) into a char */ extern JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); + +extern jsval opaque_to_jsval( JSContext *cx, void* opaque); +extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); +extern jsval long_to_jsval( JSContext *cx, long number ); +extern jsval longlong_to_jsval( JSContext *cx, long long number ); + /* Converts a char ptr into a jsval (using JS string) */ extern jsval charptr_to_jsval( JSContext *cx, const char *str); - -extern JSBool JSB_jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ); -extern JSBool JSB_jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval); extern JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); extern JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); -extern JSBool JSB_jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ); -//#ifdef __cplusplus -//} -//#endif +// some utility functions +// to native +JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); +JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); +JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); +JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); +JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); +JSBool jsval_to_ccpoint(JSContext *cx, jsval v, cocos2d::Point* ret); +JSBool jsval_to_ccrect(JSContext *cx, jsval v, cocos2d::Rect* ret); +JSBool jsval_to_ccsize(JSContext *cx, jsval v, cocos2d::Size* ret); +JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, cocos2d::Color4B* ret); +JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, cocos2d::Color4F* ret); +JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, cocos2d::Color3B* ret); +JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, cocos2d::Point **points, int *numPoints); +JSBool jsval_to_ccarray(JSContext* cx, jsval v, cocos2d::Array** ret); +JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, cocos2d::Dictionary** ret); +JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, cocos2d::Acceleration* ret); +JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, cocos2d::Array** ret); +JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, cocos2d::AffineTransform* ret); +JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition* ret ); + +// from native +jsval int32_to_jsval( JSContext *cx, int32_t l); +jsval uint32_to_jsval( JSContext *cx, uint32_t number ); +jsval long_long_to_jsval(JSContext* cx, long long v); +jsval std_string_to_jsval(JSContext* cx, const std::string& v); +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); +jsval ccpoint_to_jsval(JSContext* cx, const cocos2d::Point& v); +jsval ccrect_to_jsval(JSContext* cx, const cocos2d::Rect& v); +jsval ccsize_to_jsval(JSContext* cx, const cocos2d::Size& v); +jsval cccolor4b_to_jsval(JSContext* cx, const cocos2d::Color4B& v); +jsval cccolor4f_to_jsval(JSContext* cx, const cocos2d::Color4F& v); +jsval cccolor3b_to_jsval(JSContext* cx, const cocos2d::Color3B& v); +jsval ccdictionary_to_jsval(JSContext* cx, cocos2d::Dictionary *dict); +jsval ccarray_to_jsval(JSContext* cx, cocos2d::Array *arr); +jsval ccacceleration_to_jsval(JSContext* cx, const cocos2d::Acceleration& v); +jsval ccaffinetransform_to_jsval(JSContext* cx, const cocos2d::AffineTransform& t); +jsval FontDefinition_to_jsval(JSContext* cx, const cocos2d::FontDefinition& t); + +JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *out ); +jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); + +#define cpVect_to_jsval CGPoint_to_jsval +#define jsval_to_cpVect jsval_to_CGPoint #endif /* __JS_MANUAL_CONVERSIONS_H__ */ diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp index 1d99cff3b3..878191adfd 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp @@ -12,7 +12,6 @@ //#include "jsb_config.h" #include "js_bindings_core.h" #include "js_manual_conversions.h" -#include "cocosjs_manual_conversions.h" #include "jsb_opengl_functions.h" // Arguments: GLenum @@ -23,7 +22,7 @@ JSBool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glActiveTexture((GLenum)arg0 ); @@ -39,8 +38,8 @@ JSBool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glAttachShader((GLuint)arg0 , (GLuint)arg1 ); @@ -56,8 +55,8 @@ JSBool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; const char* arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_charptr(cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -74,8 +73,8 @@ JSBool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindBuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -91,8 +90,8 @@ JSBool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindFramebuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -108,8 +107,8 @@ JSBool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindRenderbuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -125,8 +124,8 @@ JSBool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindTexture((GLenum)arg0 , (GLuint)arg1 ); @@ -142,10 +141,10 @@ JSBool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); @@ -161,7 +160,7 @@ JSBool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendEquation((GLenum)arg0 ); @@ -177,8 +176,8 @@ JSBool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendEquationSeparate((GLenum)arg0 , (GLenum)arg1 ); @@ -194,8 +193,8 @@ JSBool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendFunc((GLenum)arg0 , (GLenum)arg1 ); @@ -211,10 +210,10 @@ JSBool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); @@ -230,10 +229,10 @@ JSBool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg1); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBufferData((GLenum)arg0 , count, (GLvoid*)arg1 , (GLenum)arg2 ); @@ -249,8 +248,8 @@ JSBool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg2); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -268,7 +267,7 @@ JSBool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLenum ret_val; @@ -285,7 +284,7 @@ JSBool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClear((GLbitfield)arg0 ); @@ -301,10 +300,10 @@ JSBool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); @@ -320,7 +319,7 @@ JSBool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearDepthf((GLclampf)arg0 ); @@ -336,7 +335,7 @@ JSBool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearStencil((GLint)arg0 ); @@ -352,10 +351,10 @@ JSBool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint16_t arg0; uint16_t arg1; uint16_t arg2; uint16_t arg3; - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glColorMask((GLboolean)arg0 , (GLboolean)arg1 , (GLboolean)arg2 , (GLboolean)arg3 ); @@ -371,7 +370,7 @@ JSBool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCompileShader((GLuint)arg0 ); @@ -387,13 +386,13 @@ JSBool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; void* arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg7); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -411,14 +410,14 @@ JSBool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; int32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -436,14 +435,14 @@ JSBool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCopyTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLint)arg3 , (GLint)arg4 , (GLsizei)arg5 , (GLsizei)arg6 , (GLint)arg7 ); @@ -459,14 +458,14 @@ JSBool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCopyTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLsizei)arg7 ); @@ -493,7 +492,7 @@ JSBool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLuint ret_val; @@ -510,7 +509,7 @@ JSBool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCullFace((GLenum)arg0 ); @@ -526,7 +525,7 @@ JSBool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDeleteProgram((GLuint)arg0 ); @@ -542,7 +541,7 @@ JSBool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDeleteShader((GLuint)arg0 ); @@ -558,7 +557,7 @@ JSBool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthFunc((GLenum)arg0 ); @@ -574,7 +573,7 @@ JSBool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint16_t arg0; - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthMask((GLboolean)arg0 ); @@ -590,8 +589,8 @@ JSBool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthRangef((GLclampf)arg0 , (GLclampf)arg1 ); @@ -607,8 +606,8 @@ JSBool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDetachShader((GLuint)arg0 , (GLuint)arg1 ); @@ -624,7 +623,7 @@ JSBool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDisable((GLenum)arg0 ); @@ -640,7 +639,7 @@ JSBool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDisableVertexAttribArray((GLuint)arg0 ); @@ -656,9 +655,9 @@ JSBool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDrawArrays((GLenum)arg0 , (GLint)arg1 , (GLsizei)arg2 ); @@ -674,9 +673,9 @@ JSBool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; void* arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg3); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -694,7 +693,7 @@ JSBool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glEnable((GLenum)arg0 ); @@ -710,7 +709,7 @@ JSBool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glEnableVertexAttribArray((GLuint)arg0 ); @@ -746,10 +745,10 @@ JSBool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFramebufferRenderbuffer((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 ); @@ -765,11 +764,11 @@ JSBool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFramebufferTexture2D((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 , (GLint)arg4 ); @@ -785,7 +784,7 @@ JSBool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFrontFace((GLenum)arg0 ); @@ -801,7 +800,7 @@ JSBool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glGenerateMipmap((GLenum)arg0 ); @@ -817,7 +816,7 @@ JSBool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; const char* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); int ret_val; @@ -846,7 +845,7 @@ JSBool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; const char* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); printf("%s ", arg1); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -865,8 +864,8 @@ JSBool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glHint((GLenum)arg0 , (GLenum)arg1 ); @@ -882,7 +881,7 @@ JSBool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -899,7 +898,7 @@ JSBool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -916,7 +915,7 @@ JSBool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -933,7 +932,7 @@ JSBool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -950,7 +949,7 @@ JSBool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -967,7 +966,7 @@ JSBool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -984,7 +983,7 @@ JSBool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -1001,7 +1000,7 @@ JSBool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glLineWidth((GLfloat)arg0 ); @@ -1017,7 +1016,7 @@ JSBool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glLinkProgram((GLuint)arg0 ); @@ -1033,8 +1032,8 @@ JSBool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glPixelStorei((GLenum)arg0 , (GLint)arg1 ); @@ -1050,8 +1049,8 @@ JSBool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glPolygonOffset((GLfloat)arg0 , (GLfloat)arg1 ); @@ -1067,12 +1066,12 @@ JSBool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; uint32_t arg4; uint32_t arg5; void* arg6; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg5 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg6); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1100,10 +1099,10 @@ JSBool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glRenderbufferStorage((GLenum)arg0 , (GLenum)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); @@ -1119,8 +1118,8 @@ JSBool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glSampleCoverage((GLclampf)arg0 , (GLboolean)arg1 ); @@ -1136,10 +1135,10 @@ JSBool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glScissor((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); @@ -1155,9 +1154,9 @@ JSBool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilFunc((GLenum)arg0 , (GLint)arg1 , (GLuint)arg2 ); @@ -1173,10 +1172,10 @@ JSBool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 , (GLuint)arg3 ); @@ -1192,7 +1191,7 @@ JSBool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilMask((GLuint)arg0 ); @@ -1208,8 +1207,8 @@ JSBool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilMaskSeparate((GLenum)arg0 , (GLuint)arg1 ); @@ -1225,9 +1224,9 @@ JSBool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilOp((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 ); @@ -1243,10 +1242,10 @@ JSBool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilOpSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); @@ -1262,14 +1261,14 @@ JSBool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1287,9 +1286,9 @@ JSBool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glTexParameterf((GLenum)arg0 , (GLenum)arg1 , (GLfloat)arg2 ); @@ -1305,9 +1304,9 @@ JSBool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glTexParameteri((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 ); @@ -1323,14 +1322,14 @@ JSBool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1348,8 +1347,8 @@ JSBool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform1f((GLint)arg0 , (GLfloat)arg1 ); @@ -1365,8 +1364,8 @@ JSBool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1384,8 +1383,8 @@ JSBool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform1i((GLint)arg0 , (GLint)arg1 ); @@ -1401,8 +1400,8 @@ JSBool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1420,9 +1419,9 @@ JSBool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform2f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); @@ -1438,8 +1437,8 @@ JSBool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1457,9 +1456,9 @@ JSBool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform2i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 ); @@ -1475,8 +1474,8 @@ JSBool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1494,10 +1493,10 @@ JSBool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform3f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); @@ -1513,8 +1512,8 @@ JSBool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1532,10 +1531,10 @@ JSBool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform3i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 ); @@ -1551,8 +1550,8 @@ JSBool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1570,11 +1569,11 @@ JSBool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform4f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); @@ -1590,8 +1589,8 @@ JSBool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1609,11 +1608,11 @@ JSBool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform4i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 ); @@ -1629,8 +1628,8 @@ JSBool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1648,8 +1647,8 @@ JSBool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1667,8 +1666,8 @@ JSBool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1686,8 +1685,8 @@ JSBool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1705,7 +1704,7 @@ JSBool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUseProgram((GLuint)arg0 ); @@ -1721,7 +1720,7 @@ JSBool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glValidateProgram((GLuint)arg0 ); @@ -1737,8 +1736,8 @@ JSBool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib1f((GLuint)arg0 , (GLfloat)arg1 ); @@ -1754,7 +1753,7 @@ JSBool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1772,9 +1771,9 @@ JSBool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib2f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); @@ -1790,7 +1789,7 @@ JSBool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1808,10 +1807,10 @@ JSBool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib3f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); @@ -1827,7 +1826,7 @@ JSBool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1845,11 +1844,11 @@ JSBool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib4f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); @@ -1865,7 +1864,7 @@ JSBool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1883,12 +1882,12 @@ JSBool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; uint16_t arg3; int32_t arg4; int32_t arg5; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttribPointer((GLuint)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLboolean)arg3 , (GLsizei)arg4 , (GLvoid*)arg5 ); @@ -1904,10 +1903,10 @@ JSBool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glViewport((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp index 38a168b935..fa4e2d31c8 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp @@ -31,7 +31,6 @@ #include "jsb_opengl_manual.h" #include "js_manual_conversions.h" -#include "cocosjs_manual_conversions.h" #include "js_bindings_core.h" #include "jsb_opengl_functions.h" diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj index 11085f336c..a4cbbd4d50 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj @@ -13,7 +13,6 @@ - @@ -25,7 +24,6 @@ - diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters index 1d1e1d400a..85bb2eccd3 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters @@ -17,9 +17,6 @@ manual - - manual - manual @@ -49,9 +46,6 @@ manual - - manual - manual From 49289d7576501e9c943cc14d49ea518f736061c7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:46:00 +0800 Subject: [PATCH 191/197] Adding cc.TextureCache.getInstance() to jsb_deprecated.js. --- cocos/scripting/javascript/script/jsb_deprecated.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos/scripting/javascript/script/jsb_deprecated.js b/cocos/scripting/javascript/script/jsb_deprecated.js index 2c7a7b1ed1..cf2065152f 100644 --- a/cocos/scripting/javascript/script/jsb_deprecated.js +++ b/cocos/scripting/javascript/script/jsb_deprecated.js @@ -14,6 +14,10 @@ var cc = cc || {}; cc.AnimationCache.destroyInstance(); }; + cc.TextureCache.getInstance = function() { + return cc.Director.getInstance().getTextureCache(); + }; + // Deprecated member functions cc.Action.prototype.copy = function() { logW("cc.Action.copy", "cc.Action.clone"); From 22584ca9c2eafd27f344684ecfee68f870924c38 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:47:43 +0800 Subject: [PATCH 192/197] Updating submodule of bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index a943736554..9797d44032 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit a94373655409f756b33d8a58cc798dcb00be257c +Subproject commit 9797d4403207848f431d5b6456632cc966d84b0d From 394f4e703b068ebb83e17fe23cd3b939238e499d Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 17:06:32 +0800 Subject: [PATCH 193/197] Reverting AssetsManager::update. --- extensions/assets-manager/AssetsManager.cpp | 2 +- extensions/assets-manager/AssetsManager.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 06e5bd11c6..4913e5efd0 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -214,7 +214,7 @@ void AssetsManager::downloadAndUncompress() _isDownloading = false; } -void AssetsManager::update(float delta) +void AssetsManager::update() { if (_isDownloading) return; diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 5608084c76..f3e413f4bd 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -98,7 +98,7 @@ public: /* @brief Download new package if there is a new version, and uncompress downloaded zip file. * Ofcourse it will set search path that stores downloaded files. */ - virtual void update(float delta) override; + virtual void update(); /* @brief Gets url of package. */ From 1e15071dc7465020facc3756a97694875d7a75a7 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 17:29:48 +0800 Subject: [PATCH 194/197] remove makefiles --- build/Makefile | 91 ----- build/make-all-linux-project.sh | 24 -- cocos/2d/Makefile | 204 ----------- cocos/audio/CMakeLists.txt | 11 + cocos/audio/proj.linux/.cproject | 378 ------------------- cocos/audio/proj.linux/.project | 100 ----- cocos/audio/proj.linux/CocosDenshion.prf | 20 - cocos/audio/proj.linux/Makefile | 49 --- cocos/editor-support/cocosbuilder/Makefile | 44 --- cocos/editor-support/cocostudio/Makefile | 69 ---- cocos/editor-support/spine/Makefile | 42 --- cocos/gui/Makefile | 43 --- cocos/network/Makefile | 22 -- cocos/scripting/lua/bindings/Makefile | 94 ----- extensions/proj.linux/.cproject | 404 --------------------- extensions/proj.linux/.project | 90 ----- extensions/proj.linux/Makefile | 49 --- external/Box2D/proj.linux/.cproject | 267 -------------- external/Box2D/proj.linux/.project | 110 ------ external/Box2D/proj.linux/Makefile | 72 ---- external/Box2D/proj.linux/box2d.prf | 19 - external/chipmunk/proj.linux/.cproject | 236 ------------ external/chipmunk/proj.linux/.project | 95 ----- external/chipmunk/proj.linux/Makefile | 47 --- external/chipmunk/proj.linux/chipmunk.prf | 19 - 25 files changed, 11 insertions(+), 2588 deletions(-) delete mode 100644 build/Makefile delete mode 100755 build/make-all-linux-project.sh delete mode 100644 cocos/2d/Makefile delete mode 100644 cocos/audio/proj.linux/.cproject delete mode 100644 cocos/audio/proj.linux/.project delete mode 100644 cocos/audio/proj.linux/CocosDenshion.prf delete mode 100644 cocos/audio/proj.linux/Makefile delete mode 100644 cocos/editor-support/cocosbuilder/Makefile delete mode 100644 cocos/editor-support/cocostudio/Makefile delete mode 100644 cocos/editor-support/spine/Makefile delete mode 100644 cocos/gui/Makefile delete mode 100644 cocos/network/Makefile delete mode 100644 cocos/scripting/lua/bindings/Makefile delete mode 100644 extensions/proj.linux/.cproject delete mode 100644 extensions/proj.linux/.project delete mode 100644 extensions/proj.linux/Makefile delete mode 100644 external/Box2D/proj.linux/.cproject delete mode 100644 external/Box2D/proj.linux/.project delete mode 100644 external/Box2D/proj.linux/Makefile delete mode 100644 external/Box2D/proj.linux/box2d.prf delete mode 100644 external/chipmunk/proj.linux/.cproject delete mode 100644 external/chipmunk/proj.linux/.project delete mode 100644 external/chipmunk/proj.linux/Makefile delete mode 100644 external/chipmunk/proj.linux/chipmunk.prf diff --git a/build/Makefile b/build/Makefile deleted file mode 100644 index 761855d264..0000000000 --- a/build/Makefile +++ /dev/null @@ -1,91 +0,0 @@ -PLATFORM ?= linux - -all: - -chipmunk: - $(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) -chipmunk-clean: - $(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) clean - -box2d: - $(MAKE) -C ../external/Box2D/proj.$(PLATFORM) -box2d-clean: - $(MAKE) -C ../external/Box2D/proj.$(PLATFORM) clean - -cocos2dx: chipmunk - $(MAKE) -C ../cocos/2d -cocos2dx-clean: - $(MAKE) -C ../cocos/2d clean - -audio: cocos2dx - $(MAKE) -C ../cocos/audio/proj.$(PLATFORM) -audio-clean: - $(MAKE) -C ../cocos/audio/proj.$(PLATFORM) clean - -gui: - $(MAKE) -C ../cocos/gui -gui-clean: - $(MAKE) -C ../cocos/gui clean - -network: cocos2dx - $(MAKE) -C ../cocos/network -network-clean: - $(MAKE) -C ../cocos/network clean - -cocosbuilder: - $(MAKE) -C ../cocos/editor-support/cocosbuilder -cocosbuilder-clean: - $(MAKE) -C ../cocos/editor-support/cocosbuilder clean - -spine: - $(MAKE) -C ../cocos/editor-support/spine -spine-clean: - $(MAKE) -C ../cocos/editor-support/spine clean - -cocostudio: - $(MAKE) -C ../cocos/editor-support/cocostudio -cocostudio-clean: - $(MAKE) -C ../cocos/editor-support/cocostudio clean - -extensions: chipmunk audio box2d - $(MAKE) -C ../extensions/proj.$(PLATFORM) -extensions-clean: - $(MAKE) -C ../extensions/proj.$(PLATFORM) clean - -lua: extensions cocosbuilder cocostudio - $(MAKE) -C ../cocos/scripting/lua/bindings -lua-clean: - $(MAKE) -C ../cocos/scripting/lua/bindings clean - -hellocpp: cocos2dx - $(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) -hellocpp-clean: - $(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) clean - -testcpp: cocos2dx audio extensions cocostudio gui cocosbuilder spine network - $(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) -testcpp-clean: - $(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) clean - -simplegame: cocos2dx audio - $(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) -simplegame-clean: - $(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) clean - -all: chipmunk audio extensions cocos2dx lua hellocpp testcpp simplegame -clean: cocos2dx-clean box2d-clean chipmunk-clean audio-clean extensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean - -hellolua: cocos2dx lua - $(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) -hellolua-clean: - $(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) clean - -testlua: cocos2dx lua - $(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) -testlua-clean: - $(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) clean - -all: hellolua testlua -clean: hellolua-clean testlua-clean - -.PHONY: all clean diff --git a/build/make-all-linux-project.sh b/build/make-all-linux-project.sh deleted file mode 100755 index 98eaeef714..0000000000 --- a/build/make-all-linux-project.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -# This script will perform a clean linux build of all targets in both -# debug and release configurations. It will also ensure that all the required -# packages are installed. For day-to-day work on the linux port it is -# faster/better to simply use 'make' either at the top level or in the subpject -# you are working on. - -# Exit of first error. -set -e - -# Change directory to the location of this script -cd $(dirname ${BASH_SOURCE[0]}) - -[ -z "$COCOS2DX_USEAPT" ] && COCOS2DX_USEAPT=true - -if $COCOS2DX_USEAPT; then - ./install-deps-linux.sh -fi - -mkdir -p linux-build -cd linux-build -cmake ../.. -make -j10 - diff --git a/cocos/2d/Makefile b/cocos/2d/Makefile deleted file mode 100644 index 3e711d5d20..0000000000 --- a/cocos/2d/Makefile +++ /dev/null @@ -1,204 +0,0 @@ -TARGET = libcocos2d.so - -INCLUDES = - -SOURCES = \ -CCAction.cpp \ -CCActionCamera.cpp \ -CCActionEase.cpp \ -CCActionGrid.cpp \ -CCActionGrid3D.cpp \ -CCActionInstant.cpp \ -CCActionInterval.cpp \ -CCActionManager.cpp \ -CCActionPageTurn3D.cpp \ -CCActionProgressTimer.cpp \ -CCActionTiledGrid.cpp \ -CCActionCatmullRom.cpp \ -CCActionTween.cpp \ -CCAtlasNode.cpp \ -CCNode.cpp \ -../base/CCAffineTransform.cpp \ -../base/CCAutoreleasePool.cpp \ -../base/CCGeometry.cpp \ -../base/CCNS.cpp \ -../base/CCObject.cpp \ -../base/CCSet.cpp \ -../base/CCArray.cpp \ -../base/CCDictionary.cpp \ -../base/CCString.cpp \ -../base/CCDataVisitor.cpp \ -../base/CCData.cpp \ -CCEventAcceleration.cpp \ -CCEventListenerAcceleration.cpp \ -CCEvent.cpp \ -CCEventDispatcher.cpp \ -CCEventListener.cpp \ -CCEventKeyboard.cpp \ -CCEventListenerKeyboard.cpp \ -CCEventMouse.cpp \ -CCEventListenerMouse.cpp \ -CCTouch.cpp \ -CCEventTouch.cpp \ -CCEventListenerTouch.cpp \ -CCEventCustom.cpp \ -CCEventListenerCustom.cpp \ -CCDrawingPrimitives.cpp \ -CCDrawNode.cpp \ -CCGrabber.cpp \ -CCGrid.cpp \ -CCFont.cpp \ -CCFontAtlas.cpp \ -CCFontAtlasCache.cpp \ -CCFontAtlasFactory.cpp \ -CCFontDefinition.cpp \ -CCFontFNT.cpp \ -CCFontFreeType.cpp \ -CCLabel.cpp \ -CCLabelAtlas.cpp \ -CCLabelBMFont.cpp \ -CCLabelTTF.cpp \ -CCLabelTextFormatter.cpp \ -CCTextImage.cpp \ -CCLayer.cpp \ -CCScene.cpp \ -CCTransition.cpp \ -CCTransitionPageTurn.cpp \ -CCTransitionProgress.cpp \ -CCMenu.cpp \ -CCMenuItem.cpp \ -CCMotionStreak.cpp \ -CCProgressTimer.cpp \ -CCClippingNode.cpp \ -CCRenderTexture.cpp \ -CCParticleExamples.cpp \ -CCParticleSystem.cpp \ -CCParticleSystemQuad.cpp \ -CCParticleBatchNode.cpp \ -../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ -../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ -../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ -../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ -../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ -../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ -../physics/CCPhysicsBody.cpp \ -../physics/CCPhysicsContact.cpp \ -../physics/CCPhysicsShape.cpp \ -../physics/CCPhysicsJoint.cpp \ -../physics/CCPhysicsWorld.cpp \ -../platform/CCSAXParser.cpp \ -../platform/CCThread.cpp \ -../platform/CCEGLViewProtocol.cpp \ -../platform/CCFileUtils.cpp \ -../platform/linux/CCStdC.cpp \ -../platform/linux/CCFileUtilsLinux.cpp \ -../platform/linux/CCCommon.cpp \ -../platform/linux/CCApplication.cpp \ -../platform/linux/CCEGLView.cpp \ -../platform/linux/CCImage.cpp \ -../platform/linux/CCDevice.cpp \ -../base/etc1.cpp \ -../base/s3tc.cpp \ -../base/atitc.cpp \ -CCScriptSupport.cpp \ -CCAnimation.cpp \ -CCAnimationCache.cpp \ -CCSprite.cpp \ -CCSpriteBatchNode.cpp \ -CCSpriteFrame.cpp \ -CCSpriteFrameCache.cpp \ -ccUTF8.cpp \ -CCProfiling.cpp \ -CCUserDefault.cpp \ -TransformUtils.cpp \ -base64.cpp \ -ccUtils.cpp \ -CCVertex.cpp \ -CCNotificationCenter.cpp \ -TGAlib.cpp \ -../../external/tinyxml2/tinyxml2.cpp \ -ZipUtils.cpp \ -../../external/unzip/ioapi.cpp \ -../../external/unzip/unzip.cpp \ -ccCArray.cpp \ -CCComponent.cpp \ -CCComponentContainer.cpp \ -CCIMEDispatcher.cpp \ -CCTextFieldTTF.cpp \ -CCTexture2D.cpp \ -CCTextureAtlas.cpp \ -CCTextureCache.cpp \ -CCParallaxNode.cpp \ -CCTMXLayer.cpp \ -CCTMXObjectGroup.cpp \ -CCTMXTiledMap.cpp \ -CCTMXXMLParser.cpp \ -CCTileMapAtlas.cpp \ -CCGLProgram.cpp \ -ccGLStateCache.cpp \ -CCShaderCache.cpp \ -ccShaders.cpp \ -../math/kazmath/src/aabb.c \ -../math/kazmath/src/plane.c \ -../math/kazmath/src/vec2.c \ -../math/kazmath/src/mat3.c \ -../math/kazmath/src/quaternion.c \ -../math/kazmath/src/vec3.c \ -../math/kazmath/src/mat4.c \ -../math/kazmath/src/ray2.c \ -../math/kazmath/src/vec4.c \ -../math/kazmath/src/neon_matrix_impl.c \ -../math/kazmath/src/utility.c \ -../math/kazmath/src/GL/mat4stack.c \ -../math/kazmath/src/GL/matrix.c \ -CCCamera.cpp \ -CCConfiguration.cpp \ -CCDirector.cpp \ -CCScheduler.cpp \ -ccFPSImages.c \ -ccTypes.cpp \ -cocos2d.cpp \ -CCDeprecated.cpp - -COCOS_ROOT = ../.. - -include cocos2dx.mk - -CXXFLAGS += -Wno-sequence-point -CCFLAGS += -Wno-sequence-point - -STATICLIBS += $(LIB_DIR)/libchipmunk.a - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - - diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 12fde54f25..2f1d642cb2 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -3,6 +3,17 @@ set(AUDIO_SRC linux/FmodAudioPlayer.cpp ) +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + +include_directories( + ../../external/linux-specific/fmod/include/${ARCH_DIR} +) + add_library(audio STATIC ${AUDIO_SRC} ) diff --git a/cocos/audio/proj.linux/.cproject b/cocos/audio/proj.linux/.cproject deleted file mode 100644 index fc010e1ed7..0000000000 --- a/cocos/audio/proj.linux/.cproject +++ /dev/null @@ -1,378 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cocos/audio/proj.linux/.project b/cocos/audio/proj.linux/.project deleted file mode 100644 index 2860d8d849..0000000000 --- a/cocos/audio/proj.linux/.project +++ /dev/null @@ -1,100 +0,0 @@ - - - libCocosDenshion - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/CocosDenshion/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - linux - 2 - PARENT-1-PROJECT_LOC/linux - - - third_party - 2 - PARENT-1-PROJECT_LOC/third_party - - - diff --git a/cocos/audio/proj.linux/CocosDenshion.prf b/cocos/audio/proj.linux/CocosDenshion.prf deleted file mode 100644 index 4c7ec10f0c..0000000000 --- a/cocos/audio/proj.linux/CocosDenshion.prf +++ /dev/null @@ -1,20 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile extensions on demand using Makefile. - build_CocosDension.name = Build extension static library - build_CocosDension.input = $$PWD/Makefile - build_CocosDension.output = $$CC_LIBRARY_DIR/libcocosdenshion.so - build_CocosDension.target = $$CC_LIBRARY_DIR/libcocosdenshion.so - build_CocosDension.CONFIG = no_link target_predeps - build_CocosDension.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_CocosDension - QMAKE_EXTRA_TARGETS += build_CocosDension - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libcocosdenshion.so - LIBS += -lcocosdenshion -} - diff --git a/cocos/audio/proj.linux/Makefile b/cocos/audio/proj.linux/Makefile deleted file mode 100644 index e8b18e3972..0000000000 --- a/cocos/audio/proj.linux/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -TARGET = libcocosdenshion.so - -INCLUDES = -I.. -I../include - -##Using OpenAL -ifeq ($(OPENAL),1) -SOURCES = ../openal/OpenALDecoder.cpp \ - ../openal/SimpleAudioEngineOpenAL.cpp -SHAREDLIBS += -lopenal -lalut - -ifeq ($(OPENAL_MP3),1) -DEFINES += -DENABLE_MPG123 -SHAREDLIBS += -lmpg123 -endif - -ifneq ($(NOVORBIS),1) -SHAREDLIBS += -logg -lvorbis -lvorbisfile -else -DEFINES += -DDISABLE_VORBIS -endif - -##Using FMOD -else -SOURCES = \ - ../linux/SimpleAudioEngineFMOD.cpp \ - ../linux/FmodAudioPlayer.cpp - -ifeq ($(LBITS),64) -INCLUDES += -I../third-party/fmod/lib64/api/inc -else -INCLUDES += -I../third-party/fmod/api/inc -endif - -endif - -COCOS_ROOT = ../../.. -include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $(TARGET) $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ diff --git a/cocos/editor-support/cocosbuilder/Makefile b/cocos/editor-support/cocosbuilder/Makefile deleted file mode 100644 index 688c5d49d5..0000000000 --- a/cocos/editor-support/cocosbuilder/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -TARGET = libcocosbuilder.a - -INCLUDES = - -SOURCES = CCBFileLoader.cpp \ -CCMenuItemImageLoader.cpp \ -CCBReader.cpp \ -CCMenuItemLoader.cpp \ -CCControlButtonLoader.cpp \ -CCNodeLoader.cpp \ -CCControlLoader.cpp \ -CCNodeLoaderLibrary.cpp \ -CCLabelBMFontLoader.cpp \ -CCParticleSystemQuadLoader.cpp \ -CCLabelTTFLoader.cpp \ -CCScale9SpriteLoader.cpp \ -CCLayerColorLoader.cpp \ -CCScrollViewLoader.cpp \ -CCLayerGradientLoader.cpp \ -CCSpriteLoader.cpp \ -CCLayerLoader.cpp \ -CCBAnimationManager.cpp \ -CCBKeyframe.cpp \ -CCBSequence.cpp \ -CCBSequenceProperty.cpp \ -CCBValue.cpp \ -CCNode+CCBRelativePositioning.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - diff --git a/cocos/editor-support/cocostudio/Makefile b/cocos/editor-support/cocostudio/Makefile deleted file mode 100644 index 810c28372e..0000000000 --- a/cocos/editor-support/cocostudio/Makefile +++ /dev/null @@ -1,69 +0,0 @@ -TARGET = libcocostudio.a - -COCOS_ROOT=../../.. - -INCLUDES = -I../../2d \ --I../../../external \ --I.. \ --I../.. \ - -SOURCES = CCActionFrame.cpp \ -CCActionFrameEasing.cpp \ -CCActionManagerEx.cpp \ -CCActionNode.cpp \ -CCActionObject.cpp \ -CCArmature.cpp \ -CCBone.cpp \ -CCArmatureAnimation.cpp \ -CCProcessBase.cpp \ -CCTween.cpp \ -CCDatas.cpp \ -CCBatchNode.cpp \ -CCDecorativeDisplay.cpp \ -CCDisplayFactory.cpp \ -CCDisplayManager.cpp \ -CCSkin.cpp \ -CCColliderDetector.cpp \ -CCArmatureDataManager.cpp \ -CCArmatureDefine.cpp \ -CCDataReaderHelper.cpp \ -CCSpriteFrameCacheHelper.cpp \ -CCTransformHelp.cpp \ -CCTweenFunction.cpp \ -CCUtilMath.cpp \ -CCComAttribute.cpp \ -CCComAudio.cpp \ -CCComController.cpp \ -CCComRender.cpp \ -CCInputDelegate.cpp \ -CSContentJsonDictionary.cpp \ -DictionaryHelper.cpp \ -CCSGUIReader.cpp \ -CCSSceneReader.cpp \ -../../../external/json/json_reader.cpp \ -../../../external/json/json_value.cpp \ -../../../external/json/json_writer.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/editor-support/spine/Makefile b/cocos/editor-support/spine/Makefile deleted file mode 100644 index 88514a824e..0000000000 --- a/cocos/editor-support/spine/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -TARGET = libspine.a - -INCLUDES = -I.. - -SOURCES = Animation.cpp \ -AnimationState.cpp \ -AnimationStateData.cpp \ -Atlas.cpp \ -AtlasAttachmentLoader.cpp \ -Attachment.cpp \ -AttachmentLoader.cpp \ -Bone.cpp \ -BoneData.cpp \ -Json.cpp \ -RegionAttachment.cpp \ -Skeleton.cpp \ -SkeletonData.cpp \ -SkeletonJson.cpp \ -Skin.cpp \ -Slot.cpp \ -SlotData.cpp \ -extension.cpp \ -spine-cocos2dx.cpp \ -CCSkeleton.cpp \ -CCSkeletonAnimation.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - diff --git a/cocos/gui/Makefile b/cocos/gui/Makefile deleted file mode 100644 index 8dcb0cb404..0000000000 --- a/cocos/gui/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -TARGET = libgui.a - -INCLUDES = -I../ \ --I../editor-support \ --I../../external - -SOURCES = UIRootWidget.cpp \ -UIWidget.cpp \ -UILayout.cpp \ -UILayoutParameter.cpp \ -UILayoutDefine.cpp \ -CocosGUI.cpp \ -UIHelper.cpp \ -UIInputManager.cpp \ -UILayer.cpp \ -UIListView.cpp \ -UIPageView.cpp \ -UIScrollView.cpp \ -UIButton.cpp \ -UICheckBox.cpp \ -UIImageView.cpp \ -UILabel.cpp \ -UILabelAtlas.cpp \ -UILabelBMFont.cpp \ -UILoadingBar.cpp \ -UISlider.cpp \ -UITextField.cpp - -include ../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/network/Makefile b/cocos/network/Makefile deleted file mode 100644 index 029078722d..0000000000 --- a/cocos/network/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TARGET = libnetwork.a - -INCLUDES = -I.. - -SOURCES = HttpClient.cpp \ -SocketIO.cpp - -include ../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile deleted file mode 100644 index 546ad977b4..0000000000 --- a/cocos/scripting/lua/bindings/Makefile +++ /dev/null @@ -1,94 +0,0 @@ -TARGET = liblua.so - -INCLUDES += -I../../../../external/lua/tolua \ --I../../../../external/lua/lua \ --I../../auto-generated/lua-bindings \ --I../../../../extensions \ --I../../../editor-support \ --I. \ --I../../../editor-support/cocosbuilder \ --I../../../editor-support/cocostudio \ --I../../../../external \ --I../../../ - -SOURCES = ../../../../external/lua/lua/lapi.c \ - ../../../../external/lua/lua/lauxlib.c \ - ../../../../external/lua/lua/lbaselib.c \ - ../../../../external/lua/lua/lcode.c \ - ../../../../external/lua/lua/ldblib.c \ - ../../../../external/lua/lua/ldebug.c \ - ../../../../external/lua/lua/ldo.c \ - ../../../../external/lua/lua/ldump.c \ - ../../../../external/lua/lua/lfunc.c \ - ../../../../external/lua/lua/lgc.c \ - ../../../../external/lua/lua/linit.c \ - ../../../../external/lua/lua/liolib.c \ - ../../../../external/lua/lua/llex.c \ - ../../../../external/lua/lua/lmathlib.c \ - ../../../../external/lua/lua/lmem.c \ - ../../../../external/lua/lua/loadlib.c \ - ../../../../external/lua/lua/lobject.c \ - ../../../../external/lua/lua/lopcodes.c \ - ../../../../external/lua/lua/loslib.c \ - ../../../../external/lua/lua/lparser.c \ - ../../../../external/lua/lua/lstate.c \ - ../../../../external/lua/lua/lstring.c \ - ../../../../external/lua/lua/lstrlib.c \ - ../../../../external/lua/lua/ltable.c \ - ../../../../external/lua/lua/ltablib.c \ - ../../../../external/lua/lua/ltm.c \ - ../../../../external/lua/lua/lundump.c \ - ../../../../external/lua/lua/lvm.c \ - ../../../../external/lua/lua/lzio.c \ - ../../../../external/lua/lua/print.c \ - ../../../../external/lua/tolua/tolua_event.c \ - ../../../../external/lua/tolua/tolua_is.c \ - ../../../../external/lua/tolua/tolua_map.c \ - ../../../../external/lua/tolua/tolua_push.c \ - ../../../../external/lua/tolua/tolua_to.c \ - tolua_fix.c \ - ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ - ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ - ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ - CCLuaBridge.cpp \ - CCLuaEngine.cpp \ - CCLuaStack.cpp \ - CCLuaValue.cpp \ - Cocos2dxLuaLoader.cpp \ - CCBProxy.cpp \ - LuaOpengl.cpp \ - LuaScriptHandlerMgr.cpp \ - LuaBasicConversions.cpp \ - lua_cocos2dx_manual.cpp \ - lua_cocos2dx_extension_manual.cpp \ - lua_cocos2dx_deprecated.cpp \ - lua_xml_http_request.cpp - - -include ../../../2d/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) -SHAREDLIBS += -lextension -lcocostudio -lcocosbuilder -STATICLIBS += $(LIB_DIR)/libbox2d.a - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../../../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/extensions/proj.linux/.cproject b/extensions/proj.linux/.cproject deleted file mode 100644 index 696f0898ce..0000000000 --- a/extensions/proj.linux/.cproject +++ /dev/null @@ -1,404 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/extensions/proj.linux/.project b/extensions/proj.linux/.project deleted file mode 100644 index 37e93964dd..0000000000 --- a/extensions/proj.linux/.project +++ /dev/null @@ -1,90 +0,0 @@ - - - libextension - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - CCBReader - 2 - PARENT-1-PROJECT_LOC/CCBReader - - - CCArmature - 2 - PARENT-1-PROJECT_LOC/CCArmature - - - Components - 2 - PARENT-1-PROJECT_LOC/Components - - - spine - 2 - PARENT-1-PROJECT_LOC/spine - - - ExtensionMacros.h - 1 - PARENT-1-PROJECT_LOC/ExtensionMacros.h - - - GUI - 2 - PARENT-1-PROJECT_LOC/GUI - - - LocalStorage - 2 - PARENT-1-PROJECT_LOC/LocalStorage - - - cocos-ext.h - 1 - PARENT-1-PROJECT_LOC/cocos-ext.h - - - network - 2 - PARENT-1-PROJECT_LOC/network - - - physics_nodes - 2 - PARENT-1-PROJECT_LOC/physics_nodes - - - - - 1373359750543 - - 22 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-WebSocket.* - - - - diff --git a/extensions/proj.linux/Makefile b/extensions/proj.linux/Makefile deleted file mode 100644 index fe07e988e5..0000000000 --- a/extensions/proj.linux/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -TARGET = libextension.a - -INCLUDES = -I.. - -SOURCES = \ -assets-manager/AssetsManager.cpp \ -GUI/CCControlExtension/CCControl.cpp \ -GUI/CCControlExtension/CCControlButton.cpp \ -GUI/CCControlExtension/CCControlColourPicker.cpp \ -GUI/CCControlExtension/CCControlHuePicker.cpp \ -GUI/CCControlExtension/CCControlPotentiometer.cpp \ -GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ -GUI/CCControlExtension/CCControlSlider.cpp \ -GUI/CCControlExtension/CCControlStepper.cpp \ -GUI/CCControlExtension/CCControlSwitch.cpp \ -GUI/CCControlExtension/CCControlUtils.cpp \ -GUI/CCControlExtension/CCInvocation.cpp \ -GUI/CCControlExtension/CCScale9Sprite.cpp \ -GUI/CCEditBox/CCEditBox.cpp \ -GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ -GUI/CCEditBox/CCEditBoxImplNone.cpp \ -GUI/CCEditBox/CCEditBoxImplTizen.cpp \ -GUI/CCEditBox/CCEditBoxImplWin.cpp \ -GUI/CCScrollView/CCScrollView.cpp \ -GUI/CCScrollView/CCSorting.cpp \ -GUI/CCScrollView/CCTableView.cpp \ -GUI/CCScrollView/CCTableViewCell.cpp \ -physics-nodes/CCPhysicsDebugNode.cpp \ -physics-nodes/CCPhysicsSprite.cpp - -include ../../cocos/2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar -Wno-unused-result - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/.cproject b/external/Box2D/proj.linux/.cproject deleted file mode 100644 index 5aa092cac3..0000000000 --- a/external/Box2D/proj.linux/.cproject +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/Box2D/proj.linux/.project b/external/Box2D/proj.linux/.project deleted file mode 100644 index 164d50f52a..0000000000 --- a/external/Box2D/proj.linux/.project +++ /dev/null @@ -1,110 +0,0 @@ - - - libBox2D - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libBox2D/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Box2D.h - 1 - PARENT-1-PROJECT_LOC/Box2D.h - - - Collision - 2 - PARENT-1-PROJECT_LOC/Collision - - - Common - 2 - PARENT-1-PROJECT_LOC/Common - - - Dynamics - 2 - PARENT-1-PROJECT_LOC/Dynamics - - - Rope - 2 - PARENT-1-PROJECT_LOC/Rope - - - diff --git a/external/Box2D/proj.linux/Makefile b/external/Box2D/proj.linux/Makefile deleted file mode 100644 index b43814ccef..0000000000 --- a/external/Box2D/proj.linux/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -TARGET = libbox2d.a - -SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ -../Collision/Shapes/b2CircleShape.cpp \ -../Collision/Shapes/b2EdgeShape.cpp \ -../Collision/Shapes/b2PolygonShape.cpp \ -../Collision/b2BroadPhase.cpp \ -../Collision/b2CollideCircle.cpp \ -../Collision/b2CollideEdge.cpp \ -../Collision/b2CollidePolygon.cpp \ -../Collision/b2Collision.cpp \ -../Collision/b2Distance.cpp \ -../Collision/b2DynamicTree.cpp \ -../Collision/b2TimeOfImpact.cpp \ -../Common/b2BlockAllocator.cpp \ -../Common/b2Draw.cpp \ -../Common/b2Math.cpp \ -../Common/b2Settings.cpp \ -../Common/b2StackAllocator.cpp \ -../Common/b2Timer.cpp \ -../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -../Dynamics/Contacts/b2CircleContact.cpp \ -../Dynamics/Contacts/b2Contact.cpp \ -../Dynamics/Contacts/b2ContactSolver.cpp \ -../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -../Dynamics/Contacts/b2PolygonContact.cpp \ -../Dynamics/Joints/b2DistanceJoint.cpp \ -../Dynamics/Joints/b2FrictionJoint.cpp \ -../Dynamics/Joints/b2GearJoint.cpp \ -../Dynamics/Joints/b2Joint.cpp \ -../Dynamics/Joints/b2MouseJoint.cpp \ -../Dynamics/Joints/b2PrismaticJoint.cpp \ -../Dynamics/Joints/b2PulleyJoint.cpp \ -../Dynamics/Joints/b2RevoluteJoint.cpp \ -../Dynamics/Joints/b2RopeJoint.cpp \ -../Dynamics/Joints/b2WeldJoint.cpp \ -../Dynamics/Joints/b2WheelJoint.cpp \ -../Dynamics/b2Body.cpp \ -../Dynamics/b2ContactManager.cpp \ -../Dynamics/b2Fixture.cpp \ -../Dynamics/b2Island.cpp \ -../Dynamics/b2World.cpp \ -../Dynamics/b2WorldCallbacks.cpp \ -../Rope/b2Rope.cpp - -include ../../../cocos/2d/cocos2dx.mk - -INCLUDES = -I../.. - -# Cocos2d is not responsible for warnings in external projects -CXXFLAGS += -w - -ifeq ($(DEBUG), 1) -DEFINES = -D_DEBUG -else -DEFINES = -endif - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/box2d.prf b/external/Box2D/proj.linux/box2d.prf deleted file mode 100644 index 434ad88406..0000000000 --- a/external/Box2D/proj.linux/box2d.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile box2d on demand using Makefile. - build_box2d.name = Build box2d static library - build_box2d.input = $$PWD/Makefile - build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.CONFIG = no_link target_predeps - build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_box2d - QMAKE_EXTRA_TARGETS += build_box2d - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a - LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic -} diff --git a/external/chipmunk/proj.linux/.cproject b/external/chipmunk/proj.linux/.cproject deleted file mode 100644 index 18467c15ca..0000000000 --- a/external/chipmunk/proj.linux/.cproject +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/chipmunk/proj.linux/.project b/external/chipmunk/proj.linux/.project deleted file mode 100644 index 2f42dedf9b..0000000000 --- a/external/chipmunk/proj.linux/.project +++ /dev/null @@ -1,95 +0,0 @@ - - - libChipmunk - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libChipmunk/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - src - 2 - PARENT-1-PROJECT_LOC/src - - - diff --git a/external/chipmunk/proj.linux/Makefile b/external/chipmunk/proj.linux/Makefile deleted file mode 100644 index a2cb985b7c..0000000000 --- a/external/chipmunk/proj.linux/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -SOURCES = ../src/chipmunk.c \ - ../src/cpBody.c \ - ../src/cpSpace.c \ - ../src/cpSpatialIndex.c \ - ../src/cpArbiter.c \ - ../src/cpCollision.c \ - ../src/cpSpaceComponent.c \ - ../src/cpSweep1D.c \ - ../src/cpArray.c \ - ../src/cpHashSet.c \ - ../src/cpSpaceHash.c \ - ../src/cpVect.c \ - ../src/cpBB.c \ - ../src/cpPolyShape.c \ - ../src/cpSpaceQuery.c \ - ../src/cpBBTree.c \ - ../src/cpShape.c \ - ../src/cpSpaceStep.c \ - ../src/constraints/cpConstraint.c \ - ../src/constraints/cpPivotJoint.c \ - ../src/constraints/cpDampedRotarySpring.c \ - ../src/constraints/cpRatchetJoint.c \ - ../src/constraints/cpDampedSpring.c \ - ../src/constraints/cpRotaryLimitJoint.c \ - ../src/constraints/cpGearJoint.c \ - ../src/constraints/cpSimpleMotor.c \ - ../src/constraints/cpGrooveJoint.c \ - ../src/constraints/cpSlideJoint.c \ - ../src/constraints/cpPinJoint.c \ - -include ../../../cocos/2d/cocos2dx.mk - -TARGET = $(LIB_DIR)/libchipmunk.a -INCLUDES = -I../include/chipmunk -DEFINES = -DLINUX -CCFLAGS += -std=gnu99 -OBJECTS := $(subst src/,,$(OBJECTS)) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../src/%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/chipmunk/proj.linux/chipmunk.prf b/external/chipmunk/proj.linux/chipmunk.prf deleted file mode 100644 index a807b0ab99..0000000000 --- a/external/chipmunk/proj.linux/chipmunk.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile chipmunk on demand using Makefile. - build_chipmunk.name = Build chipmunk static library - build_chipmunk.input = $$PWD/Makefile - build_chipmunk.output = $$CC_LIBRARY_DIR/libchipmunk.a - build_chipmunk.target = $$CC_LIBRARY_DIR/libchipmunk.a - build_chipmunk.CONFIG = no_link target_predeps - build_chipmunk.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_chipmunk - QMAKE_EXTRA_TARGETS += build_chipmunk - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libchipmunk.a - LIBS += -Wl,-Bstatic -lchipmunk -Wl,-Bdynamic -} From d1a414194ef5f6f91de2ea31849df9a567a39044 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 17:36:23 +0800 Subject: [PATCH 195/197] [ci skip]update linux build commands --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2b1a5fa297..938f0c39fb 100644 --- a/README.md +++ b/README.md @@ -98,10 +98,13 @@ $ open samples.xcodeproj ``` $ cd cocos2d-x/build -$ ./make-all-linux-project.sh +$ ./install-deps-linux.sh +$ cmake .. +$ make ``` -You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. + You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. + `install-deps-linux.sh` only has to be run onece. * For Windows From df214acb6f062a5f5aa0e06605de89c6b71d157b Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 18:42:39 +0800 Subject: [PATCH 196/197] [develop] Updating bindings-generator, fixing forward declare that generates binding glue codes which is an empty class. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 9797d44032..cad9d9ec4a 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 9797d4403207848f431d5b6456632cc966d84b0d +Subproject commit cad9d9ec4a24bdad1de383c941afa9418501161e From 3472d7ad50be0f61135949f06714f5bc4de9afde Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 11 Nov 2013 10:57:57 +0000 Subject: [PATCH 197/197] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 5788b25003..ce2f223cd3 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 5788b2500339473ecc19acf1c2e43656a2537a6d +Subproject commit ce2f223cd3b4bffbd564df37c738fc5b18f8d853