Merge pull request #5 from cocos2d/develop

sync original repo
This commit is contained in:
子龙山人 2013-12-30 01:35:23 -08:00
commit 50c9617d25
265 changed files with 10246 additions and 10568 deletions

View File

@ -677,10 +677,17 @@ Developers:
seobyeongky seobyeongky
Updates spine runtime. Updates spine runtime.
Fixed a potential bug in Data's copy constructor.
luocker luocker
Fix a bug that string itself is also modified in `String::componentsSeparatedByString`. Fix a bug that string itself is also modified in `String::componentsSeparatedByString`.
omersaeed
Fix a bug that game will crash if connection breaks during download using AssetManager.
SBKarr
AngelCode binary file format support for LabelBMFont.
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang
Author of windows port, CCTextField, Author of windows port, CCTextField,

View File

@ -16,6 +16,9 @@ cocos2d-x-3.0beta0 ?? 2013
[FIX] Deprecates FileUtils::getFileData, adds FileUtils::getStringFromFile/getDataFromFile. [FIX] Deprecates FileUtils::getFileData, adds FileUtils::getStringFromFile/getDataFromFile.
[FIX] GUI refactoring: Removes UI prefix, Widget is inherited from Node, uses new containers(Vector<T>, Map<K,V>). [FIX] GUI refactoring: Removes UI prefix, Widget is inherited from Node, uses new containers(Vector<T>, Map<K,V>).
[FIX] String itself is also modified in `String::componentsSeparatedByString`. [FIX] String itself is also modified in `String::componentsSeparatedByString`.
[FIX] Sprites with PhysicsBody move to a wrong position when game resume from background.
[FIX] Crash if connection breaks during download using AssetManager.
[NEW] AngelCode binary file format support for LabelBMFont.
[Android] [Android]
[NEW] build/android-build.sh: add supporting to generate .apk file [NEW] build/android-build.sh: add supporting to generate .apk file
[FIX] XMLHttpRequest receives wrong binary array. [FIX] XMLHttpRequest receives wrong binary array.
@ -27,6 +30,7 @@ cocos2d-x-3.0beta0 ?? 2013
[Bindings] [Bindings]
[FIX] Don't bind override functions for JSB and LuaBining since they aren't needed at all. [FIX] Don't bind override functions for JSB and LuaBining since they aren't needed at all.
[NEW] Adds spine JS binding support. [NEW] Adds spine JS binding support.
[FIX] The order of onEnter and onExit is wrong.
cocos2d-x-3.0alpha1 Nov.19 2013 cocos2d-x-3.0alpha1 Nov.19 2013
[all platforms] [all platforms]

View File

@ -269,8 +269,6 @@ endif(BUILD_EDITOR_COCOSBUILDER)
if(BUILD_EDITOR_COCOSTUDIO) if(BUILD_EDITOR_COCOSTUDIO)
# cocostudio # cocostudio
add_subdirectory(cocos/editor-support/cocostudio) add_subdirectory(cocos/editor-support/cocostudio)
# jsoncpp library, cocostuido depends on jsoncpp
add_subdirectory(external/json)
endif(BUILD_EDITOR_COCOSTUDIO) endif(BUILD_EDITOR_COCOSTUDIO)
if(BUILD_LIBS_LUA) if(BUILD_LIBS_LUA)

View File

@ -1 +1 @@
ff210e4a55306fce7f69c41995a746c084b6b074 812ab716d10a52b752f0d15b2393b2b0a7c8e969

View File

@ -1 +1 @@
90bb8f93ddfe16e1337c0e278efe123ca1b92891 b83c3a0fd60d6b1b1a032495615afd77fccd5050

View File

@ -43,7 +43,7 @@ NS_CC_BEGIN;
* Implementation of PointArray * Implementation of PointArray
*/ */
PointArray* PointArray::create(int capacity) PointArray* PointArray::create(ssize_t capacity)
{ {
PointArray* pointArray = new PointArray(); PointArray* pointArray = new PointArray();
if (pointArray) if (pointArray)
@ -63,7 +63,7 @@ PointArray* PointArray::create(int capacity)
} }
bool PointArray::initWithCapacity(int capacity) bool PointArray::initWithCapacity(ssize_t capacity)
{ {
_controlPoints = new vector<Point*>(); _controlPoints = new vector<Point*>();
@ -126,19 +126,19 @@ void PointArray::addControlPoint(Point controlPoint)
_controlPoints->push_back(new Point(controlPoint.x, controlPoint.y)); _controlPoints->push_back(new Point(controlPoint.x, controlPoint.y));
} }
void PointArray::insertControlPoint(Point &controlPoint, int index) void PointArray::insertControlPoint(Point &controlPoint, ssize_t index)
{ {
Point *temp = new Point(controlPoint.x, controlPoint.y); Point *temp = new Point(controlPoint.x, controlPoint.y);
_controlPoints->insert(_controlPoints->begin() + index, temp); _controlPoints->insert(_controlPoints->begin() + index, temp);
} }
Point PointArray::getControlPointAtIndex(int index) Point PointArray::getControlPointAtIndex(ssize_t index)
{ {
index = static_cast<int>(MIN(_controlPoints->size()-1, MAX(index, 0))); index = static_cast<int>(MIN(_controlPoints->size()-1, MAX(index, 0)));
return *(_controlPoints->at(index)); return *(_controlPoints->at(index));
} }
void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index) void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, ssize_t index)
{ {
Point *temp = _controlPoints->at(index); Point *temp = _controlPoints->at(index);
@ -146,7 +146,7 @@ void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index)
temp->y = controlPoint.y; temp->y = controlPoint.y;
} }
void PointArray::removeControlPointAtIndex(int index) void PointArray::removeControlPointAtIndex(ssize_t index)
{ {
vector<Point*>::iterator iter = _controlPoints->begin() + index; vector<Point*>::iterator iter = _controlPoints->begin() + index;
Point* removedPoint = *iter; Point* removedPoint = *iter;
@ -154,9 +154,9 @@ void PointArray::removeControlPointAtIndex(int index)
delete removedPoint; delete removedPoint;
} }
int PointArray::count() const ssize_t PointArray::count() const
{ {
return static_cast<int>(_controlPoints->size()); return _controlPoints->size();
} }
PointArray* PointArray::reverse() const PointArray* PointArray::reverse() const
@ -177,11 +177,11 @@ PointArray* PointArray::reverse() const
void PointArray::reverseInline() void PointArray::reverseInline()
{ {
auto l = _controlPoints->size(); size_t l = _controlPoints->size();
Point *p1 = nullptr; Point *p1 = nullptr;
Point *p2 = nullptr; Point *p2 = nullptr;
int x, y; float x, y;
for (int i = 0; i < l/2; ++i) for (size_t i = 0; i < l/2; ++i)
{ {
p1 = _controlPoints->at(i); p1 = _controlPoints->at(i);
p2 = _controlPoints->at(l-i-1); p2 = _controlPoints->at(l-i-1);
@ -291,7 +291,7 @@ CardinalSplineTo* CardinalSplineTo::clone() const
void CardinalSplineTo::update(float time) void CardinalSplineTo::update(float time)
{ {
int p; ssize_t p;
float lt; float lt;
// eg. // eg.
@ -383,7 +383,7 @@ CardinalSplineBy* CardinalSplineBy::reverse() const
// convert "absolutes" to "diffs" // convert "absolutes" to "diffs"
// //
Point p = copyConfig->getControlPointAtIndex(0); Point p = copyConfig->getControlPointAtIndex(0);
for (unsigned int i = 1; i < copyConfig->count(); ++i) for (ssize_t i = 1; i < copyConfig->count(); ++i)
{ {
Point current = copyConfig->getControlPointAtIndex(i); Point current = copyConfig->getControlPointAtIndex(i);
Point diff = current - p; Point diff = current - p;
@ -405,7 +405,7 @@ CardinalSplineBy* CardinalSplineBy::reverse() const
p = -p; p = -p;
pReverse->insertControlPoint(p, 0); pReverse->insertControlPoint(p, 0);
for (unsigned int i = 1; i < pReverse->count(); ++i) for (ssize_t i = 1; i < pReverse->count(); ++i)
{ {
Point current = pReverse->getControlPointAtIndex(i); Point current = pReverse->getControlPointAtIndex(i);
current = -current; current = -current;
@ -528,7 +528,7 @@ CatmullRomBy* CatmullRomBy::reverse() const
// convert "absolutes" to "diffs" // convert "absolutes" to "diffs"
// //
Point p = copyConfig->getControlPointAtIndex(0); Point p = copyConfig->getControlPointAtIndex(0);
for (unsigned int i = 1; i < copyConfig->count(); ++i) for (ssize_t i = 1; i < copyConfig->count(); ++i)
{ {
Point current = copyConfig->getControlPointAtIndex(i); Point current = copyConfig->getControlPointAtIndex(i);
Point diff = current - p; Point diff = current - p;
@ -550,7 +550,7 @@ CatmullRomBy* CatmullRomBy::reverse() const
p = -p; p = -p;
reverse->insertControlPoint(p, 0); reverse->insertControlPoint(p, 0);
for (unsigned int i = 1; i < reverse->count(); ++i) for (ssize_t i = 1; i < reverse->count(); ++i)
{ {
Point current = reverse->getControlPointAtIndex(i); Point current = reverse->getControlPointAtIndex(i);
current = -current; current = -current;

View File

@ -61,7 +61,7 @@ public:
/** creates and initializes a Points array with capacity /** creates and initializes a Points array with capacity
* @js NA * @js NA
*/ */
static PointArray* create(int capacity); static PointArray* create(ssize_t capacity);
/** /**
* @js NA * @js NA
@ -77,7 +77,7 @@ public:
/** initializes a Catmull Rom config with a capacity hint /** initializes a Catmull Rom config with a capacity hint
* @js NA * @js NA
*/ */
bool initWithCapacity(int capacity); bool initWithCapacity(ssize_t capacity);
/** appends a control point /** appends a control point
* @js NA * @js NA
@ -87,27 +87,27 @@ public:
/** inserts a controlPoint at index /** inserts a controlPoint at index
* @js NA * @js NA
*/ */
void insertControlPoint(Point &controlPoint, int index); void insertControlPoint(Point &controlPoint, ssize_t index);
/** replaces an existing controlPoint at index /** replaces an existing controlPoint at index
* @js NA * @js NA
*/ */
void replaceControlPoint(Point &controlPoint, int index); void replaceControlPoint(Point &controlPoint, ssize_t index);
/** get the value of a controlPoint at a given index /** get the value of a controlPoint at a given index
* @js NA * @js NA
*/ */
Point getControlPointAtIndex(int index); Point getControlPointAtIndex(ssize_t index);
/** deletes a control point at a given index /** deletes a control point at a given index
* @js NA * @js NA
*/ */
void removeControlPointAtIndex(int index); void removeControlPointAtIndex(ssize_t index);
/** returns the number of objects of the control point array /** returns the number of objects of the control point array
* @js NA * @js NA
*/ */
int count() const; ssize_t count() const;
/** returns a new copy of the array reversed. User is responsible for releasing this copy /** returns a new copy of the array reversed. User is responsible for releasing this copy
* @js NA * @js NA

View File

@ -32,7 +32,7 @@ THE SOFTWARE.
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCSpriteFrame.h" #include "CCSpriteFrame.h"
#include "CCAnimation.h" #include "CCAnimation.h"
#include <CCVector.h> #include "CCVector.h"
#include <vector> #include <vector>
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -102,7 +102,8 @@ void AnimationCache::parseVersion1(const ValueMap& animations)
continue; continue;
} }
Vector<AnimationFrame*> frames(static_cast<int>(frameNames.size())); ssize_t frameNameSize = frameNames.size();
Vector<AnimationFrame*> frames(frameNameSize);
for (auto& frameName : frameNames) for (auto& frameName : frameNames)
{ {
@ -118,12 +119,12 @@ void AnimationCache::parseVersion1(const ValueMap& animations)
frames.pushBack(animFrame); frames.pushBack(animFrame);
} }
if ( frames.size() == 0 ) if ( frames.empty() )
{ {
CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", iter->first.c_str()); CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", iter->first.c_str());
continue; continue;
} }
else if ( frames.size() != frameNames.size() ) else if ( frames.size() != frameNameSize )
{ {
CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", iter->first.c_str()); CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", iter->first.c_str());
} }

View File

@ -34,7 +34,7 @@ THE SOFTWARE.
#include "CCDirector.h" #include "CCDirector.h"
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCRenderer.h" #include "CCRenderer.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -151,8 +151,7 @@ void AtlasNode::draw(void)
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
QuadCommand* cmd = QuadCommand::getCommandPool().generateCommand(); _quadCommand.init(0,
cmd->init(0,
_vertexZ, _vertexZ,
_textureAtlas->getTexture()->getName(), _textureAtlas->getTexture()->getName(),
shader, shader,
@ -161,7 +160,7 @@ void AtlasNode::draw(void)
_textureAtlas->getTotalQuads(), _textureAtlas->getTotalQuads(),
_modelViewTransform); _modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(cmd); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }
@ -263,12 +262,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const
return _textureAtlas; return _textureAtlas;
} }
int AtlasNode::getQuadsToDraw() const ssize_t AtlasNode::getQuadsToDraw() const
{ {
return _quadsToDraw; return _quadsToDraw;
} }
void AtlasNode::setQuadsToDraw(int quadsToDraw) void AtlasNode::setQuadsToDraw(ssize_t quadsToDraw)
{ {
_quadsToDraw = quadsToDraw; _quadsToDraw = quadsToDraw;
} }

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "CCNode.h" #include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "renderer/CCQuadCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -62,8 +63,8 @@ public:
void setTextureAtlas(TextureAtlas* textureAtlas); void setTextureAtlas(TextureAtlas* textureAtlas);
TextureAtlas* getTextureAtlas() const; TextureAtlas* getTextureAtlas() const;
void setQuadsToDraw(int quadsToDraw); void setQuadsToDraw(ssize_t quadsToDraw);
int getQuadsToDraw() const; ssize_t getQuadsToDraw() const;
// Overrides // Overrides
@ -125,11 +126,13 @@ protected:
BlendFunc _blendFunc; BlendFunc _blendFunc;
// quads to draw // quads to draw
int _quadsToDraw; ssize_t _quadsToDraw;
// color uniform // color uniform
GLint _uniformColor; GLint _uniformColor;
// This varible is only used for LabelAtlas FPS display. So plz don't modify its value. // This varible is only used for LabelAtlas FPS display. So plz don't modify its value.
bool _ignoreContentScaleFactor; bool _ignoreContentScaleFactor;
// quad command
QuadCommand _quadCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(AtlasNode); CC_DISALLOW_COPY_AND_ASSIGN(AtlasNode);

View File

@ -209,23 +209,20 @@ void ClippingNode::visit()
Renderer* renderer = Director::getInstance()->getRenderer(); Renderer* renderer = Director::getInstance()->getRenderer();
GroupCommand* groupCommand = GroupCommand::getCommandPool().generateCommand(); _groupCommand.init(0,_vertexZ);
groupCommand->init(0,_vertexZ); renderer->addCommand(&_groupCommand);
renderer->addCommand(groupCommand);
renderer->pushGroup(groupCommand->getRenderQueueID()); renderer->pushGroup(_groupCommand.getRenderQueueID());
CustomCommand* beforeVisitCmd = CustomCommand::getCommandPool().generateCommand(); _beforeVisitCmd.init(0,_vertexZ);
beforeVisitCmd->init(0,_vertexZ); _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this);
beforeVisitCmd->func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); renderer->addCommand(&_beforeVisitCmd);
renderer->addCommand(beforeVisitCmd);
_stencil->visit(); _stencil->visit();
CustomCommand* afterDrawStencilCmd = CustomCommand::getCommandPool().generateCommand(); _afterDrawStencilCmd.init(0,_vertexZ);
afterDrawStencilCmd->init(0,_vertexZ); _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this);
afterDrawStencilCmd->func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd);
renderer->addCommand(afterDrawStencilCmd);
int i = 0; int i = 0;
@ -253,10 +250,9 @@ void ClippingNode::visit()
this->draw(); this->draw();
} }
CustomCommand* afterVisitCmd = CustomCommand::getCommandPool().generateCommand(); _afterVisitCmd.init(0,_vertexZ);
afterVisitCmd->init(0,_vertexZ); _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this);
afterVisitCmd->func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); renderer->addCommand(&_afterVisitCmd);
renderer->addCommand(afterVisitCmd);
renderer->popGroup(); renderer->popGroup();

View File

@ -30,6 +30,8 @@
#include "CCNode.h" #include "CCNode.h"
#include "CCGL.h" #include "CCGL.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -142,6 +144,11 @@ protected:
GLint _mask_layer_le; GLint _mask_layer_le;
GroupCommand _groupCommand;
CustomCommand _beforeVisitCmd;
CustomCommand _afterDrawStencilCmd;
CustomCommand _afterVisitCmd;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode); CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode);
}; };

View File

@ -847,13 +847,10 @@ void Director::resume()
setAnimationInterval(_oldAnimationInterval); setAnimationInterval(_oldAnimationInterval);
if (gettimeofday(_lastUpdate, nullptr) != 0)
{
CCLOG("cocos2d: Director: Error in gettimeofday");
}
_paused = false; _paused = false;
_deltaTime = 0; _deltaTime = 0;
// fix issue #3509, skip one fps to avoid incorrect time calculation.
setNextDeltaTimeZero(true);
} }
// display the FPS using a LabelAtlas // display the FPS using a LabelAtlas

View File

@ -241,10 +241,9 @@ void DrawNode::render()
void DrawNode::draw() void DrawNode::draw()
{ {
CustomCommand* cmd = CustomCommand::getCommandPool().generateCommand(); _customCommand.init(0, _vertexZ);
cmd->init(0, _vertexZ); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this);
cmd->func = CC_CALLBACK_0(DrawNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
Director::getInstance()->getRenderer()->addCommand(cmd);
} }
void DrawNode::onDraw() void DrawNode::onDraw()

View File

@ -32,6 +32,7 @@
#include "CCNode.h" #include "CCNode.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -105,6 +106,7 @@ protected:
V2F_C4B_T2F *_buffer; V2F_C4B_T2F *_buffer;
BlendFunc _blendFunc; BlendFunc _blendFunc;
CustomCommand _customCommand;
bool _dirty; bool _dirty;

View File

@ -475,7 +475,7 @@ void drawCardinalSpline( PointArray *config, float tension, unsigned int segmen
Vertex2F* vertices = new Vertex2F[segments + 1]; Vertex2F* vertices = new Vertex2F[segments + 1];
unsigned int p; ssize_t p;
float lt; float lt;
float deltaT = 1.0f / config->count(); float deltaT = 1.0f / config->count();

View File

@ -97,10 +97,10 @@ static EventListener::ListenerID __getListenerID(Event* event)
return ret; return ret;
} }
EventDispatcher::EventListenerVector::EventListenerVector() EventDispatcher::EventListenerVector::EventListenerVector() :
: _sceneGraphListeners(nullptr) _fixedListeners(nullptr),
, _fixedListeners(nullptr) _sceneGraphListeners(nullptr),
, _gt0Index(0) _gt0Index(0)
{ {
} }
@ -501,11 +501,12 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s
auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
int i = 0; ssize_t i = 0;
// priority < 0 // priority < 0
if (fixedPriorityListeners) if (fixedPriorityListeners)
{ {
for (; !fixedPriorityListeners->empty() && i < listeners->getGt0Index(); ++i) bool isEmpty = fixedPriorityListeners->empty();
for (; !isEmpty && i < listeners->getGt0Index(); ++i)
{ {
auto l = fixedPriorityListeners->at(i); auto l = fixedPriorityListeners->at(i);
if (!l->isPaused() && l->isRegistered() && onEvent(l)) if (!l->isPaused() && l->isRegistered() && onEvent(l))
@ -537,7 +538,8 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s
if (!shouldStopPropagation) if (!shouldStopPropagation)
{ {
// priority > 0 // priority > 0
for (; i < fixedPriorityListeners->size(); ++i) ssize_t size = fixedPriorityListeners->size();
for (; i < size; ++i)
{ {
auto l = fixedPriorityListeners->at(i); auto l = fixedPriorityListeners->at(i);

View File

@ -67,8 +67,8 @@ EventListenerMouse* EventListenerMouse::clone()
} }
EventListenerMouse::EventListenerMouse() EventListenerMouse::EventListenerMouse()
: onMouseUp(nullptr) : onMouseDown(nullptr)
, onMouseDown(nullptr) , onMouseUp(nullptr)
, onMouseMove(nullptr) , onMouseMove(nullptr)
, onMouseScroll(nullptr) , onMouseScroll(nullptr)
{ {

View File

@ -102,16 +102,20 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li
Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader)
: _reusedLetter(nullptr) : _reusedLetter(nullptr)
, _multilineEnable(true)
, _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false) , _lineBreakWithoutSpaces(false)
,_multilineEnable(true) , _width(0.0f)
, _alignment(alignment) , _alignment(alignment)
, _currentUTF16String(0) , _currentUTF16String(0)
, _originalUTF16String(0) , _originalUTF16String(0)
, _advances(0) , _advances(nullptr)
, _fontAtlas(atlas) , _fontAtlas(atlas)
, _isOpacityModifyRGB(true) , _isOpacityModifyRGB(true)
,_useDistanceField(useDistanceField) , _useDistanceField(useDistanceField)
,_useA8Shader(useA8Shader) , _useA8Shader(useA8Shader)
, _fontSize(0)
, _uniformEffectColor(0)
{ {
} }

View File

@ -113,7 +113,7 @@ bool LabelAtlas::initWithString(const std::string& theString, const std::string&
//CCLabelAtlas - Atlas generation //CCLabelAtlas - Atlas generation
void LabelAtlas::updateAtlasValues() void LabelAtlas::updateAtlasValues()
{ {
auto n = _string.length(); ssize_t n = _string.length();
const unsigned char *s = (unsigned char*)_string.c_str(); const unsigned char *s = (unsigned char*)_string.c_str();
@ -130,7 +130,7 @@ void LabelAtlas::updateAtlasValues()
CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length");
V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads(); V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads();
for(int i = 0; i < n; i++) { for(ssize_t i = 0; i < n; i++) {
unsigned char a = s[i] - _mapStartChar; unsigned char a = s[i] - _mapStartChar;
float row = (float) (a % _itemsPerRow); float row = (float) (a % _itemsPerRow);
@ -178,7 +178,7 @@ void LabelAtlas::updateAtlasValues()
} }
if (n > 0 ){ if (n > 0 ){
_textureAtlas->setDirty(true); _textureAtlas->setDirty(true);
auto totalQuads = _textureAtlas->getTotalQuads(); ssize_t totalQuads = _textureAtlas->getTotalQuads();
if (n > totalQuads) { if (n > totalQuads) {
_textureAtlas->increaseTotalQuadsWith(static_cast<int>(n - totalQuads)); _textureAtlas->increaseTotalQuadsWith(static_cast<int>(n - totalQuads));
} }
@ -188,10 +188,10 @@ void LabelAtlas::updateAtlasValues()
//CCLabelAtlas - LabelProtocol //CCLabelAtlas - LabelProtocol
void LabelAtlas::setString(const std::string &label) void LabelAtlas::setString(const std::string &label)
{ {
auto len = label.size(); ssize_t len = label.size();
if (len > _textureAtlas->getTotalQuads()) if (len > _textureAtlas->getTotalQuads())
{ {
_textureAtlas->resizeCapacity(static_cast<int>(len)); _textureAtlas->resizeCapacity(len);
} }
_string.clear(); _string.clear();
_string = label; _string = label;
@ -201,7 +201,7 @@ void LabelAtlas::setString(const std::string &label)
this->setContentSize(s); this->setContentSize(s);
_quadsToDraw = static_cast<int>(len); _quadsToDraw = len;
} }
const std::string& LabelAtlas::getString(void) const const std::string& LabelAtlas::getString(void) const

View File

@ -184,9 +184,15 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string
{ {
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile); std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile);
std::string contents = FileUtils::getInstance()->getStringFromFile(fullpath); Data data = FileUtils::getInstance()->getDataFromFile(fullpath);
CCASSERT((!data.isNull() && data.getSize() > 0), "CCBMFontConfiguration::parseConfigFile | Open file error.");
CCASSERT(!contents.empty(), "CCBMFontConfiguration::parseConfigFile | Open file error."); if (memcmp("BMF", data.getBytes(), 3) == 0) {
std::set<unsigned int>* ret = parseBinaryConfigFile(data.getBytes(), data.getSize(), controlFile);
return ret;
}
std::string contents((const char*)data.getBytes(), data.getSize());
std::set<unsigned int> *validCharsString = new std::set<unsigned int>(); std::set<unsigned int> *validCharsString = new std::set<unsigned int>();
@ -260,6 +266,167 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string
return validCharsString; return validCharsString;
} }
std::set<unsigned int>* CCBMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile)
{
/* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */
set<unsigned int> *validCharsString = new set<unsigned int>();
unsigned long remains = size;
unsigned char version = pData[3];
CCASSERT(version == 3, "Only version 3 is supported");
pData += 4; remains -= 4;
while (remains > 0)
{
unsigned char blockId = pData[0]; pData += 1; remains -= 1;
uint32_t blockSize = 0; memcpy(&blockSize, pData, 4);
pData += 4; remains -= 4;
if (blockId == 1)
{
/*
fontSize 2 int 0
bitField 1 bits 2 bit 0: smooth, bit 1: unicode, bit 2: italic, bit 3: bold, bit 4: fixedHeigth, bits 5-7: reserved
charSet 1 uint 3
stretchH 2 uint 4
aa 1 uint 6
paddingUp 1 uint 7
paddingRight 1 uint 8
paddingDown 1 uint 9
paddingLeft 1 uint 10
spacingHoriz 1 uint 11
spacingVert 1 uint 12
outline 1 uint 13 added with version 2
fontName n+1 string 14 null terminated string with length n
*/
_padding.top = (unsigned char)pData[7];
_padding.right = (unsigned char)pData[8];
_padding.bottom = (unsigned char)pData[9];
_padding.left = (unsigned char)pData[10];
}
else if (blockId == 2)
{
/*
lineHeight 2 uint 0
base 2 uint 2
scaleW 2 uint 4
scaleH 2 uint 6
pages 2 uint 8
bitField 1 bits 10 bits 0-6: reserved, bit 7: packed
alphaChnl 1 uint 11
redChnl 1 uint 12
greenChnl 1 uint 13
blueChnl 1 uint 14
*/
uint16_t lineHeight = 0; memcpy(&lineHeight, pData, 2);
_commonHeight = lineHeight;
uint16_t scaleW = 0; memcpy(&scaleW, pData + 4, 2);
uint16_t scaleH = 0; memcpy(&scaleH, pData + 6, 2);
CCASSERT(scaleW <= Configuration::getInstance()->getMaxTextureSize() && scaleH <= Configuration::getInstance()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
uint16_t pages = 0; memcpy(&pages, pData + 8, 2);
CCASSERT(pages == 1, "CCBitfontAtlas: only supports 1 page");
}
else if (blockId == 3)
{
/*
pageNames p*(n+1) strings 0 p null terminated strings, each with length n
*/
const char *value = (const char *)pData;
size_t len = strlen(value);
CCASSERT(len < blockSize, "Block size should be less then string");
_atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile);
}
else if (blockId == 4)
{
/*
id 4 uint 0+c*20 These fields are repeated until all characters have been described
x 2 uint 4+c*20
y 2 uint 6+c*20
width 2 uint 8+c*20
height 2 uint 10+c*20
xoffset 2 int 12+c*20
yoffset 2 int 14+c*20
xadvance 2 int 16+c*20
page 1 uint 18+c*20
chnl 1 uint 19+c*20
*/
unsigned long count = blockSize / 20;
for (unsigned long i = 0; i < count; i++)
{
tFontDefHashElement* element = (tFontDefHashElement*)malloc( sizeof(*element) );
uint32_t charId = 0; memcpy(&charId, pData + (i * 20), 4);
element->fontDef.charID = charId;
uint16_t charX = 0; memcpy(&charX, pData + (i * 20) + 4, 2);
element->fontDef.rect.origin.x = charX;
uint16_t charY = 0; memcpy(&charY, pData + (i * 20) + 6, 2);
element->fontDef.rect.origin.y = charY;
uint16_t charWidth = 0; memcpy(&charWidth, pData + (i * 20) + 8, 2);
element->fontDef.rect.size.width = charWidth;
uint16_t charHeight = 0; memcpy(&charHeight, pData + (i * 20) + 10, 2);
element->fontDef.rect.size.height = charHeight;
int16_t xoffset = 0; memcpy(&xoffset, pData + (i * 20) + 12, 2);
element->fontDef.xOffset = xoffset;
int16_t yoffset = 0; memcpy(&yoffset, pData + (i * 20) + 14, 2);
element->fontDef.yOffset = yoffset;
int16_t xadvance = 0; memcpy(&xadvance, pData + (i * 20) + 16, 2);
element->fontDef.xAdvance = xadvance;
element->key = element->fontDef.charID;
HASH_ADD_INT(_fontDefDictionary, key, element);
validCharsString->insert(element->fontDef.charID);
}
}
else if (blockId == 5) {
/*
first 4 uint 0+c*10 These fields are repeated until all kerning pairs have been described
second 4 uint 4+c*10
amount 2 int 8+c*10
*/
unsigned long count = blockSize / 20;
for (unsigned long i = 0; i < count; i++)
{
uint32_t first = 0; memcpy(&first, pData + (i * 10), 4);
uint32_t second = 0; memcpy(&second, pData + (i * 10) + 4, 4);
int16_t amount = 0; memcpy(&amount, pData + (i * 10) + 8, 2);
tKerningHashElement *element = (tKerningHashElement *)calloc( sizeof( *element ), 1 );
element->amount = amount;
element->key = (first<<16) | (second&0xffff);
HASH_ADD_INT(_kerningDictionary,key, element);
}
}
pData += blockSize; remains -= blockSize;
}
return validCharsString;
}
void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile) void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile)
{ {
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -947,7 +1114,7 @@ void LabelBMFont::updateLabel()
size_t size = multiline_string.size(); size_t size = multiline_string.size();
unsigned short* str_new = new unsigned short[size + 1]; unsigned short* str_new = new unsigned short[size + 1];
for (int j = 0; j < size; ++j) for (size_t j = 0; j < size; ++j)
{ {
str_new[j] = multiline_string[j]; str_new[j] = multiline_string[j];
} }

View File

@ -151,6 +151,7 @@ public:
std::set<unsigned int>* getCharacterSet() const; std::set<unsigned int>* getCharacterSet() const;
private: private:
std::set<unsigned int>* parseConfigFile(const std::string& controlFile); std::set<unsigned int>* parseConfigFile(const std::string& controlFile);
std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile);
void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition);
void parseInfoArguments(std::string line); void parseInfoArguments(std::string line);
void parseCommonArguments(std::string line); void parseCommonArguments(std::string line);

View File

@ -200,7 +200,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
size_t size = multiline_string.size(); size_t size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1]; unsigned short* strNew = new unsigned short[size + 1];
for (int j = 0; j < size; ++j) for (size_t j = 0; j < size; ++j)
{ {
strNew[j] = multiline_string[j]; strNew[j] = multiline_string[j];
} }

View File

@ -53,11 +53,11 @@ Layer::Layer()
: _touchEnabled(false) : _touchEnabled(false)
, _accelerometerEnabled(false) , _accelerometerEnabled(false)
, _keyboardEnabled(false) , _keyboardEnabled(false)
, _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
, _touchListener(nullptr) , _touchListener(nullptr)
, _keyboardListener(nullptr) , _keyboardListener(nullptr)
, _accelerationListener(nullptr) , _accelerationListener(nullptr)
, _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
{ {
_ignoreAnchorPointForPosition = true; _ignoreAnchorPointForPosition = true;
setAnchorPoint(Point(0.5f, 0.5f)); setAnchorPoint(Point(0.5f, 0.5f));
@ -564,10 +564,9 @@ void LayerColor::updateColor()
void LayerColor::draw() void LayerColor::draw()
{ {
CustomCommand* cmd = CustomCommand::getCommandPool().generateCommand(); _customCommand.init(0, _vertexZ);
cmd->init(0, _vertexZ); _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this);
cmd->func = CC_CALLBACK_0(LayerColor::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
Director::getInstance()->getRenderer()->addCommand(cmd);
} }
void LayerColor::onDraw() void LayerColor::onDraw()

View File

@ -35,6 +35,7 @@ THE SOFTWARE.
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
#include "CCEventKeyboard.h" #include "CCEventKeyboard.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -296,6 +297,7 @@ protected:
BlendFunc _blendFunc; BlendFunc _blendFunc;
Vertex2F _squareVertices[4]; Vertex2F _squareVertices[4];
Color4F _squareColors[4]; Color4F _squareColors[4];
CustomCommand _customCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(LayerColor); CC_DISALLOW_COPY_AND_ASSIGN(LayerColor);

View File

@ -346,7 +346,7 @@ void Menu::alignItemsInColumns(int columns, va_list args)
void Menu::alignItemsInColumnsWithArray(const ValueVector& rows) void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
{ {
int height = -5; int height = -5;
int row = 0; size_t row = 0;
int rowHeight = 0; int rowHeight = 0;
int columnsOccupied = 0; int columnsOccupied = 0;
int rowColumns = 0; int rowColumns = 0;
@ -441,7 +441,7 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
int width = -10; int width = -10;
int columnHeight = -5; int columnHeight = -5;
int column = 0; size_t column = 0;
int columnWidth = 0; int columnWidth = 0;
int rowsOccupied = 0; int rowsOccupied = 0;
int columnRows; int columnRows;

View File

@ -358,10 +358,9 @@ void MotionStreak::draw()
if(_nuPoints <= 1) if(_nuPoints <= 1)
return; return;
kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV); kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV);
CustomCommand* cmd = CustomCommand::getCommandPool().generateCommand(); _customCommand.init(0,_vertexZ);
cmd->init(0,_vertexZ); _customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this);
cmd->func = CC_CALLBACK_0(MotionStreak::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
Director::getInstance()->getRenderer()->addCommand(cmd);
} }

View File

@ -29,6 +29,7 @@ THE SOFTWARE.
#include "CCTexture2D.h" #include "CCTexture2D.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "CCNode.h" #include "CCNode.h"
#include "renderer/CCCustomCommand.h"
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
#include "CCGLBufferedNode.h" #include "CCGLBufferedNode.h"
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
@ -145,6 +146,8 @@ protected:
GLubyte* _colorPointer; GLubyte* _colorPointer;
Tex2F* _texCoords; Tex2F* _texCoords;
CustomCommand _customCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(MotionStreak); CC_DISALLOW_COPY_AND_ASSIGN(MotionStreak);
}; };

View File

@ -44,7 +44,7 @@ THE SOFTWARE.
#include "CCEventTouch.h" #include "CCEventTouch.h"
#include "CCScene.h" #include "CCScene.h"
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
#include "CCPhysicsBody.h" #include "CCPhysicsBody.h"
#endif #endif
@ -123,7 +123,7 @@ Node::Node(void)
, _isTransitionFinished(false) , _isTransitionFinished(false)
, _updateScriptHandler(0) , _updateScriptHandler(0)
, _componentContainer(nullptr) , _componentContainer(nullptr)
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
, _physicsBody(nullptr) , _physicsBody(nullptr)
#endif #endif
, _displayedOpacity(255) , _displayedOpacity(255)
@ -178,7 +178,7 @@ Node::~Node()
CC_SAFE_DELETE(_componentContainer); CC_SAFE_DELETE(_componentContainer);
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
CC_SAFE_RELEASE(_physicsBody); CC_SAFE_RELEASE(_physicsBody);
#endif #endif
} }
@ -264,7 +264,7 @@ void Node::setRotation(float newRotation)
_rotationX = _rotationY = newRotation; _rotationX = _rotationY = newRotation;
_transformDirty = _inverseDirty = true; _transformDirty = _inverseDirty = true;
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
if (_physicsBody) if (_physicsBody)
{ {
_physicsBody->setRotation(newRotation); _physicsBody->setRotation(newRotation);
@ -354,7 +354,7 @@ void Node::setPosition(const Point& newPosition)
_position = newPosition; _position = newPosition;
_transformDirty = _inverseDirty = true; _transformDirty = _inverseDirty = true;
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
if (_physicsBody) if (_physicsBody)
{ {
_physicsBody->setPosition(newPosition); _physicsBody->setPosition(newPosition);
@ -604,7 +604,7 @@ void Node::addChild(Node *child, int zOrder, int tag)
this->insertChild(child, zOrder); this->insertChild(child, zOrder);
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
for (Node* node = this->getParent(); node != nullptr; node = node->getParent()) for (Node* node = this->getParent(); node != nullptr; node = node->getParent())
{ {
if (dynamic_cast<Scene*>(node) != nullptr) if (dynamic_cast<Scene*>(node) != nullptr)
@ -739,7 +739,7 @@ void Node::detachChild(Node *child, ssize_t childIndex, bool doCleanup)
child->onExit(); child->onExit();
} }
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
if (child->_physicsBody != nullptr) if (child->_physicsBody != nullptr)
{ {
child->_physicsBody->removeFromWorld(); child->_physicsBody->removeFromWorld();
@ -848,7 +848,7 @@ void Node::transformAncestors()
void Node::transform() void Node::transform()
{ {
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
updatePhysicsTransform(); updatePhysicsTransform();
#endif #endif
@ -867,13 +867,6 @@ void Node::onEnter()
{ {
_isTransitionFinished = false; _isTransitionFinished = false;
for( const auto &child: _children)
child->onEnter();
this->resume();
_running = true;
if (_scriptType != kScriptTypeNone) if (_scriptType != kScriptTypeNone)
{ {
int action = kNodeOnEnter; int action = kNodeOnEnter;
@ -881,15 +874,19 @@ void Node::onEnter()
ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEvent scriptEvent(kNodeEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
} }
for( const auto &child: _children)
child->onEnter();
this->resume();
_running = true;
} }
void Node::onEnterTransitionDidFinish() void Node::onEnterTransitionDidFinish()
{ {
_isTransitionFinished = true; _isTransitionFinished = true;
for( const auto &child: _children)
child->onEnterTransitionDidFinish();
if (_scriptType != kScriptTypeNone) if (_scriptType != kScriptTypeNone)
{ {
int action = kNodeOnEnterTransitionDidFinish; int action = kNodeOnEnterTransitionDidFinish;
@ -897,6 +894,9 @@ void Node::onEnterTransitionDidFinish()
ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEvent scriptEvent(kNodeEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
} }
for( const auto &child: _children)
child->onEnterTransitionDidFinish();
} }
void Node::onExitTransitionDidStart() void Node::onExitTransitionDidStart()
@ -918,6 +918,10 @@ void Node::onExit()
this->pause(); this->pause();
_running = false; _running = false;
for( const auto &child: _children)
child->onExit();
if (_scriptType != kScriptTypeNone) if (_scriptType != kScriptTypeNone)
{ {
int action = kNodeOnExit; int action = kNodeOnExit;
@ -925,9 +929,6 @@ void Node::onExit()
ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEvent scriptEvent(kNodeEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
} }
for( const auto &child: _children)
child->onExit();
} }
void Node::setEventDispatcher(EventDispatcher* dispatcher) void Node::setEventDispatcher(EventDispatcher* dispatcher)
@ -1170,8 +1171,8 @@ const kmMat4& Node::getNodeToParentTransform() const
// If skew is needed, apply skew and then anchor point // If skew is needed, apply skew and then anchor point
if (needsSkewMatrix) if (needsSkewMatrix)
{ {
kmMat4 skewMatrix = { 1, tanf(CC_DEGREES_TO_RADIANS(_skewY)), 0, 0, kmMat4 skewMatrix = { 1, (float)tanf(CC_DEGREES_TO_RADIANS(_skewY)), 0, 0,
tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1, 0, 0, (float)tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 1}; 0, 0, 0, 1};
@ -1324,7 +1325,7 @@ Point Node::convertTouchToNodeSpaceAR(Touch *touch) const
return this->convertToNodeSpaceAR(point); return this->convertToNodeSpaceAR(point);
} }
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
bool Node::updatePhysicsTransform() bool Node::updatePhysicsTransform()
{ {
if (_physicsBody != nullptr && _physicsBody->getWorld() != nullptr && !_physicsBody->isResting()) if (_physicsBody != nullptr && _physicsBody->getWorld() != nullptr && !_physicsBody->isResting())
@ -1374,7 +1375,7 @@ void Node::removeAllComponents()
_componentContainer->removeAll(); _componentContainer->removeAll();
} }
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
void Node::setPhysicsBody(PhysicsBody* body) void Node::setPhysicsBody(PhysicsBody* body)
{ {
if (_physicsBody != nullptr) if (_physicsBody != nullptr)

View File

@ -54,7 +54,7 @@ class Component;
class ComponentContainer; class ComponentContainer;
class EventDispatcher; class EventDispatcher;
class Scene; class Scene;
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
class PhysicsBody; class PhysicsBody;
#endif #endif
@ -590,7 +590,7 @@ public:
* *
* @return a Node object whose tag equals to the input parameter * @return a Node object whose tag equals to the input parameter
*/ */
Node * getChildByTag(int tag); virtual Node * getChildByTag(int tag);
/** /**
* Return an array of children * Return an array of children
* *
@ -615,7 +615,7 @@ public:
* *
* @return The amount of children. * @return The amount of children.
*/ */
ssize_t getChildrenCount() const; virtual ssize_t getChildrenCount() const;
/** /**
* Sets the parent node * Sets the parent node
@ -1341,7 +1341,7 @@ public:
/// @} end of component functions /// @} end of component functions
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
/** /**
* set the PhysicsBody that let the sprite effect with physics * set the PhysicsBody that let the sprite effect with physics
*/ */
@ -1465,7 +1465,7 @@ protected:
ComponentContainer *_componentContainer; ///< Dictionary of components ComponentContainer *_componentContainer; ///< Dictionary of components
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
PhysicsBody* _physicsBody; ///< the physicsBody the node have PhysicsBody* _physicsBody; ///< the physicsBody the node have
#endif #endif

View File

@ -47,8 +47,8 @@ NodeGrid* NodeGrid::create()
} }
NodeGrid::NodeGrid() NodeGrid::NodeGrid()
: _nodeGrid(nullptr) : _gridTarget(nullptr)
, _gridTarget(nullptr) , _nodeGrid(nullptr)
{ {
} }
@ -92,10 +92,9 @@ void NodeGrid::visit()
Renderer* renderer = Director::getInstance()->getRenderer(); Renderer* renderer = Director::getInstance()->getRenderer();
GroupCommand* groupCommand = GroupCommand::getCommandPool().generateCommand(); _groupCommand.init(0,_vertexZ);
groupCommand->init(0,_vertexZ); renderer->addCommand(&_groupCommand);
renderer->addCommand(groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID());
renderer->pushGroup(groupCommand->getRenderQueueID());
kmGLPushMatrix(); kmGLPushMatrix();
Director::Projection beforeProjectionType; Director::Projection beforeProjectionType;
@ -105,10 +104,9 @@ void NodeGrid::visit()
_nodeGrid->set2DProjection(); _nodeGrid->set2DProjection();
} }
CustomCommand* gridBeginCmd = CustomCommand::getCommandPool().generateCommand(); _gridBeginCommand.init(0,_vertexZ);
gridBeginCmd->init(0,_vertexZ); _gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this);
gridBeginCmd->func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this); renderer->addCommand(&_gridBeginCommand);
renderer->addCommand(gridBeginCmd);
this->transform(); this->transform();
@ -154,10 +152,9 @@ void NodeGrid::visit()
director->setProjection(beforeProjectionType); director->setProjection(beforeProjectionType);
} }
CustomCommand* gridEndCmd = CustomCommand::getCommandPool().generateCommand(); _gridEndCommand.init(0,_vertexZ);
gridEndCmd->init(0,_vertexZ); _gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this);
gridEndCmd->func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this); renderer->addCommand(&_gridEndCommand);
renderer->addCommand(gridEndCmd);
renderer->popGroup(); renderer->popGroup();

View File

@ -27,6 +27,8 @@
#include "CCNode.h" #include "CCNode.h"
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -64,6 +66,9 @@ protected:
Node* _gridTarget; Node* _gridTarget;
GridBase* _nodeGrid; GridBase* _nodeGrid;
GroupCommand _groupCommand;
CustomCommand _gridBeginCommand;
CustomCommand _gridEndCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(NodeGrid); CC_DISALLOW_COPY_AND_ASSIGN(NodeGrid);

View File

@ -190,13 +190,7 @@ void NotificationCenter::postNotification(const std::string& name, Object *sende
if (observer->getName() == name && (observer->getSender() == sender || observer->getSender() == nullptr || sender == nullptr)) if (observer->getName() == name && (observer->getSender() == sender || observer->getSender() == nullptr || sender == nullptr))
{ {
if (0 != observer->getHandler()) if (0 == observer->getHandler())
{
BasicScriptData data(this, (void*)name.c_str());
ScriptEvent scriptEvent(kNotificationEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
}
else
{ {
observer->performSelector(sender); observer->performSelector(sender);
} }

View File

@ -42,7 +42,7 @@
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCRenderer.h" #include "CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -392,8 +392,7 @@ void ParticleBatchNode::draw(void)
kmMat4 mv; kmMat4 mv;
kmGLGetMatrix(KM_GL_MODELVIEW, &mv); kmGLGetMatrix(KM_GL_MODELVIEW, &mv);
QuadCommand* cmd = QuadCommand::getCommandPool().generateCommand(); _quadCommand.init(0,
cmd->init(0,
_vertexZ, _vertexZ,
_textureAtlas->getTexture()->getName(), _textureAtlas->getTexture()->getName(),
shader, shader,
@ -401,7 +400,7 @@ void ParticleBatchNode::draw(void)
_textureAtlas->getQuads(), _textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(), _textureAtlas->getTotalQuads(),
mv); mv);
Director::getInstance()->getRenderer()->addCommand(cmd); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
CC_PROFILER_STOP("CCParticleBatchNode - draw"); CC_PROFILER_STOP("CCParticleBatchNode - draw");
} }

View File

@ -31,6 +31,7 @@
#include "CCNode.h" #include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "renderer/CCQuadCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -140,6 +141,8 @@ private:
private: private:
/** the blend function used for drawing the quads */ /** the blend function used for drawing the quads */
BlendFunc _blendFunc; BlendFunc _blendFunc;
// quad command
QuadCommand _quadCommand;
}; };
// end of particle_nodes group // end of particle_nodes group

View File

@ -39,7 +39,7 @@ THE SOFTWARE.
#include "CCEventType.h" #include "CCEventType.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCRenderer.h" #include "CCRenderer.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCCustomCommand.h" #include "CCCustomCommand.h"
// extern // extern
@ -443,9 +443,8 @@ void ParticleSystemQuad::draw()
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
QuadCommand* cmd = QuadCommand::getCommandPool().generateCommand(); _quadCommand.init(0, _vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform);
cmd->init(0, _vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
Director::getInstance()->getRenderer()->addCommand(cmd);
} }
} }

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#define __CC_PARTICLE_SYSTEM_QUAD_H__ #define __CC_PARTICLE_SYSTEM_QUAD_H__
#include "CCParticleSystem.h" #include "CCParticleSystem.h"
#include "renderer/CCQuadCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -151,6 +152,8 @@ protected:
GLuint _buffersVBO[2]; //0: vertex 1: indices GLuint _buffersVBO[2]; //0: vertex 1: indices
kmMat4 _transformMatrix; kmMat4 _transformMatrix;
QuadCommand _quadCommand; // quad command
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleSystemQuad); CC_DISALLOW_COPY_AND_ASSIGN(ParticleSystemQuad);
}; };

View File

@ -532,10 +532,9 @@ void ProgressTimer::draw()
if( ! _vertexData || ! _sprite) if( ! _vertexData || ! _sprite)
return; return;
CustomCommand* cmd = CustomCommand::getCommandPool().generateCommand(); _customCommand.init(0, _vertexZ);
cmd->init(0, _vertexZ); _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this);
cmd->func = CC_CALLBACK_0(ProgressTimer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
Director::getInstance()->getRenderer()->addCommand(cmd);
} }

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#define __MISC_NODE_CCPROGRESS_TIMER_H__ #define __MISC_NODE_CCPROGRESS_TIMER_H__
#include "CCSprite.h" #include "CCSprite.h"
#include "renderer/CCCustomCommand.h"
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
#include "CCGLBufferedNode.h" #include "CCGLBufferedNode.h"
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
@ -144,6 +145,8 @@ protected:
int _vertexDataCount; int _vertexDataCount;
V2F_C4B_T2F *_vertexData; V2F_C4B_T2F *_vertexData;
CustomCommand _customCommand;
bool _reverseDirection; bool _reverseDirection;
private: private:

View File

@ -329,10 +329,9 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep
this->begin(); this->begin();
//clear screen //clear screen
CustomCommand* clearCmd = CustomCommand::getCommandPool().generateCommand(); _beginWithClearCommand.init(0, _vertexZ);
clearCmd->init(0, _vertexZ); _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
clearCmd->func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand);
Director::getInstance()->getRenderer()->addCommand(clearCmd);
} }
//TODO find a better way to clear the screen, there is no need to rebind render buffer there. //TODO find a better way to clear the screen, there is no need to rebind render buffer there.
@ -348,11 +347,10 @@ void RenderTexture::clearDepth(float depthValue)
this->begin(); this->begin();
CustomCommand* cmd = CustomCommand::getCommandPool().generateCommand(); _clearDepthCommand.init(0, _vertexZ);
cmd->init(0, _vertexZ); _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this);
cmd->func = CC_CALLBACK_0(RenderTexture::onClearDepth, this);
Director::getInstance()->getRenderer()->addCommand(cmd); Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand);
this->end(); this->end();
} }
@ -614,10 +612,9 @@ void RenderTexture::draw()
begin(); begin();
//clear screen //clear screen
CustomCommand* clearCmd = CustomCommand::getCommandPool().generateCommand(); _clearCommand.init(0, _vertexZ);
clearCmd->init(0, _vertexZ); _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
clearCmd->func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_clearCommand);
Director::getInstance()->getRenderer()->addCommand(clearCmd);
//! make sure all children are drawn //! make sure all children are drawn
sortAllChildren(); sortAllChildren();
@ -643,28 +640,25 @@ void RenderTexture::begin()
kmGLPushMatrix(); kmGLPushMatrix();
kmGLGetMatrix(KM_GL_MODELVIEW, &_transformMatrix); kmGLGetMatrix(KM_GL_MODELVIEW, &_transformMatrix);
GroupCommand* groupCommand = GroupCommand::getCommandPool().generateCommand(); _groupCommand.init(0, _vertexZ);
groupCommand->init(0, _vertexZ);
Renderer *renderer = Director::getInstance()->getRenderer(); Renderer *renderer = Director::getInstance()->getRenderer();
renderer->addCommand(groupCommand); renderer->addCommand(&_groupCommand);
renderer->pushGroup(groupCommand->getRenderQueueID()); renderer->pushGroup(_groupCommand.getRenderQueueID());
CustomCommand* beginCmd = CustomCommand::getCommandPool().generateCommand(); _beginCommand.init(0, _vertexZ);
beginCmd->init(0, _vertexZ); _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this);
beginCmd->func = CC_CALLBACK_0(RenderTexture::onBegin, this);
Director::getInstance()->getRenderer()->addCommand(beginCmd); Director::getInstance()->getRenderer()->addCommand(&_beginCommand);
} }
void RenderTexture::end() void RenderTexture::end()
{ {
CustomCommand* endCmd = CustomCommand::getCommandPool().generateCommand(); _endCommand.init(0, _vertexZ);
endCmd->init(0, _vertexZ); _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this);
endCmd->func = CC_CALLBACK_0(RenderTexture::onEnd, this);
Renderer *renderer = Director::getInstance()->getRenderer(); Renderer *renderer = Director::getInstance()->getRenderer();
renderer->addCommand(endCmd); renderer->addCommand(&_endCommand);
renderer->popGroup(); renderer->popGroup();
} }

View File

@ -29,6 +29,8 @@ THE SOFTWARE.
#include "CCSprite.h" #include "CCSprite.h"
#include "kazmath/mat4.h" #include "kazmath/mat4.h"
#include "platform/CCImage.h" #include "platform/CCImage.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -187,6 +189,13 @@ protected:
- [[renderTexture sprite] setBlendFunc:(BlendFunc){GL_ONE, GL_ONE_MINUS_SRC_ALPHA}]; - [[renderTexture sprite] setBlendFunc:(BlendFunc){GL_ONE, GL_ONE_MINUS_SRC_ALPHA}];
*/ */
Sprite* _sprite; Sprite* _sprite;
GroupCommand _groupCommand;
CustomCommand _beginWithClearCommand;
CustomCommand _clearDepthCommand;
CustomCommand _clearCommand;
CustomCommand _beginCommand;
CustomCommand _endCommand;
protected: protected:
//renderer caches and callbacks //renderer caches and callbacks
void onBegin(); void onBegin();

View File

@ -34,7 +34,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
Scene::Scene() Scene::Scene()
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
: _physicsWorld(nullptr) : _physicsWorld(nullptr)
#endif #endif
{ {
@ -44,7 +44,7 @@ Scene::Scene()
Scene::~Scene() Scene::~Scene()
{ {
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
CC_SAFE_DELETE(_physicsWorld); CC_SAFE_DELETE(_physicsWorld);
#endif #endif
} }
@ -88,7 +88,22 @@ Scene* Scene::getScene()
return this; return this;
} }
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
void Scene::addChild(Node* child, int zOrder, int tag)
{
Node::addChild(child, zOrder, tag);
addChildToPhysicsWorld(child);
}
void Scene::update(float delta)
{
Node::update(delta);
if (nullptr != _physicsWorld)
{
_physicsWorld->update(delta);
}
}
Scene *Scene::createWithPhysics() Scene *Scene::createWithPhysics()
{ {
Scene *ret = new Scene(); Scene *ret = new Scene();
@ -121,13 +136,6 @@ bool Scene::initWithPhysics()
return ret; return ret;
} }
void Scene::addChild(Node* child, int zOrder, int tag)
{
Node::addChild(child, zOrder, tag);
addChildToPhysicsWorld(child);
}
void Scene::addChildToPhysicsWorld(Node* child) void Scene::addChildToPhysicsWorld(Node* child)
{ {
if (_physicsWorld) if (_physicsWorld)
@ -149,18 +157,6 @@ void Scene::addChildToPhysicsWorld(Node* child)
addToPhysicsWorldFunc(child); addToPhysicsWorldFunc(child);
} }
} }
void Scene::update(float delta)
{
Node::update(delta);
if (nullptr != _physicsWorld)
{
_physicsWorld->update(delta);
}
}
#endif #endif
NS_CC_END NS_CC_END

View File

@ -52,32 +52,13 @@ class CC_DLL Scene : public Node
public: public:
/** creates a new Scene object */ /** creates a new Scene object */
static Scene *create(); static Scene *create();
#ifdef CC_USE_PHYSICS
static Scene *createWithPhysics();
#endif
// Overrides // Overrides
virtual Scene *getScene() override; virtual Scene *getScene() override;
#ifdef CC_USE_PHYSICS
public:
inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; }
using Node::addChild; using Node::addChild;
virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void update(float delta) override;
virtual std::string getDescription() const override; virtual std::string getDescription() const override;
protected:
bool initWithPhysics();
void addChildToPhysicsWorld(Node* child);
PhysicsWorld* _physicsWorld;
#endif // CC_USE_PHYSICS
protected: protected:
Scene(); Scene();
virtual ~Scene(); virtual ~Scene();
@ -88,6 +69,19 @@ protected:
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(Scene); CC_DISALLOW_COPY_AND_ASSIGN(Scene);
#if CC_USE_PHYSICS
public:
virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void update(float delta) override;
inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; }
static Scene *createWithPhysics();
protected:
bool initWithPhysics();
void addChildToPhysicsWorld(Node* child);
PhysicsWorld* _physicsWorld;
#endif // CC_USE_PHYSICS
}; };
// end of scene group // end of scene group

View File

@ -201,7 +201,6 @@ enum ScriptEventType
{ {
kNodeEvent = 0, kNodeEvent = 0,
kMenuClickedEvent, kMenuClickedEvent,
kNotificationEvent,
kCallFuncEvent, kCallFuncEvent,
kScheduleEvent, kScheduleEvent,
kTouchEvent, kTouchEvent,
@ -210,16 +209,6 @@ enum ScriptEventType
kAccelerometerEvent, kAccelerometerEvent,
kControlEvent, kControlEvent,
kCommonEvent, kCommonEvent,
kTableViewEvent,//Now it's only used in LuaBinding
kAssetsManagerEvent,//Now it's only used in Lua Binding
kCocoStudioEventListener,//Now it's only used in Lua Binding
kArmatureWrapper,//Now it's only used in Lua Binding
kEventListenerAcc,//Now it's only used in Lua Binding
kEventListenerKeyboard,//Now it's only used in Lua Binding
kEventListenerTouch,//Now it's only used in Lua Binding
kEventListenerTouches,//Now it's only used in Lua Binding
kEventListenerMouse,//Now it's only used in Lua Binding
kEventListenerCustom,////Now it's only used in Lua Binding
}; };
struct BasicScriptData struct BasicScriptData

View File

@ -45,7 +45,7 @@ THE SOFTWARE.
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "CCRenderer.h" #include "CCRenderer.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCFrustum.h" #include "CCFrustum.h"
// external // external
@ -502,7 +502,7 @@ void Sprite::updateTransform(void)
{ {
CCASSERT(_batchNode, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode"); CCASSERT(_batchNode, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode");
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
if (updatePhysicsTransform()) if (updatePhysicsTransform())
{ {
setDirty(true); setDirty(true);
@ -671,16 +671,11 @@ void Sprite::updateTransform(void)
void Sprite::draw(void) void Sprite::draw(void)
{ {
//TODO implement z order //TODO implement z order
QuadCommand* renderCommand = QuadCommand::getCommandPool().generateCommand(); _quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform);
renderCommand->init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform);
// if(!culling()) // if(culling())
// {
// renderCommand->releaseToCommandPool();
// }
// else
{ {
Director::getInstance()->getRenderer()->addCommand(renderCommand); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }
} }
@ -711,7 +706,7 @@ bool Sprite::culling() const
void Sprite::updateQuadVertices() void Sprite::updateQuadVertices()
{ {
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
updatePhysicsTransform(); updatePhysicsTransform();
setDirty(true); setDirty(true);
#endif #endif

View File

@ -37,6 +37,7 @@ THE SOFTWARE.
#include "CCGLBufferedNode.h" #include "CCGLBufferedNode.h"
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
#include "CCPhysicsBody.h" #include "CCPhysicsBody.h"
#include "renderer/CCQuadCommand.h"
#include "kazmath/kazmath.h" #include "kazmath/kazmath.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -545,6 +546,7 @@ protected:
// //
BlendFunc _blendFunc; /// It's required for TextureProtocol inheritance BlendFunc _blendFunc; /// It's required for TextureProtocol inheritance
Texture2D* _texture; /// Texture2D object that is used to render the sprite Texture2D* _texture; /// Texture2D object that is used to render the sprite
QuadCommand _quadCommand; /// quad command
// //
// Shared data // Shared data

View File

@ -43,7 +43,7 @@ THE SOFTWARE.
#include "CCLayer.h" #include "CCLayer.h"
#include "CCScene.h" #include "CCScene.h"
#include "CCRenderer.h" #include "CCRenderer.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -360,8 +360,7 @@ void SpriteBatchNode::draw()
kmMat4 mv; kmMat4 mv;
kmGLGetMatrix(KM_GL_MODELVIEW, &mv); kmGLGetMatrix(KM_GL_MODELVIEW, &mv);
QuadCommand* cmd = QuadCommand::getCommandPool().generateCommand(); _quadCommand.init(0,
cmd->init(0,
_vertexZ, _vertexZ,
_textureAtlas->getTexture()->getName(), _textureAtlas->getTexture()->getName(),
shader, shader,
@ -369,7 +368,7 @@ void SpriteBatchNode::draw()
_textureAtlas->getQuads(), _textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(), _textureAtlas->getTotalQuads(),
mv); mv);
Director::getInstance()->getRenderer()->addCommand(cmd); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }
void SpriteBatchNode::increaseAtlasCapacity(void) void SpriteBatchNode::increaseAtlasCapacity(void)

View File

@ -34,6 +34,7 @@ THE SOFTWARE.
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCTextureAtlas.h" #include "CCTextureAtlas.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "renderer/CCQuadCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -187,6 +188,7 @@ protected:
TextureAtlas *_textureAtlas; TextureAtlas *_textureAtlas;
BlendFunc _blendFunc; BlendFunc _blendFunc;
QuadCommand _quadCommand; // quad command
// all descendants: children, grand children, etc... // all descendants: children, grand children, etc...
// There is not need to retain/release these objects, since they are already retained by _children // There is not need to retain/release these objects, since they are already retained by _children

View File

@ -209,7 +209,7 @@ void TextFieldTTF::deleteBackward()
} }
// get the delete byte number // get the delete byte number
int deleteLen = 1; // default, erase 1 byte size_t deleteLen = 1; // default, erase 1 byte
while(0x80 == (0xC0 & _inputText.at(len - deleteLen))) while(0x80 == (0xC0 & _inputText.at(len - deleteLen)))
{ {

View File

@ -51,7 +51,7 @@ TextPageDef::~TextPageDef()
{ {
size_t numLines = _lines.size(); size_t numLines = _lines.size();
for( int c = 0; c<numLines; ++c ) for( size_t c = 0; c<numLines; ++c )
{ {
delete _lines[c]; delete _lines[c];
} }

View File

@ -89,7 +89,7 @@ void TextureCache::purgeSharedTextureCache()
std::string TextureCache::getDescription() const std::string TextureCache::getDescription() const
{ {
return StringUtils::format("<TextureCache | Number of textures = %lu>", _textures.size()); return StringUtils::format("<TextureCache | Number of textures = %zd>", _textures.size());
} }
void TextureCache::addImageAsync(const std::string &path, Object *target, SEL_CallFuncO selector) void TextureCache::addImageAsync(const std::string &path, Object *target, SEL_CallFuncO selector)

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "CCActionGrid.h" #include "CCActionGrid.h"
#include "CCActionPageTurn3D.h" #include "CCActionPageTurn3D.h"
#include "CCNodeGrid.h" #include "CCNodeGrid.h"
#include "renderer/CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -78,24 +79,43 @@ void TransitionPageTurn::sceneOrder()
_isInSceneOnTop = _back; _isInSceneOnTop = _back;
} }
void TransitionPageTurn::onEnablePolygonOffset()
{
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
}
void TransitionPageTurn::onDisablePolygonOffset()
{
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0);
}
void TransitionPageTurn::draw() void TransitionPageTurn::draw()
{ {
Scene::draw(); Scene::draw();
if( _isInSceneOnTop ) { if( _isInSceneOnTop ) {
_outSceneProxy->visit(); _outSceneProxy->visit();
glEnable(GL_POLYGON_OFFSET_FILL); _enableOffsetCmd.init(0, _vertexZ);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd);
_inSceneProxy->visit(); _inSceneProxy->visit();
glDisable(GL_POLYGON_OFFSET_FILL); _disableOffsetCmd.init(0, _vertexZ);
glPolygonOffset(0, 0); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd);
} else { } else {
_inSceneProxy->visit(); _inSceneProxy->visit();
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS); _enableOffsetCmd.init(0, _vertexZ);
_enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd);
_outSceneProxy->visit(); _outSceneProxy->visit();
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0); _disableOffsetCmd.init(0, _vertexZ);
_disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd);
} }
} }

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#define __CCPAGE_TURN_TRANSITION_H__ #define __CCPAGE_TURN_TRANSITION_H__
#include "CCTransition.h" #include "CCTransition.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -96,6 +97,12 @@ protected:
bool _back; bool _back;
static float POLYGON_OFFSET_FACTOR; static float POLYGON_OFFSET_FACTOR;
static float POLYGON_OFFSET_UNITS; static float POLYGON_OFFSET_UNITS;
protected:
CustomCommand _enableOffsetCmd;
CustomCommand _disableOffsetCmd;
void onEnablePolygonOffset();
void onDisablePolygonOffset();
}; };
// end of transition group // end of transition group

View File

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

View File

@ -1200,7 +1200,8 @@ bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen)
} }
if (! configuration->supportsNPOT() && if (! configuration->supportsNPOT() &&
(header->width != ccNextPOT(header->width) || header->height != ccNextPOT(header->height))) (static_cast<int>(header->width) != ccNextPOT(header->width)
|| static_cast<int>(header->height) != ccNextPOT(header->height)))
{ {
CCLOG("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height); CCLOG("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height);
return false; return false;

View File

@ -33,6 +33,7 @@
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOG_RENDER_DEBUG(...) #define LOG_RENDER_DEBUG(...)
// #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) // #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
@ -40,6 +41,13 @@
#define LOG_EVENTS_DEBUG(...) #define LOG_EVENTS_DEBUG(...)
// #define LOG_EVENTS_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) // #define LOG_EVENTS_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#else
# define LOGV(...) ((void)0)
#endif
void cocos_android_app_init(struct android_app* app); void cocos_android_app_init(struct android_app* app);
/** /**
@ -454,6 +462,7 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread); LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread);
struct engine* engine = (struct engine*)app->userData; struct engine* engine = (struct engine*)app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
engine->animating = 1; engine->animating = 1;
engine->state.x = AMotionEvent_getX(event, 0); engine->state.x = AMotionEvent_getX(event, 0);
@ -563,6 +572,23 @@ static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) {
isContentRectChanged = true; isContentRectChanged = true;
} }
static void process_input(struct android_app* app, struct android_poll_source* source) {
AInputEvent* event = NULL;
int processed = 0;
while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
LOGV("New input event: type=%d\n", AInputEvent_getType(event));
if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
continue;
}
int32_t handled = 0;
if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
AInputQueue_finishEvent(app->inputQueue, event, handled);
processed = 1;
}
if (processed == 0) {
LOGE("Failure reading next input event: %s\n", strerror(errno));
}
}
/** /**
* This is the main entry point of a native application that is using * 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 * android_native_app_glue. It runs in its own thread, with its own
@ -577,6 +603,7 @@ void android_main(struct android_app* state) {
state->userData = &engine; state->userData = &engine;
state->onAppCmd = engine_handle_cmd; state->onAppCmd = engine_handle_cmd;
state->onInputEvent = engine_handle_input; state->onInputEvent = engine_handle_input;
state->inputPollSource.process = process_input;
engine.app = state; engine.app = state;
// Prepare to monitor accelerometer // Prepare to monitor accelerometer

View File

@ -150,7 +150,7 @@ static Data getData(const std::string& filename, bool forString)
} }
DWORD sizeRead = 0; DWORD sizeRead = 0;
BOOL successed = FALSE; BOOL successed = FALSE;
successed = ::ReadFile(fileHandle, buffer, *size, &sizeRead, NULL); successed = ::ReadFile(fileHandle, buffer, size, &sizeRead, NULL);
::CloseHandle(fileHandle); ::CloseHandle(fileHandle);
if (!successed) if (!successed)
@ -180,22 +180,21 @@ static Data getData(const std::string& filename, bool forString)
return ret; return ret;
} }
std::string FileUtilsAndroid::getStringFromFile(const std::string& filename) std::string FileUtilsWin32::getStringFromFile(const std::string& filename)
{ {
Data data = getData(filename, true); Data data = getData(filename, true);
std::string ret((const char*)data.getBytes()); std::string ret((const char*)data.getBytes());
return ret; return ret;
} }
Data FileUtilsAndroid::getDataFromFile(const std::string& filename) Data FileUtilsWin32::getDataFromFile(const std::string& filename)
{ {
return getData(filename, false); return getData(filename, false);
} }
unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, ssize_t* size) unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const char* mode, ssize_t* size)
{ {
unsigned char * pBuffer = NULL; unsigned char * pBuffer = NULL;
CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters.");
*size = 0; *size = 0;
do do
{ {

View File

@ -58,7 +58,7 @@ protected:
* @return Upon success, a pointer to the data is returned, otherwise NULL. * @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. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/ */
CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const char* filename, const char* mode, ssize_t * size) override; CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
/** /**
* Gets string from a file. * Gets string from a file.

View File

@ -25,13 +25,12 @@
#include "CCCustomCommand.h" #include "CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
RenderCommandPool<CustomCommand> CustomCommand::_commandPool;
CustomCommand::CustomCommand() CustomCommand::CustomCommand()
:RenderCommand() :RenderCommand()
, func(nullptr)
, _viewport(0) , _viewport(0)
, _depth(0) , _depth(0)
, func(nullptr)
{ {
_type = RenderCommand::Type::CUSTOM_COMMAND; _type = RenderCommand::Type::CUSTOM_COMMAND;
} }
@ -66,9 +65,4 @@ void CustomCommand::execute()
} }
} }
void CustomCommand::releaseToCommandPool()
{
getCommandPool().pushBackCommand(this);
}
NS_CC_END NS_CC_END

View File

@ -34,7 +34,10 @@ NS_CC_BEGIN
class CustomCommand : public RenderCommand class CustomCommand : public RenderCommand
{ {
public: public:
static RenderCommandPool<CustomCommand>& getCommandPool() { return _commandPool; } CustomCommand();
~CustomCommand();
public:
void init(int viewport, int32_t depth); void init(int viewport, int32_t depth);
@ -48,18 +51,11 @@ public:
void execute(); void execute();
inline bool isTranslucent() { return true; } inline bool isTranslucent() { return true; }
virtual void releaseToCommandPool() override;
std::function<void()> func; std::function<void()> func;
protected: protected:
CustomCommand();
~CustomCommand();
int _viewport; int _viewport;
int32_t _depth; int32_t _depth;
static RenderCommandPool<CustomCommand> _commandPool;
friend class RenderCommandPool<CustomCommand>;
}; };
NS_CC_END NS_CC_END

View File

@ -28,7 +28,6 @@
#include "CCDirector.h" #include "CCDirector.h"
NS_CC_BEGIN NS_CC_BEGIN
RenderCommandPool<GroupCommand> GroupCommand::_commandPool;
static GroupCommandManager* s_instance; static GroupCommandManager* s_instance;
GroupCommandManager *GroupCommandManager::getInstance() GroupCommandManager *GroupCommandManager::getInstance()
@ -119,10 +118,4 @@ int64_t GroupCommand::generateID()
return _id; return _id;
} }
void GroupCommand::releaseToCommandPool()
{
getCommandPool().pushBackCommand(this);
}
NS_CC_END NS_CC_END

View File

@ -53,7 +53,10 @@ protected:
class GroupCommand : public RenderCommand class GroupCommand : public RenderCommand
{ {
public: public:
static RenderCommandPool<GroupCommand>& getCommandPool() { return _commandPool; } GroupCommand();
~GroupCommand();
public:
void init(int viewport, int32_t depth); void init(int viewport, int32_t depth);
@ -66,18 +69,11 @@ public:
inline bool isTranslucent() {return true;} inline bool isTranslucent() {return true;}
inline int getRenderQueueID() {return _renderQueueID;} inline int getRenderQueueID() {return _renderQueueID;}
virtual void releaseToCommandPool() override;
protected: protected:
GroupCommand();
~GroupCommand();
int _viewport; int _viewport;
int32_t _depth; int32_t _depth;
int _renderQueueID; int _renderQueueID;
static RenderCommandPool<GroupCommand> _commandPool;
friend class RenderCommandPool<GroupCommand>;
}; };
NS_CC_END NS_CC_END

View File

@ -23,11 +23,10 @@
****************************************************************************/ ****************************************************************************/
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
NS_CC_BEGIN NS_CC_BEGIN
RenderCommandPool<QuadCommand> QuadCommand::_commandPool;
QuadCommand::QuadCommand() QuadCommand::QuadCommand()
:RenderCommand() :RenderCommand()
@ -172,9 +171,4 @@ void QuadCommand::useMaterial()
GL::blendFunc(_blendType.src, _blendType.dst); GL::blendFunc(_blendType.src, _blendType.dst);
} }
void QuadCommand::releaseToCommandPool()
{
getCommandPool().pushBackCommand(this);
}
NS_CC_END NS_CC_END

View File

@ -37,7 +37,6 @@ NS_CC_BEGIN
class QuadCommand : public RenderCommand class QuadCommand : public RenderCommand
{ {
public: public:
static RenderCommandPool<QuadCommand>& getCommandPool() { return _commandPool; }
QuadCommand(); QuadCommand();
~QuadCommand(); ~QuadCommand();
@ -69,8 +68,6 @@ public:
inline BlendFunc getBlendType() const { return _blendType; } inline BlendFunc getBlendType() const { return _blendType; }
virtual void releaseToCommandPool() override;
protected: protected:
int32_t _materialID; int32_t _materialID;
@ -91,12 +88,7 @@ protected:
V3F_C4B_T2F_Quad* _quad; V3F_C4B_T2F_Quad* _quad;
ssize_t _quadCount; ssize_t _quadCount;
ssize_t _capacity; ssize_t _capacity;
friend class RenderCommandPool<QuadCommand>;
static RenderCommandPool<QuadCommand> _commandPool;
}; };
NS_CC_END NS_CC_END
#endif //_CC_QUADCOMMAND_H_ #endif //_CC_QUADCOMMAND_H_

View File

@ -37,11 +37,11 @@ RenderCommand::~RenderCommand()
{ {
} }
void printBits(size_t const size, void const * const ptr) void printBits(ssize_t const size, void const * const ptr)
{ {
unsigned char *b = (unsigned char*) ptr; unsigned char *b = (unsigned char*) ptr;
unsigned char byte; unsigned char byte;
int i, j; ssize_t i, j;
for (i=size-1;i>=0;i--) for (i=size-1;i>=0;i--)
{ {

View File

@ -52,7 +52,6 @@ public:
virtual inline int64_t getID() { return _id; } virtual inline int64_t getID() { return _id; }
virtual inline Type getType() { return _type; } virtual inline Type getType() { return _type; }
virtual void releaseToCommandPool() =0;
protected: protected:
RenderCommand(); RenderCommand();

View File

@ -26,7 +26,7 @@
#include "CCShaderCache.h" #include "CCShaderCache.h"
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
#include "CCCustomCommand.h" #include "CCCustomCommand.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCGroupCommand.h" #include "CCGroupCommand.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCNotificationCenter.h" #include "CCNotificationCenter.h"
@ -41,9 +41,9 @@ using namespace std;
Renderer::Renderer() Renderer::Renderer()
:_lastMaterialID(0) :_lastMaterialID(0)
,_numQuads(0)
,_firstCommand(0) ,_firstCommand(0)
,_lastCommand(0) ,_lastCommand(0)
,_numQuads(0)
,_glViewAssigned(false) ,_glViewAssigned(false)
{ {
_commandGroupStack.push(DEFAULT_RENDER_QUEUE); _commandGroupStack.push(DEFAULT_RENDER_QUEUE);
@ -296,13 +296,13 @@ void Renderer::render()
} }
} }
//TODO give command back to command pool
for (size_t j = 0 ; j < _renderGroups.size(); j++) for (size_t j = 0 ; j < _renderGroups.size(); j++)
{ {
for (const auto &cmd : _renderGroups[j]) //commands are owned by nodes
{ // for (const auto &cmd : _renderGroups[j])
cmd->releaseToCommandPool(); // {
} // cmd->releaseToCommandPool();
// }
_renderGroups[j].clear(); _renderGroups[j].clear();
} }

View File

@ -39,13 +39,17 @@ _size(0)
CCLOGINFO("In the empty constructor of Data."); CCLOGINFO("In the empty constructor of Data.");
} }
Data::Data(Data&& other) Data::Data(Data&& other) :
_bytes(nullptr),
_size(0)
{ {
CCLOGINFO("In the move constructor of Data."); CCLOGINFO("In the move constructor of Data.");
move(other); move(other);
} }
Data::Data(const Data& other) Data::Data(const Data& other) :
_bytes(nullptr),
_size(0)
{ {
CCLOGINFO("In the copy constructor of Data."); CCLOGINFO("In the copy constructor of Data.");
copy(other._bytes, other._size); copy(other._bytes, other._size);

View File

@ -28,6 +28,7 @@
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
#include <stdint.h> // for ssize_t on android #include <stdint.h> // for ssize_t on android
#include <string> // for ssize_t on linux #include <string> // for ssize_t on linux
#include "CCStdC.h" // for ssize_t on window
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -107,10 +107,22 @@ public:
_data.reserve(capacity); _data.reserve(capacity);
} }
/** Returns capacity of the map */ /** Returns the number of buckets in the Map container. */
ssize_t capacity() const ssize_t bucketCount() const
{ {
return _data.capacity(); return _data.bucket_count();
}
/** Returns the number of elements in bucket n. */
ssize_t bucketSize(ssize_t n) const
{
return _data.bucket_size(n);
}
/** Returns the bucket number where the element with key k is located. */
ssize_t bucket(const K& k) const
{
return _data.bucket(k);
} }
/** The number of elements in the map. */ /** The number of elements in the map. */

View File

@ -34,18 +34,19 @@ NS_CC_BEGIN
typedef std::vector<std::string> strArray; typedef std::vector<std::string> strArray;
// string toolkit // string toolkit
static inline void split(std::string src, const char* token, strArray& vect) static inline void split(const std::string& src, const std::string& token, strArray& vect)
{ {
size_t nend=0; size_t nend = 0;
size_t nbegin=0; size_t nbegin = 0;
while(nend != -1) size_t tokenSize = token.size();
while(nend != std::string::npos)
{ {
nend = src.find(token, nbegin); nend = src.find(token, nbegin);
if(nend == -1) if(nend == std::string::npos)
vect.push_back(src.substr(nbegin, src.length()-nbegin)); vect.push_back(src.substr(nbegin, src.length()-nbegin));
else else
vect.push_back(src.substr(nbegin, nend-nbegin)); vect.push_back(src.substr(nbegin, nend-nbegin));
nbegin = nend + strlen(token); nbegin = nend + tokenSize;
} }
} }
@ -69,7 +70,7 @@ static bool splitWithForm(const std::string& str, strArray& strs)
size_t nPosRight = content.find('}'); size_t nPosRight = content.find('}');
// don't have '{' and '}' // don't have '{' and '}'
CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); CC_BREAK_IF(nPosLeft == std::string::npos || nPosRight == std::string::npos);
// '}' is before '{' // '}' is before '{'
CC_BREAK_IF(nPosLeft > nPosRight); CC_BREAK_IF(nPosLeft > nPosRight);
@ -80,7 +81,7 @@ static bool splitWithForm(const std::string& str, strArray& strs)
size_t nPos1 = pointStr.find('{'); size_t nPos1 = pointStr.find('{');
size_t nPos2 = pointStr.find('}'); size_t nPos2 = pointStr.find('}');
// contain '{' or '}' // contain '{' or '}'
CC_BREAK_IF(nPos1 != (int)std::string::npos || nPos2 != (int)std::string::npos); CC_BREAK_IF(nPos1 != std::string::npos || nPos2 != std::string::npos);
split(pointStr, ",", strs); split(pointStr, ",", strs);
if (strs.size() != 2 || strs[0].length() == 0 || strs[1].length() == 0) if (strs.size() != 2 || strs[0].length() == 0 || strs[1].length() == 0)
@ -111,19 +112,19 @@ Rect RectFromString(const std::string& str)
size_t nPosRight = content.find('}'); size_t nPosRight = content.find('}');
for (int i = 1; i < 3; ++i) for (int i = 1; i < 3; ++i)
{ {
if (nPosRight == (int)std::string::npos) if (nPosRight == std::string::npos)
{ {
break; break;
} }
nPosRight = content.find('}', nPosRight + 1); nPosRight = content.find('}', nPosRight + 1);
} }
CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); CC_BREAK_IF(nPosLeft == std::string::npos || nPosRight == std::string::npos);
content = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); content = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1);
size_t nPointEnd = content.find('}'); size_t nPointEnd = content.find('}');
CC_BREAK_IF(nPointEnd == (int)std::string::npos); CC_BREAK_IF(nPointEnd == std::string::npos);
nPointEnd = content.find(',', nPointEnd); nPointEnd = content.find(',', nPointEnd);
CC_BREAK_IF(nPointEnd == (int)std::string::npos); CC_BREAK_IF(nPointEnd == std::string::npos);
// get the point string and size string // get the point string and size string
std::string pointStr = content.substr(0, nPointEnd); std::string pointStr = content.substr(0, nPointEnd);

View File

@ -6,6 +6,7 @@ LOCAL_MODULE := cocostudio_static
LOCAL_MODULE_FILENAME := libcocostudio LOCAL_MODULE_FILENAME := libcocostudio
LOCAL_SRC_FILES := CCActionFrame.cpp \ LOCAL_SRC_FILES := CCActionFrame.cpp \
CCActionEaseEx.cpp \
CCActionFrameEasing.cpp \ CCActionFrameEasing.cpp \
CCActionManagerEx.cpp \ CCActionManagerEx.cpp \
CCActionNode.cpp \ CCActionNode.cpp \
@ -34,13 +35,13 @@ CCComAudio.cpp \
CCComController.cpp \ CCComController.cpp \
CCComRender.cpp \ CCComRender.cpp \
CCInputDelegate.cpp \ CCInputDelegate.cpp \
CSContentJsonDictionary.cpp \
DictionaryHelper.cpp \ DictionaryHelper.cpp \
CCSGUIReader.cpp \ CCSGUIReader.cpp \
CCSSceneReader.cpp \ CCSSceneReader.cpp \
../../../external/json/json_reader.cpp \ ObjectFactory.cpp \
../../../external/json/json_value.cpp \ TriggerBase.cpp \
../../../external/json/json_writer.cpp TriggerMng.cpp \
TriggerObj.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \
$(LOCAL_PATH)/../../../external $(LOCAL_PATH)/../../../external

View File

@ -0,0 +1,748 @@
/****************************************************************************
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 "CCActionEaseEx.h"
using namespace cocos2d;
namespace cocostudio {
static inline float bezieratFunction( float a, float b, float c, float d, float t )
{
return (powf(1-t,3) * a + 3*t*(powf(1-t,2))*b + 3*powf(t,2)*(1-t)*c + powf(t,3)*d );
}
EaseBezierAction* EaseBezierAction::create(cocos2d::ActionInterval* action)
{
EaseBezierAction *ret = new EaseBezierAction();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
void EaseBezierAction::setBezierParamer( float p0, float p1, float p2, float p3)
{
_p0 = p0;
_p1 = p1;
_p2 = p2;
_p3 = p3;
}
EaseBezierAction* EaseBezierAction::clone() const
{
// no copy constructor
auto a = new EaseBezierAction();
a->initWithAction(_inner->clone());
a->setBezierParamer(_p0,_p1,_p2,_p3);
a->autorelease();
return a;
}
void EaseBezierAction::update(float time)
{
_inner->update(bezieratFunction(_p0,_p1,_p2,_p3,time));
}
EaseBezierAction* EaseBezierAction::reverse() const
{
EaseBezierAction* reverseAction = EaseBezierAction::create(_inner->reverse());
reverseAction->setBezierParamer(_p3,_p2,_p1,_p0);
return reverseAction;
}
//
// EaseQuadraticActionIn
//
EaseQuadraticActionIn* EaseQuadraticActionIn::create(ActionInterval* action)
{
EaseQuadraticActionIn *ret = new EaseQuadraticActionIn();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuadraticActionIn* EaseQuadraticActionIn::clone() const
{
// no copy constructor
auto a = new EaseQuadraticActionIn();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuadraticActionIn::update(float time)
{
_inner->update(powf(time,2));
}
EaseQuadraticActionIn* EaseQuadraticActionIn::reverse() const
{
return EaseQuadraticActionIn::create(_inner->reverse());
}
//
// EaseQuadraticActionOut
//
EaseQuadraticActionOut* EaseQuadraticActionOut::create(ActionInterval* action)
{
EaseQuadraticActionOut *ret = new EaseQuadraticActionOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuadraticActionOut* EaseQuadraticActionOut::clone() const
{
// no copy constructor
auto a = new EaseQuadraticActionOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuadraticActionOut::update(float time)
{
_inner->update(-time*(time-2));
}
EaseQuadraticActionOut* EaseQuadraticActionOut::reverse() const
{
return EaseQuadraticActionOut::create(_inner->reverse());
}
//
// EaseQuadraticActionInOut
//
EaseQuadraticActionInOut* EaseQuadraticActionInOut::create(ActionInterval* action)
{
EaseQuadraticActionInOut *ret = new EaseQuadraticActionInOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuadraticActionInOut* EaseQuadraticActionInOut::clone() const
{
// no copy constructor
auto a = new EaseQuadraticActionInOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuadraticActionInOut::update(float time)
{
float resultTime = time;
time = time*0.5f;
if (time < 1)
{
resultTime = time * time * 0.5f;
}
else
{
--time;
resultTime = -0.5f * (time * (time - 2) - 1);
}
_inner->update(resultTime);
}
EaseQuadraticActionInOut* EaseQuadraticActionInOut::reverse() const
{
return EaseQuadraticActionInOut::create(_inner->reverse());
}
//
// EaseQuarticActionIn
//
EaseQuarticActionIn* EaseQuarticActionIn::create(ActionInterval* action)
{
EaseQuarticActionIn *ret = new EaseQuarticActionIn();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuarticActionIn* EaseQuarticActionIn::clone() const
{
// no copy constructor
auto a = new EaseQuarticActionIn();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuarticActionIn::update(float time)
{
_inner->update(powf(time,4.0f));
}
EaseQuarticActionIn* EaseQuarticActionIn::reverse() const
{
return EaseQuarticActionIn::create(_inner->reverse());
}
//
// EaseQuarticActionOut
//
EaseQuarticActionOut* EaseQuarticActionOut::create(ActionInterval* action)
{
EaseQuarticActionOut *ret = new EaseQuarticActionOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuarticActionOut* EaseQuarticActionOut::clone() const
{
// no copy constructor
auto a = new EaseQuarticActionOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuarticActionOut::update(float time)
{
float tempTime = time -1;
_inner->update(1- powf(tempTime,4.0f));
}
EaseQuarticActionOut* EaseQuarticActionOut::reverse() const
{
return EaseQuarticActionOut::create(_inner->reverse());
}
//
// EaseQuarticActionInOut
//
EaseQuarticActionInOut* EaseQuarticActionInOut::create(ActionInterval* action)
{
EaseQuarticActionInOut *ret = new EaseQuarticActionInOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuarticActionInOut* EaseQuarticActionInOut::clone() const
{
// no copy constructor
auto a = new EaseQuarticActionInOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuarticActionInOut::update(float time)
{
float tempTime = time * 0.5f;
if (tempTime < 1)
tempTime = powf(tempTime,4.0f) * 0.5f;
else
{
tempTime -= 2;
tempTime = 1 - powf(tempTime,4.0f)* 0.5f;
}
_inner->update(tempTime);
}
EaseQuarticActionInOut* EaseQuarticActionInOut::reverse() const
{
return EaseQuarticActionInOut::create(_inner->reverse());
}
//
// EaseQuinticActionIn
//
EaseQuinticActionIn* EaseQuinticActionIn::create(ActionInterval* action)
{
EaseQuinticActionIn *ret = new EaseQuinticActionIn();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuinticActionIn* EaseQuinticActionIn::clone() const
{
// no copy constructor
auto a = new EaseQuinticActionIn();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuinticActionIn::update(float time)
{
_inner->update(powf(time,5.0f));
}
EaseQuinticActionIn* EaseQuinticActionIn::reverse() const
{
return EaseQuinticActionIn::create(_inner->reverse());
}
//
// EaseQuinticActionOut
//
EaseQuinticActionOut* EaseQuinticActionOut::create(ActionInterval* action)
{
EaseQuinticActionOut *ret = new EaseQuinticActionOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuinticActionOut* EaseQuinticActionOut::clone() const
{
// no copy constructor
auto a = new EaseQuinticActionOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuinticActionOut::update(float time)
{
float tempTime = time -1;
_inner->update(1 + powf(tempTime,5.0f));
}
EaseQuinticActionOut* EaseQuinticActionOut::reverse() const
{
return EaseQuinticActionOut::create(_inner->reverse());
}
//
// EaseQuinticActionInOut
//
EaseQuinticActionInOut* EaseQuinticActionInOut::create(ActionInterval* action)
{
EaseQuinticActionInOut *ret = new EaseQuinticActionInOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseQuinticActionInOut* EaseQuinticActionInOut::clone() const
{
// no copy constructor
auto a = new EaseQuinticActionInOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseQuinticActionInOut::update(float time)
{
float tempTime = time * 0.5f;
if (tempTime < 1)
tempTime = powf(tempTime,5.0f) * 0.5f;
else
{
tempTime -= 2;
tempTime = 1 + powf(tempTime,5.0f)* 0.5f;
}
_inner->update(tempTime);
}
EaseQuinticActionInOut* EaseQuinticActionInOut::reverse() const
{
return EaseQuinticActionInOut::create(_inner->reverse());
}
//
// EaseCircleActionIn
//
EaseCircleActionIn* EaseCircleActionIn::create(ActionInterval* action)
{
EaseCircleActionIn *ret = new EaseCircleActionIn();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseCircleActionIn* EaseCircleActionIn::clone() const
{
// no copy constructor
auto a = new EaseCircleActionIn();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseCircleActionIn::update(float time)
{
_inner->update(1-sqrt(1-powf(time,2.0f)));
}
EaseCircleActionIn* EaseCircleActionIn::reverse() const
{
return EaseCircleActionIn::create(_inner->reverse());
}
//
// EaseCircleActionOut
//
EaseCircleActionOut* EaseCircleActionOut::create(ActionInterval* action)
{
EaseCircleActionOut *ret = new EaseCircleActionOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseCircleActionOut* EaseCircleActionOut::clone() const
{
// no copy constructor
auto a = new EaseCircleActionOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseCircleActionOut::update(float time)
{
float tempTime = time - 1;
_inner->update(sqrt(1-powf(tempTime,2.0f)));
}
EaseCircleActionOut* EaseCircleActionOut::reverse() const
{
return EaseCircleActionOut::create(_inner->reverse());
}
//
// EaseCircleActionInOut
//
EaseCircleActionInOut* EaseCircleActionInOut::create(ActionInterval* action)
{
EaseCircleActionInOut *ret = new EaseCircleActionInOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseCircleActionInOut* EaseCircleActionInOut::clone() const
{
// no copy constructor
auto a = new EaseCircleActionInOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseCircleActionInOut::update(float time)
{
float tempTime = time * 0.5f;
if (tempTime < 1)
tempTime = (1- sqrt(1 - powf(tempTime,2.0f))) * 0.5f;
else
{
tempTime -= 2;
tempTime = (1+ sqrt(1 - powf(tempTime,2.0f)));
}
_inner->update(time);
}
EaseCircleActionInOut* EaseCircleActionInOut::reverse() const
{
return EaseCircleActionInOut::create(_inner->reverse());
}
//
// EaseCubicActionIn
//
EaseCubicActionIn* EaseCubicActionIn::create(ActionInterval* action)
{
EaseCubicActionIn *ret = new EaseCubicActionIn();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseCubicActionIn* EaseCubicActionIn::clone() const
{
// no copy constructor
auto a = new EaseCubicActionIn();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseCubicActionIn::update(float time)
{
_inner->update(powf(time,3.0f));
}
EaseCubicActionIn* EaseCubicActionIn::reverse() const
{
return EaseCubicActionIn::create(_inner->reverse());
}
//
// EaseCubicActionOut
//
EaseCubicActionOut* EaseCubicActionOut::create(ActionInterval* action)
{
EaseCubicActionOut *ret = new EaseCubicActionOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseCubicActionOut* EaseCubicActionOut::clone() const
{
// no copy constructor
auto a = new EaseCubicActionOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseCubicActionOut::update(float time)
{
_inner->update(1+powf(time,3.0f));
}
EaseCubicActionOut* EaseCubicActionOut::reverse() const
{
return EaseCubicActionOut::create(_inner->reverse());
}
//
// EaseCubicActionInOut
//
EaseCubicActionInOut* EaseCubicActionInOut::create(ActionInterval* action)
{
EaseCubicActionInOut *ret = new EaseCubicActionInOut();
if (ret)
{
if (ret->initWithAction(action))
{
ret->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(ret);
}
}
return ret;
}
EaseCubicActionInOut* EaseCubicActionInOut::clone() const
{
// no copy constructor
auto a = new EaseCubicActionInOut();
a->initWithAction(_inner->clone());
a->autorelease();
return a;
}
void EaseCubicActionInOut::update(float time)
{
float tempTime = time * 0.5f;
if (tempTime < 1)
tempTime = powf(tempTime,3.0f) * 0.5f;
else
{
tempTime -= 2;
tempTime = 1 + powf(tempTime,3.0f)* 0.5f;
}
_inner->update(time);
}
EaseCubicActionInOut* EaseCubicActionInOut::reverse() const
{
return EaseCubicActionInOut::create(_inner->reverse());
}
}

View File

@ -0,0 +1,397 @@
/****************************************************************************
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 __ActionEaseEx_H__
#define __ActionEaseEx_H__
#include "cocos2d.h"
#include "cocostudio/CocoStudio.h"
namespace cocostudio {
/**
@brief Ease Bezier
@ingroup Actions
*/
class EaseBezierAction : public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseBezierAction* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseBezierAction* clone() const override;
virtual EaseBezierAction* reverse() const override;
virtual void setBezierParamer( float p0, float p1, float p2, float p3);
protected:
EaseBezierAction() {}
virtual ~EaseBezierAction() {}
float _p0;
float _p1;
float _p2;
float _p3;
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseBezierAction);
};
/**
@brief Ease Quadratic In
@ingroup Actions
*/
class EaseQuadraticActionIn:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuadraticActionIn* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuadraticActionIn* clone() const override;
virtual EaseQuadraticActionIn* reverse() const override;
protected:
EaseQuadraticActionIn() {}
virtual ~EaseQuadraticActionIn() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuadraticActionIn);
};
/**
@brief Ease Quadratic Out
@ingroup Actions
*/
class EaseQuadraticActionOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuadraticActionOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuadraticActionOut* clone() const override;
virtual EaseQuadraticActionOut* reverse() const override;
protected:
EaseQuadraticActionOut() {}
virtual ~EaseQuadraticActionOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuadraticActionOut);
};
/**
@brief Ease Quadratic InOut
@ingroup Actions
*/
class EaseQuadraticActionInOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuadraticActionInOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuadraticActionInOut* clone() const override;
virtual EaseQuadraticActionInOut* reverse() const override;
protected:
EaseQuadraticActionInOut() {}
virtual ~EaseQuadraticActionInOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuadraticActionInOut);
};
/**
@brief Ease Quartic In
@ingroup Actions
*/
class EaseQuarticActionIn:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuarticActionIn* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuarticActionIn* clone() const override;
virtual EaseQuarticActionIn* reverse() const override;
protected:
EaseQuarticActionIn() {}
virtual ~EaseQuarticActionIn() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuarticActionIn);
};
/**
@brief Ease Quartic Out
@ingroup Actions
*/
class EaseQuarticActionOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuarticActionOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuarticActionOut* clone() const override;
virtual EaseQuarticActionOut* reverse() const override;
protected:
EaseQuarticActionOut() {}
virtual ~EaseQuarticActionOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuarticActionOut);
};
/**
@brief Ease Quartic InOut
@ingroup Actions
*/
class EaseQuarticActionInOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuarticActionInOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuarticActionInOut* clone() const override;
virtual EaseQuarticActionInOut* reverse() const override;
protected:
EaseQuarticActionInOut() {}
virtual ~EaseQuarticActionInOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuarticActionInOut);
};
/**
@brief Ease Quintic In
@ingroup Actions
*/
class EaseQuinticActionIn:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuinticActionIn* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuinticActionIn* clone() const override;
virtual EaseQuinticActionIn* reverse() const override;
protected:
EaseQuinticActionIn() {}
virtual ~EaseQuinticActionIn() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuinticActionIn);
};
/**
@brief Ease Quintic Out
@ingroup Actions
*/
class EaseQuinticActionOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuinticActionOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuinticActionOut* clone() const override;
virtual EaseQuinticActionOut* reverse() const override;
protected:
EaseQuinticActionOut() {}
virtual ~EaseQuinticActionOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuinticActionOut);
};
/**
@brief Ease Quintic InOut
@ingroup Actions
*/
class EaseQuinticActionInOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseQuinticActionInOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseQuinticActionInOut* clone() const override;
virtual EaseQuinticActionInOut* reverse() const override;
protected:
EaseQuinticActionInOut() {}
virtual ~EaseQuinticActionInOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseQuinticActionInOut);
};
/**
@brief Ease Circle In
@ingroup Actions
*/
class EaseCircleActionIn:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseCircleActionIn* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseCircleActionIn* clone() const override;
virtual EaseCircleActionIn* reverse() const override;
protected:
EaseCircleActionIn() {}
virtual ~EaseCircleActionIn() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseCircleActionIn);
};
/**
@brief Ease Circle Out
@ingroup Actions
*/
class EaseCircleActionOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseCircleActionOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseCircleActionOut* clone() const override;
virtual EaseCircleActionOut* reverse() const override;
protected:
EaseCircleActionOut() {}
virtual ~EaseCircleActionOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseCircleActionOut);
};
/**
@brief Ease Circle InOut
@ingroup Actions
*/
class EaseCircleActionInOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseCircleActionInOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseCircleActionInOut* clone() const override;
virtual EaseCircleActionInOut* reverse() const override;
protected:
EaseCircleActionInOut() {}
virtual ~EaseCircleActionInOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseCircleActionInOut);
};
/**
@brief Ease Cubic In
@ingroup Actions
*/
class EaseCubicActionIn:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseCubicActionIn* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseCubicActionIn* clone() const override;
virtual EaseCubicActionIn* reverse() const override;
protected:
EaseCubicActionIn() {}
virtual ~EaseCubicActionIn() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseCubicActionIn);
};
/**
@brief Ease Cubic Out
@ingroup Actions
*/
class EaseCubicActionOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseCubicActionOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseCubicActionOut* clone() const override;
virtual EaseCubicActionOut* reverse() const override;
protected:
EaseCubicActionOut() {}
virtual ~EaseCubicActionOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseCubicActionOut);
};
/**
@brief Ease Cubic InOut
@ingroup Actions
*/
class EaseCubicActionInOut:public cocos2d::ActionEase
{
public:
/** creates the action */
static EaseCubicActionInOut* create(cocos2d::ActionInterval* action);
virtual void update(float time) override;
virtual EaseCubicActionInOut* clone() const override;
virtual EaseCubicActionInOut* reverse() const override;
protected:
EaseCubicActionInOut() {}
virtual ~EaseCubicActionInOut() {}
private:
CC_DISALLOW_COPY_AND_ASSIGN(EaseCubicActionInOut);
};
}
#endif

View File

@ -1,38 +1,39 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCActionFrame.h" #include "CCActionFrame.h"
#include "CCActionEaseEx.h"
using namespace cocos2d; using namespace cocos2d;
namespace cocostudio { namespace cocostudio {
ActionFrame::ActionFrame() ActionFrame::ActionFrame()
: _frameType(0) : _frameType(0)
, _easingType(0)
, _frameIndex(0) , _frameIndex(0)
, _fTime(0.0f) , _fTime(0.0f)
, _easingType(FrameEaseType::LINERAR)
{ {
} }
@ -70,22 +71,163 @@ int ActionFrame::getFrameType()
void ActionFrame::setEasingType(int easingType) void ActionFrame::setEasingType(int easingType)
{ {
_easingType = easingType; _easingType = (FrameEaseType)easingType;
} }
int ActionFrame::getEasingType() int ActionFrame::getEasingType()
{ {
return _easingType; return (int)_easingType;
} }
Action* ActionFrame::getAction(float fDuration) ActionInterval* ActionFrame::getAction(float fDuration)
{ {
log("Need a definition of <getAction> for ActionFrame"); log("Need a definition of <getAction> for ActionFrame");
return NULL; return nullptr;
}
ActionInterval* ActionFrame::getAction(float fDuration,ActionFrame* srcFrame)
{
return this->getAction(fDuration);
}
void ActionFrame::setEasingParameter(std::vector<float>& parameter)
{
_Parameter.clear();
for (size_t i = 0; i<parameter.size(); i++)
{
_Parameter.push_back(parameter[i]);
}
}
ActionInterval* ActionFrame::getEasingAction(ActionInterval* action)
{
if (action == nullptr)
{
return nullptr;
}
switch (_easingType)
{
case FrameEaseType::Custom:
{
EaseBezierAction* cAction = EaseBezierAction::create(action);
cAction->setBezierParamer(_Parameter[0],_Parameter[1],_Parameter[2],_Parameter[3]);
return cAction;
}
break;
case FrameEaseType::LINERAR:
return action;
break;
case FrameEaseType::SINE_EASEIN:
return EaseSineIn::create(action);
break;
case FrameEaseType::SINE_EASEOUT:
return EaseSineOut::create(action);
break;
case FrameEaseType::SINE_EASEINOUT:
return EaseSineInOut::create(action);
break;
case FrameEaseType::QUAD_EASEIN:
return EaseQuadraticActionIn::create(action);
break;
case FrameEaseType::QUAD_EASEOUT:
return EaseQuadraticActionOut::create(action);
break;
case FrameEaseType::QUAD_EASEINOUT:
return EaseQuadraticActionInOut::create(action);
break;
case FrameEaseType::CUBIC_EASEIN:
return EaseCubicActionIn::create(action);
break;
case FrameEaseType::CUBIC_EASEOUT:
return EaseCubicActionOut::create(action);
break;
case FrameEaseType::CUBIC_EASEINOUT:
return EaseCubicActionInOut::create(action);
break;
case FrameEaseType::QUART_EASEIN:
return EaseQuarticActionIn::create(action);
break;
case FrameEaseType::QUART_EASEOUT:
return EaseQuadraticActionOut::create(action);
break;
case FrameEaseType::QUART_EASEINOUT:
return EaseQuarticActionInOut::create(action);
break;
case FrameEaseType::QUINT_EASEIN:
return EaseQuinticActionIn::create(action);
break;
case FrameEaseType::QUINT_EASEOUT:
return EaseQuinticActionOut::create(action);
break;
case FrameEaseType::QUINT_EASEINOUT:
return EaseQuinticActionInOut::create(action);
break;
case FrameEaseType::EXPO_EASEIN:
return EaseExponentialIn::create(action);
break;
case FrameEaseType::EXPO_EASEOUT:
return EaseExponentialOut::create(action);
break;
case FrameEaseType::EXPO_EASEINOUT:
return EaseExponentialInOut::create(action);
break;
case FrameEaseType::CIRC_EASEIN:
return EaseCircleActionIn::create(action);
break;
case FrameEaseType::CIRC_EASEOUT:
return EaseCircleActionOut::create(action);
break;
case FrameEaseType::CIRC_EASEINOUT:
return EaseCircleActionInOut::create(action);
break;
case FrameEaseType::ELASTIC_EASEIN:
{
EaseElasticIn* cAction = EaseElasticIn::create(action);
cAction->setPeriod(_Parameter[0]);
return cAction;
}
break;
case FrameEaseType::ELASTIC_EASEOUT:
{
EaseElasticOut* cAction = EaseElasticOut::create(action);
cAction->setPeriod(_Parameter[0]);
return cAction;
}
break;
case FrameEaseType::ELASTIC_EASEINOUT:
{
EaseElasticInOut* cAction = EaseElasticInOut::create(action);
cAction->setPeriod(_Parameter[0]);
return cAction;
}
break;
case FrameEaseType::BACK_EASEIN:
return EaseBackIn::create(action);
break;
case FrameEaseType::BACK_EASEOUT:
return EaseBackOut::create(action);
break;
case FrameEaseType::BACK_EASEINOUT:
return EaseBackInOut::create(action);
break;
case FrameEaseType::BOUNCE_EASEIN:
return EaseBounceIn::create(action);
break;
case FrameEaseType::BOUNCE_EASEOUT:
return EaseBounceOut::create(action);
break;
case FrameEaseType::BOUNCE_EASEINOUT:
return EaseBounceInOut::create(action);
break;
default:
return action;
break;
}
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
ActionMoveFrame::ActionMoveFrame() ActionMoveFrame::ActionMoveFrame()
: _position(Point(0.0f,0.0f)) : _position(Point(0.0f,0.0f))
{ {
_frameType = (int)kKeyframeMove; _frameType = (int)kKeyframeMove;
} }
@ -101,15 +243,15 @@ Point ActionMoveFrame::getPosition()
{ {
return _position; return _position;
} }
Action* ActionMoveFrame::getAction(float fDuration) ActionInterval* ActionMoveFrame::getAction(float fDuration)
{ {
return MoveTo::create(fDuration,_position); return this->getEasingAction(CCMoveTo::create(fDuration,_position));
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
ActionScaleFrame::ActionScaleFrame() ActionScaleFrame::ActionScaleFrame()
: _scaleX(1.0f) : _scaleX(1.0f)
, _scaleY(1.0f) , _scaleY(1.0f)
{ {
_frameType = (int)kKeyframeScale; _frameType = (int)kKeyframeScale;
} }
@ -139,13 +281,13 @@ float ActionScaleFrame::getScaleY()
return _scaleY; return _scaleY;
} }
Action* ActionScaleFrame::getAction(float fDuration) ActionInterval* ActionScaleFrame::getAction(float fDuration)
{ {
return ScaleTo::create(fDuration,_scaleX,_scaleY); return this->getEasingAction(CCScaleTo::create(fDuration,_scaleX,_scaleY));
} }
ActionRotationFrame::ActionRotationFrame() ActionRotationFrame::ActionRotationFrame()
: _rotation(0.0f) : _rotation(0.0f)
{ {
_frameType = (int)kKeyframeRotate; _frameType = (int)kKeyframeRotate;
} }
@ -165,13 +307,26 @@ float ActionRotationFrame::getRotation()
return _rotation; return _rotation;
} }
Action* ActionRotationFrame::getAction(float fDuration) ActionInterval* ActionRotationFrame::getAction(float fDuration)
{ {
return RotateTo::create(fDuration,_rotation); return this->getEasingAction(CCRotateTo::create(fDuration,_rotation));
}
ActionInterval* ActionRotationFrame::getAction(float fDuration,ActionFrame* srcFrame)
{
ActionRotationFrame* srcRotationFrame = static_cast<ActionRotationFrame*>(srcFrame);
if (srcRotationFrame == nullptr)
{
return this->getAction(fDuration);
}
else
{
float diffRotation = _rotation - srcRotationFrame->_rotation;
return this->getEasingAction(CCRotateBy::create(fDuration,diffRotation));
}
} }
ActionFadeFrame::ActionFadeFrame() ActionFadeFrame::ActionFadeFrame()
: _opacity(255) : _opacity(255)
{ {
_frameType = (int)kKeyframeFade; _frameType = (int)kKeyframeFade;
} }
@ -191,14 +346,14 @@ int ActionFadeFrame::getOpacity()
return _opacity; return _opacity;
} }
Action* ActionFadeFrame::getAction(float fDuration) ActionInterval* ActionFadeFrame::getAction(float fDuration)
{ {
return FadeTo::create(fDuration,_opacity); return this->getEasingAction(CCFadeTo::create(fDuration,_opacity));
} }
ActionTintFrame::ActionTintFrame() ActionTintFrame::ActionTintFrame()
: _color(Color3B(255,255,255)) : _color(Color3B(255,255,255))
{ {
_frameType = (int)kKeyframeTint; _frameType = (int)kKeyframeTint;
} }
@ -218,9 +373,9 @@ Color3B ActionTintFrame::getColor()
return _color; return _color;
} }
Action* ActionTintFrame::getAction(float fDuration) ActionInterval* ActionTintFrame::getAction(float fDuration)
{ {
return TintTo::create(fDuration,_color.r,_color.g,_color.b); return this->getEasingAction(CCTintTo::create(fDuration,_color.r,_color.g,_color.b));
} }

View File

@ -1,26 +1,26 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __ActionFRAME_H__ #ifndef __ActionFRAME_H__
#define __ActionFRAME_H__ #define __ActionFRAME_H__
@ -39,10 +39,58 @@ enum FrameType
kKeyframeMax kKeyframeMax
}; };
enum class FrameEaseType
{
Custom = -1,
LINERAR = 0,
SINE_EASEIN,
SINE_EASEOUT,
SINE_EASEINOUT,
QUAD_EASEIN,
QUAD_EASEOUT,
QUAD_EASEINOUT,
CUBIC_EASEIN,
CUBIC_EASEOUT,
CUBIC_EASEINOUT,
QUART_EASEIN,
QUART_EASEOUT,
QUART_EASEINOUT,
QUINT_EASEIN,
QUINT_EASEOUT,
QUINT_EASEINOUT,
EXPO_EASEIN,
EXPO_EASEOUT,
EXPO_EASEINOUT,
CIRC_EASEIN,
CIRC_EASEOUT,
CIRC_EASEINOUT,
ELASTIC_EASEIN,
ELASTIC_EASEOUT,
ELASTIC_EASEINOUT,
BACK_EASEIN,
BACK_EASEOUT,
BACK_EASEINOUT,
BOUNCE_EASEIN,
BOUNCE_EASEOUT,
BOUNCE_EASEINOUT,
TWEEN_EASING_MAX = 10000
};
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionFrame:public cocos2d::Object class ActionFrame:public cocos2d::Object
{ {
@ -115,24 +163,52 @@ public:
int getEasingType(); int getEasingType();
/** /**
* Gets the CCAction of ActionFrame. * Gets the ActionInterval of ActionFrame.
* *
* @parame fDuration the duration time of ActionFrame * @parame duration the duration time of ActionFrame
* *
* @return CCAction * @return ActionInterval
*/ */
virtual cocos2d::Action* getAction(float fDuration); virtual cocos2d::ActionInterval* getAction(float duration);
/**
* Gets the ActionInterval of ActionFrame.
*
* @parame duration the duration time of ActionFrame
*
* @parame duration the source ActionFrame
*
* @return ActionInterval
*/
virtual cocos2d::ActionInterval* getAction(float duration,ActionFrame* srcFrame);
/**
*Set the ActionInterval easing parameter.
*
*@parame parameter the parameter for frame ease
*
*/
virtual void setEasingParameter(std::vector<float>& parameter);
protected:
/**
* Gets the Easing Action of ActionFrame.
*
* @parame action the duration time of ActionFrame
*
* @return ActionInterval
*/
virtual cocos2d::ActionInterval* getEasingAction(cocos2d::ActionInterval* action);
protected: protected:
int _frameType; int _frameType;
int _easingType;
int _frameIndex; int _frameIndex;
float _fTime; float _fTime;
FrameEaseType _easingType;
std::vector<float> _Parameter;
}; };
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionMoveFrame:public ActionFrame class ActionMoveFrame:public ActionFrame
{ {
public: public:
@ -162,21 +238,21 @@ public:
cocos2d::Point getPosition(); cocos2d::Point getPosition();
/** /**
* Gets the CCAction of ActionFrame. * Gets the ActionInterval of ActionFrame.
* *
* @parame fDuration the duration time of ActionFrame * @parame duration the duration time of ActionFrame
* *
* @return CCAction * @return ActionInterval
*/ */
virtual cocos2d::Action* getAction(float fDuration); virtual cocos2d::ActionInterval* getAction(float duration);
protected: protected:
cocos2d::Point _position; cocos2d::Point _position;
}; };
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionScaleFrame:public ActionFrame class ActionScaleFrame:public ActionFrame
{ {
public: public:
@ -220,21 +296,21 @@ public:
float getScaleY(); float getScaleY();
/** /**
* Gets the CCAction of ActionFrame. * Gets the ActionInterval of ActionFrame.
* *
* @parame fDuration the duration time of ActionFrame * @parame duration the duration time of ActionFrame
* *
* @return CCAction * @return ActionInterval
*/ */
virtual cocos2d::Action* getAction(float fDuration); virtual cocos2d::ActionInterval* getAction(float duration);
protected: protected:
float _scaleX; float _scaleX;
float _scaleY; float _scaleY;
}; };
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionRotationFrame:public ActionFrame class ActionRotationFrame:public ActionFrame
{ {
public: public:
@ -264,20 +340,30 @@ public:
float getRotation(); float getRotation();
/** /**
* Gets the CCAction of ActionFrame. * Gets the ActionInterval of ActionFrame.
* *
* @parame fDuration the duration time of ActionFrame * @parame duration the duration time of ActionFrame
* *
* @return CCAction * @return ActionInterval
*/ */
virtual cocos2d::Action* getAction(float fDuration); virtual cocos2d::ActionInterval* getAction(float duration);
protected: /**
* Gets the ActionInterval of ActionFrame.
*
* @parame duration the duration time of ActionFrame
*
* @parame duration the source ActionFrame
*
* @return ActionInterval
*/
virtual cocos2d::ActionInterval* getAction(float duration,ActionFrame* srcFrame);
public:
float _rotation; float _rotation;
}; };
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionFadeFrame:public ActionFrame class ActionFadeFrame:public ActionFrame
{ {
public: public:
@ -307,20 +393,20 @@ public:
int getOpacity(); int getOpacity();
/** /**
* Gets the CCAction of ActionFrame. * Gets the ActionInterval of ActionFrame.
* *
* @parame fDuration the duration time of ActionFrame * @parame duration the duration time of ActionFrame
* *
* @return CCAction * @return ActionInterval
*/ */
virtual cocos2d::Action* getAction(float fDuration); virtual cocos2d::ActionInterval* getAction(float duration);
protected: protected:
float _opacity; float _opacity;
}; };
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionTintFrame:public ActionFrame class ActionTintFrame:public ActionFrame
{ {
@ -351,13 +437,13 @@ public:
cocos2d::Color3B getColor(); cocos2d::Color3B getColor();
/** /**
* Gets the CCAction of ActionFrame. * Gets the ActionInterval of ActionFrame.
* *
* @parame fDuration the duration time of ActionFrame * @parame duration the duration time of ActionFrame
* *
* @return CCAction * @return ActionInterval
*/ */
virtual cocos2d::Action* getAction(float fDuration); virtual cocos2d::ActionInterval* getAction(float duration);
protected: protected:
cocos2d::Color3B _color; cocos2d::Color3B _color;
}; };

View File

@ -1,26 +1,26 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include <math.h> #include <math.h>
#include "cocostudio/CCActionFrameEasing.h" #include "cocostudio/CCActionFrameEasing.h"

View File

@ -1,32 +1,31 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __ActionFrameEasing_H__ #ifndef __ActionFrameEasing_H__
#define __ActionFrameEasing_H__ #define __ActionFrameEasing_H__
#include "cocos2d.h" #include "cocos2d.h"
#include "cocostudio/CSContentJsonDictionary.h"
namespace cocostudio { namespace cocostudio {
@ -54,9 +53,9 @@ enum FrameEasingType
}; };
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionFrameEasing:public cocos2d::Object class ActionFrameEasing:public cocos2d::Object
{ {
protected: protected:

View File

@ -1,37 +1,37 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocostudio/CCActionManagerEx.h" #include "cocostudio/CCActionManagerEx.h"
#include "cocostudio/DictionaryHelper.h" #include "cocostudio/DictionaryHelper.h"
using namespace cocos2d; using namespace cocos2d;
namespace cocostudio { namespace cocostudio {
static ActionManagerEx* sharedActionManager = NULL; static ActionManagerEx* sharedActionManager = nullptr;
ActionManagerEx* ActionManagerEx::shareManager() ActionManagerEx* ActionManagerEx::getInstance()
{ {
if (!sharedActionManager) { if (!sharedActionManager) {
sharedActionManager = new ActionManagerEx(); sharedActionManager = new ActionManagerEx();
@ -39,60 +39,56 @@ ActionManagerEx* ActionManagerEx::shareManager()
return sharedActionManager; return sharedActionManager;
} }
void ActionManagerEx::purgeActionManager() void ActionManagerEx::destroyInstance()
{ {
CC_SAFE_DELETE(sharedActionManager); CC_SAFE_DELETE(sharedActionManager);
} }
ActionManagerEx::ActionManagerEx() ActionManagerEx::ActionManagerEx()
: _pActionDic(NULL)
{ {
_pActionDic = Dictionary::create();
_pActionDic->retain();
} }
ActionManagerEx::~ActionManagerEx() ActionManagerEx::~ActionManagerEx()
{ {
_pActionDic->removeAllObjects(); _actionDic.clear();
_pActionDic->release();
} }
void ActionManagerEx::initWithDictionary(const char* jsonName,JsonDictionary *dic,Object* root) void ActionManagerEx::initWithDictionary(const char* jsonName,const rapidjson::Value &dic,Object* root)
{ {
std::string path = jsonName; std::string path = jsonName;
int pos = path.find_last_of("/"); ssize_t pos = path.find_last_of("/");
std::string fileName = path.substr(pos+1,path.length()); std::string fileName = path.substr(pos+1,path.length());
CCLOG("filename == %s",fileName.c_str()); CCLOG("filename == %s",fileName.c_str());
Array* actionList = Array::create(); cocos2d::Vector<ActionObject*> actionList;
int actionCount = DICTOOL->getArrayCount_json(dic, "actionlist"); int actionCount = DICTOOL->getArrayCount_json(dic, "actionlist");
for (int i=0; i<actionCount; i++) { for (int i=0; i<actionCount; i++) {
ActionObject* action = new ActionObject(); ActionObject* action = new ActionObject();
action->autorelease(); action->autorelease();
JsonDictionary* actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i); const rapidjson::Value &actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i);
action->initWithDictionary(actionDic,root); action->initWithDictionary(actionDic,root);
actionList->addObject(action); actionList.pushBack(action);
CC_SAFE_DELETE(actionDic);
} }
_pActionDic->setObject(actionList, fileName); _actionDic.insert(std::pair<std::string, cocos2d::Vector<ActionObject*>>(fileName, actionList));
} }
ActionObject* ActionManagerEx::getActionByName(const char* jsonName,const char* actionName) ActionObject* ActionManagerEx::getActionByName(const char* jsonName,const char* actionName)
{ {
Array* actionList = (Array*)(_pActionDic->objectForKey(jsonName)); auto iterator = _actionDic.find(jsonName);
if (!actionList) if (iterator == _actionDic.end())
{ {
return NULL; return nullptr;
} }
for (int i = 0; i < actionList->count(); i++) auto actionList = iterator->second;
for (int i = 0; i < actionList.size(); i++)
{ {
ActionObject* action = dynamic_cast<ActionObject*>(actionList->getObjectAtIndex(i)); ActionObject* action = actionList.at(i);
if (strcmp(actionName, action->getName()) == 0) if (strcmp(actionName, action->getName()) == 0)
{ {
return action; return action;
} }
} }
return NULL; return nullptr;
} }
ActionObject* ActionManagerEx::playActionByName(const char* jsonName,const char* actionName) ActionObject* ActionManagerEx::playActionByName(const char* jsonName,const char* actionName)
@ -105,10 +101,19 @@ ActionObject* ActionManagerEx::playActionByName(const char* jsonName,const char*
return action; return action;
} }
ActionObject* ActionManagerEx::playActionByName(const char* jsonName,const char* actionName, CallFunc* func)
{
ActionObject* action = getActionByName(jsonName,actionName);
if (action)
{
action->play(func);
}
return action;
}
void ActionManagerEx::releaseActions() void ActionManagerEx::releaseActions()
{ {
_pActionDic->removeAllObjects(); _actionDic.clear();
} }
} }

View File

@ -1,33 +1,33 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __ActionMANAGER_H__ #ifndef __ActionMANAGER_H__
#define __ActionMANAGER_H__ #define __ActionMANAGER_H__
#include "cocos2d.h" #include "cocos2d.h"
#include "cocostudio/CCActionObject.h" #include "cocostudio/CCActionObject.h"
#include "cocostudio/CSContentJsonDictionary.h" #include "cocostudio/DictionaryHelper.h"
namespace cocostudio { namespace cocostudio {
@ -53,14 +53,14 @@ public:
* @js getInstance * @js getInstance
* @lua getInstance * @lua getInstance
*/ */
static ActionManagerEx* shareManager(); static ActionManagerEx* getInstance();
/** /**
* Purges ActionManager point. * Purges ActionManager point.
* @js purge * @js purge
* @lua destroyActionManager * @lua destroyActionManager
*/ */
static void purgeActionManager(); static void destroyInstance();
/** /**
* Gets an ActionObject with a name. * Gets an ActionObject with a name.
@ -84,9 +84,19 @@ public:
*/ */
ActionObject* playActionByName(const char* jsonName,const char* actionName); ActionObject* playActionByName(const char* jsonName,const char* actionName);
/*init properties with json dictionay*/ /**
void initWithDictionary(const char* jsonName,JsonDictionary* dic,cocos2d::Object* root); * Play an Action with a name.
*
* @param jsonName UI file name
*
* @param actionName action name in teh UIfile.
*
* @param func ui action call back
*/
ActionObject* playActionByName(const char* jsonName,const char* actionName, cocos2d::CallFunc* func);
/*init properties with json dictionay*/
void initWithDictionary(const char* jsonName,const rapidjson::Value &dic, Object* root);
/** /**
* Release all actions. * Release all actions.
* *
@ -94,7 +104,7 @@ public:
void releaseActions(); void releaseActions();
protected: protected:
cocos2d::Dictionary* _pActionDic; std::unordered_map<std::string, cocos2d::Vector<ActionObject*>> _actionDic;
}; };
} }

View File

@ -38,26 +38,21 @@ ActionNode::ActionNode()
, _destFrameIndex(0) , _destFrameIndex(0)
, _fUnitTime(0.1f) , _fUnitTime(0.1f)
, _actionTag(0) , _actionTag(0)
, _actionSpawn(NULL) , _actionSpawn(nullptr)
, _action(NULL) , _action(nullptr)
, _object(NULL) , _object(nullptr)
, _frameArray(NULL)
, _frameArrayNum(0) , _frameArrayNum(0)
{ {
_frameArray = Array::create();
_frameArray->retain();
_frameArrayNum = (int)kKeyframeMax; _frameArrayNum = (int)kKeyframeMax;
for(int i = 0; i < _frameArrayNum; i++) for(int i = 0; i < _frameArrayNum; i++)
{ {
Array* cArray = Array::create(); _frameArray.push_back( new cocos2d::Vector<ActionFrame*>());
_frameArray->addObject(cArray);
} }
} }
ActionNode::~ActionNode() ActionNode::~ActionNode()
{ {
if (_action == NULL) if (_action == nullptr)
{ {
CC_SAFE_RELEASE_NULL(_actionSpawn); CC_SAFE_RELEASE_NULL(_actionSpawn);
} }
@ -66,20 +61,20 @@ ActionNode::~ActionNode()
CC_SAFE_RELEASE_NULL(_action); CC_SAFE_RELEASE_NULL(_action);
} }
if (_frameArray != NULL) for (auto object : _frameArray)
{ {
_frameArray->removeAllObjects(); object->clear();
CC_SAFE_RELEASE_NULL(_frameArray);
} }
_frameArray.clear();
} }
void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root) void ActionNode::initWithDictionary(const rapidjson::Value& dic,Object* root)
{ {
setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag")); setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag"));
int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist"); int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist");
for (int i=0; i<actionFrameCount; i++) { for (int i=0; i<actionFrameCount; i++) {
JsonDictionary* actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i); const rapidjson::Value& actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i);
int frameInex = DICTOOL->getIntValue_json(actionFrameDic,"frameid"); int frameInex = DICTOOL->getIntValue_json(actionFrameDic,"frameid");
bool existPosition = DICTOOL->checkObjectExist_json(actionFrameDic,"positionx"); bool existPosition = DICTOOL->checkObjectExist_json(actionFrameDic,"positionx");
@ -88,10 +83,11 @@ void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root)
float positionX = DICTOOL->getFloatValue_json(actionFrameDic, "positionx"); float positionX = DICTOOL->getFloatValue_json(actionFrameDic, "positionx");
float positionY = DICTOOL->getFloatValue_json(actionFrameDic, "positiony"); float positionY = DICTOOL->getFloatValue_json(actionFrameDic, "positiony");
ActionMoveFrame* actionFrame = new ActionMoveFrame(); ActionMoveFrame* actionFrame = new ActionMoveFrame();
actionFrame->autorelease();
actionFrame->setFrameIndex(frameInex); actionFrame->setFrameIndex(frameInex);
actionFrame->setPosition(Point(positionX, positionY)); actionFrame->setPosition(Point(positionX, positionY));
Array* cActionArray = (Array*)_frameArray->getObjectAtIndex((int)kKeyframeMove); auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->addObject(actionFrame); cActionArray->pushBack(actionFrame);
} }
bool existScale = DICTOOL->checkObjectExist_json(actionFrameDic,"scalex"); bool existScale = DICTOOL->checkObjectExist_json(actionFrameDic,"scalex");
@ -100,11 +96,12 @@ void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root)
float scaleX = DICTOOL->getFloatValue_json(actionFrameDic, "scalex"); float scaleX = DICTOOL->getFloatValue_json(actionFrameDic, "scalex");
float scaleY = DICTOOL->getFloatValue_json(actionFrameDic, "scaley"); float scaleY = DICTOOL->getFloatValue_json(actionFrameDic, "scaley");
ActionScaleFrame* actionFrame = new ActionScaleFrame(); ActionScaleFrame* actionFrame = new ActionScaleFrame();
actionFrame->autorelease();
actionFrame->setFrameIndex(frameInex); actionFrame->setFrameIndex(frameInex);
actionFrame->setScaleX(scaleX); actionFrame->setScaleX(scaleX);
actionFrame->setScaleY(scaleY); actionFrame->setScaleY(scaleY);
Array* cActionArray = (Array*)_frameArray->getObjectAtIndex((int)kKeyframeScale); auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->addObject(actionFrame); cActionArray->pushBack(actionFrame);
} }
bool existRotation = DICTOOL->checkObjectExist_json(actionFrameDic,"rotation"); bool existRotation = DICTOOL->checkObjectExist_json(actionFrameDic,"rotation");
@ -112,10 +109,11 @@ void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root)
{ {
float rotation = DICTOOL->getFloatValue_json(actionFrameDic, "rotation"); float rotation = DICTOOL->getFloatValue_json(actionFrameDic, "rotation");
ActionRotationFrame* actionFrame = new ActionRotationFrame(); ActionRotationFrame* actionFrame = new ActionRotationFrame();
actionFrame->autorelease();
actionFrame->setFrameIndex(frameInex); actionFrame->setFrameIndex(frameInex);
actionFrame->setRotation(rotation); actionFrame->setRotation(rotation);
Array* cActionArray = (Array*)_frameArray->getObjectAtIndex((int)kKeyframeRotate); auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->addObject(actionFrame); cActionArray->pushBack(actionFrame);
} }
bool existOpacity = DICTOOL->checkObjectExist_json(actionFrameDic,"opacity"); bool existOpacity = DICTOOL->checkObjectExist_json(actionFrameDic,"opacity");
@ -123,10 +121,11 @@ void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root)
{ {
int opacity = DICTOOL->getIntValue_json(actionFrameDic, "opacity"); int opacity = DICTOOL->getIntValue_json(actionFrameDic, "opacity");
ActionFadeFrame* actionFrame = new ActionFadeFrame(); ActionFadeFrame* actionFrame = new ActionFadeFrame();
actionFrame->autorelease();
actionFrame->setFrameIndex(frameInex); actionFrame->setFrameIndex(frameInex);
actionFrame->setOpacity(opacity); actionFrame->setOpacity(opacity);
Array* cActionArray = (Array*)_frameArray->getObjectAtIndex((int)kKeyframeFade); auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->addObject(actionFrame); cActionArray->pushBack(actionFrame);
} }
bool existColor = DICTOOL->checkObjectExist_json(actionFrameDic,"colorr"); bool existColor = DICTOOL->checkObjectExist_json(actionFrameDic,"colorr");
@ -136,13 +135,12 @@ void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root)
int colorG = DICTOOL->getIntValue_json(actionFrameDic, "colorg"); int colorG = DICTOOL->getIntValue_json(actionFrameDic, "colorg");
int colorB = DICTOOL->getIntValue_json(actionFrameDic, "colorb"); int colorB = DICTOOL->getIntValue_json(actionFrameDic, "colorb");
ActionTintFrame* actionFrame = new ActionTintFrame(); ActionTintFrame* actionFrame = new ActionTintFrame();
actionFrame->autorelease();
actionFrame->setFrameIndex(frameInex); actionFrame->setFrameIndex(frameInex);
actionFrame->setColor(Color3B(colorR,colorG,colorB)); actionFrame->setColor(Color3B(colorR,colorG,colorB));
Array* cActionArray = (Array*)_frameArray->getObjectAtIndex((int)kKeyframeTint); auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->addObject(actionFrame); cActionArray->pushBack(actionFrame);
} }
CC_SAFE_DELETE(actionFrameDic);
} }
initActionNodeFromRoot(root); initActionNodeFromRoot(root);
} }
@ -150,13 +148,13 @@ void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root)
void ActionNode::initActionNodeFromRoot(Object* root) void ActionNode::initActionNodeFromRoot(Object* root)
{ {
Node* rootNode = dynamic_cast<Node*>(root); Node* rootNode = dynamic_cast<Node*>(root);
if (rootNode != NULL) if (rootNode != nullptr)
{ {
Widget* rootWidget = dynamic_cast<Widget*>(root); Widget* rootWidget = dynamic_cast<Widget*>(root);
if (rootWidget != NULL) if (rootWidget != nullptr)
{ {
Widget* widget = UIHelper::seekActionWidgetByActionTag(rootWidget, getActionTag()); Widget* widget = UIHelper::seekActionWidgetByActionTag(rootWidget, getActionTag());
if (widget != NULL) if (widget != nullptr)
{ {
setObject(widget); setObject(widget);
} }
@ -198,114 +196,113 @@ Object* ActionNode::getObject()
Node* ActionNode::getActionNode() Node* ActionNode::getActionNode()
{ {
Node* cNode = dynamic_cast<Node*>(_object); Node* cNode = dynamic_cast<Node*>(_object);
if (cNode != NULL) if (cNode != nullptr)
{ {
return cNode; return cNode;
} }
else else
{ {
Widget* rootWidget = dynamic_cast<Widget*>(_object); Widget* rootWidget = dynamic_cast<Widget*>(_object);
if (rootWidget != NULL) if (rootWidget != nullptr)
{ {
return rootWidget; return rootWidget;
} }
} }
return NULL; return nullptr;
} }
void ActionNode::insertFrame(int index, ActionFrame* frame) void ActionNode::insertFrame(int index, ActionFrame* frame)
{ {
if (frame == NULL) if (frame == nullptr)
{ {
return; return;
} }
int frameType = frame->getFrameType(); int frameType = frame->getFrameType();
Array* cArray = (Array*)_frameArray->getObjectAtIndex(frameType); if(frameType < _frameArray.size())
if (cArray == NULL)
{ {
return; auto cArray = _frameArray.at(frameType);
cArray->insert(index, frame);
} }
cArray->insertObject(frame,index);
} }
void ActionNode::addFrame(ActionFrame* frame) void ActionNode::addFrame(ActionFrame* frame)
{ {
if (frame == NULL) if (frame == nullptr)
{ {
return; return;
} }
int frameType = frame->getFrameType(); int frameType = frame->getFrameType();
Array* cArray = (Array*)_frameArray->getObjectAtIndex(frameType);
if (cArray == NULL) if(frameType < _frameArray.size())
{ {
return; auto cArray = _frameArray.at(frameType);
cArray->pushBack(frame);
} }
cArray->addObject(frame);
} }
void ActionNode::deleteFrame(ActionFrame* frame) void ActionNode::deleteFrame(ActionFrame* frame)
{ {
if (frame == NULL) if (frame == nullptr)
{ {
return; return;
} }
int frameType = frame->getFrameType(); int frameType = frame->getFrameType();
Array* cArray = (Array*)_frameArray->getObjectAtIndex(frameType); if(frameType < _frameArray.size())
if (cArray == NULL)
{ {
return; auto cArray = _frameArray.at(frameType);
cArray->eraseObject(frame);
} }
cArray->removeObject(frame);
} }
void ActionNode::clearAllFrame() void ActionNode::clearAllFrame()
{ {
for (int i = 0; i < _frameArrayNum; i++) for(auto array : _frameArray)
{ {
_frameArray[i].removeAllObjects(); array->clear();
} }
} }
Spawn * ActionNode::refreshActionProperty() Spawn * ActionNode::refreshActionProperty()
{ {
if ( _object == NULL ) if ( _object == nullptr )
{ {
return NULL; return nullptr;
} }
Vector<FiniteTimeAction*> cSpawnArray; Vector<FiniteTimeAction*> cSpawnArray;
for (int n = 0; n < _frameArrayNum; n++) for (int n = 0; n < _frameArrayNum; n++)
{ {
Array* cArray = (Array*)(_frameArray->getObjectAtIndex(n)); auto cArray = _frameArray.at(n);
if (cArray == NULL || cArray->count() <= 0) if (cArray->size() <= 0)
{ {
continue; continue;
} }
Vector<FiniteTimeAction*> cSequenceArray; Vector<FiniteTimeAction*> cSequenceArray;
auto frameCount = cArray->count(); auto frameCount = cArray->size();
for (int i = 0; i < frameCount; i++) for (int i = 0; i < frameCount; i++)
{ {
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i)); auto frame = cArray->at(i);
if (i == 0) if (i == 0)
{ {
} }
else else
{ {
ActionFrame* srcFrame = (ActionFrame*)(cArray->getObjectAtIndex(i-1)); auto srcFrame = cArray->at(i-1);
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex()) * getUnitTime(); float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex()) * getUnitTime();
Action* cAction = frame->getAction(duration); Action* cAction = frame->getAction(duration);
if(cAction != nullptr)
cSequenceArray.pushBack(static_cast<FiniteTimeAction*>(cAction)); cSequenceArray.pushBack(static_cast<FiniteTimeAction*>(cAction));
} }
} }
Sequence* cSequence = Sequence::create(cSequenceArray); Sequence* cSequence = Sequence::create(cSequenceArray);
if (cSequence != NULL) if (cSequence != nullptr)
{ {
cSpawnArray.pushBack(cSequence); cSpawnArray.pushBack(cSequence);
} }
} }
if (_action == NULL) if (_action == nullptr)
{ {
CC_SAFE_RELEASE_NULL(_actionSpawn); CC_SAFE_RELEASE_NULL(_actionSpawn);
} }
@ -321,17 +318,17 @@ Spawn * ActionNode::refreshActionProperty()
void ActionNode::playAction() void ActionNode::playAction()
{ {
if ( _object == NULL || _actionSpawn == NULL) if ( _object == nullptr || _actionSpawn == nullptr)
{ {
return; return;
} }
if (_action!=NULL) if (_action!=nullptr)
{ {
_action->release(); _action->release();
} }
_action = Sequence::create(_actionSpawn, NULL); _action = Sequence::create(_actionSpawn, nullptr);
_action->retain(); _action->retain();
this->runAction(); this->runAction();
@ -341,7 +338,7 @@ void ActionNode::playAction()
void ActionNode::runAction() void ActionNode::runAction()
{ {
Node* cNode = this->getActionNode(); Node* cNode = this->getActionNode();
if (cNode != NULL && _action != NULL) if (cNode != nullptr && _action != nullptr)
{ {
cNode->runAction(_action); cNode->runAction(_action);
} }
@ -350,7 +347,7 @@ void ActionNode::runAction()
void ActionNode::stopAction() void ActionNode::stopAction()
{ {
Node* cNode = this->getActionNode(); Node* cNode = this->getActionNode();
if (cNode != NULL && _action != NULL) if (cNode != nullptr && _action != nullptr)
{ {
cNode->stopAction(_action); cNode->stopAction(_action);
} }
@ -362,13 +359,13 @@ int ActionNode::getFirstFrameIndex()
bool bFindFrame = false; bool bFindFrame = false;
for (int n = 0; n < _frameArrayNum; n++) for (int n = 0; n < _frameArrayNum; n++)
{ {
Array* cArray = (Array*)(_frameArray->getObjectAtIndex(n)); auto cArray = _frameArray.at(n);
if (cArray == NULL || cArray->count() <= 0) if (cArray->empty())
{ {
continue; continue;
} }
bFindFrame = true; bFindFrame = true;
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(0)); auto frame = cArray->at(0);
int iFrameIndex = frame->getFrameIndex(); int iFrameIndex = frame->getFrameIndex();
if (frameindex > iFrameIndex) if (frameindex > iFrameIndex)
@ -389,14 +386,14 @@ int ActionNode::getLastFrameIndex()
bool bFindFrame = false; bool bFindFrame = false;
for (int n = 0; n < _frameArrayNum; n++) for (int n = 0; n < _frameArrayNum; n++)
{ {
Array* cArray = (Array*)(_frameArray->getObjectAtIndex(n)); auto cArray = _frameArray.at(n);
if (cArray == NULL || cArray->count() <= 0) if (cArray->empty())
{ {
continue; continue;
} }
bFindFrame = true; bFindFrame = true;
ssize_t lastInex = cArray->count() - 1; ssize_t lastInex = cArray->size() - 1;
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(lastInex)); auto frame = cArray->at(lastInex);
int iFrameIndex = frame->getFrameIndex(); int iFrameIndex = frame->getFrameIndex();
if (frameindex < iFrameIndex) if (frameindex < iFrameIndex)
@ -414,24 +411,24 @@ bool ActionNode::updateActionToTimeLine(float fTime)
{ {
bool bFindFrame = false; bool bFindFrame = false;
ActionFrame* srcFrame = NULL; ActionFrame* srcFrame = nullptr;
// ActionFrame* destFrame = NULL; // ActionFrame* destFrame = nullptr;
for (int n = 0; n < _frameArrayNum; n++) for (int n = 0; n < _frameArrayNum; n++)
{ {
Array* cArray = (Array*)(_frameArray->getObjectAtIndex(n)); auto cArray = _frameArray.at(n);
if (cArray == NULL) if (cArray->empty())
{ {
continue; continue;
} }
ssize_t frameCount = cArray->count(); ssize_t frameCount = cArray->size();
for (int i = 0; i < frameCount; i++) for (int i = 0; i < frameCount; i++)
{ {
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i)); auto frame = cArray->at(i);
if (frame->getFrameIndex()*getUnitTime() == fTime) if (frame->getFrameIndex()*getUnitTime() == fTime)
{ {
this->easingToFrame(1.0f,1.0f,frame); this->easingToFrame(1.0f,1.0f,nullptr,frame);
bFindFrame = true; bFindFrame = true;
break; break;
} }
@ -439,17 +436,17 @@ bool ActionNode::updateActionToTimeLine(float fTime)
{ {
if (i == 0) if (i == 0)
{ {
this->easingToFrame(1.0f,1.0f,frame); this->easingToFrame(1.0f,1.0f,nullptr,frame);
bFindFrame = false; bFindFrame = false;
} }
else else
{ {
srcFrame = (ActionFrame*)(cArray->getObjectAtIndex(i-1)); srcFrame = cArray->at(i-1);
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex())*getUnitTime(); float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex())*getUnitTime();
float delaytime = fTime - srcFrame->getFrameIndex()*getUnitTime(); float delaytime = fTime - srcFrame->getFrameIndex()*getUnitTime();
this->easingToFrame(duration,1.0f,srcFrame); this->easingToFrame(duration,1.0f,nullptr,srcFrame);
//float easingTime = ActionFrameEasing::bounceTime(delaytime); //float easingTime = ActionFrameEasing::bounceTime(delaytime);
this->easingToFrame(duration,delaytime/duration,frame); this->easingToFrame(duration,delaytime/duration,srcFrame,frame);
bFindFrame = true; bFindFrame = true;
} }
break; break;
@ -459,11 +456,11 @@ bool ActionNode::updateActionToTimeLine(float fTime)
return bFindFrame; return bFindFrame;
} }
void ActionNode::easingToFrame(float duration,float delayTime,ActionFrame* destFrame) void ActionNode::easingToFrame(float duration,float delayTime,ActionFrame* srcFrame,ActionFrame* destFrame)
{ {
Action* cAction = destFrame->getAction(duration); Action* cAction = destFrame->getAction(duration,srcFrame);
Node* cNode = this->getActionNode(); Node* cNode = this->getActionNode();
if (cAction == NULL || cNode == NULL) if (cAction == nullptr || cNode == nullptr)
{ {
return; return;
} }

View File

@ -1,40 +1,40 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __ActionNODE_H__ #ifndef __ActionNODE_H__
#define __ActionNODE_H__ #define __ActionNODE_H__
#include "cocos2d.h" #include "cocos2d.h"
#include "cocostudio/CCActionFrame.h" #include "cocostudio/CCActionFrame.h"
#include "cocostudio/CSContentJsonDictionary.h" #include "cocostudio/DictionaryHelper.h"
namespace cocostudio { namespace cocostudio {
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionNode:public cocos2d::Object class ActionNode:public cocos2d::Object
{ {
public: public:
@ -149,7 +149,7 @@ public:
virtual void stopAction(); virtual void stopAction();
/*init properties with a json dictionary*/ /*init properties with a json dictionary*/
virtual void initWithDictionary(JsonDictionary* dic,cocos2d::Object* root); virtual void initWithDictionary(const rapidjson::Value& dic,Object* root);
/** /**
* Gets if the action is done once time. * Gets if the action is done once time.
@ -168,7 +168,7 @@ protected:
cocos2d::Action* _action; cocos2d::Action* _action;
cocos2d::Object* _object; cocos2d::Object* _object;
cocos2d::Array* _frameArray; std::vector<cocos2d::Vector<ActionFrame*>*> _frameArray;
int _frameArrayNum; int _frameArrayNum;
protected: protected:
@ -176,7 +176,7 @@ protected:
virtual cocos2d::Spawn * refreshActionProperty(); virtual cocos2d::Spawn * refreshActionProperty();
virtual void runAction(); virtual void runAction();
virtual void initActionNodeFromRoot(cocos2d::Object* root); virtual void initActionNodeFromRoot(cocos2d::Object* root);
virtual void easingToFrame(float duration,float delayTime,ActionFrame* destFrame); virtual void easingToFrame(float duration,float delayTime,ActionFrame* srcFrame,ActionFrame* destFrame);
}; };
} }

View File

@ -1,26 +1,26 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocostudio/CCActionObject.h" #include "cocostudio/CCActionObject.h"
#include "cocostudio/DictionaryHelper.h" #include "cocostudio/DictionaryHelper.h"
@ -30,25 +30,23 @@ using namespace cocos2d;
namespace cocostudio { namespace cocostudio {
ActionObject::ActionObject() ActionObject::ActionObject()
: _actionNodeList(NULL) : _name("")
, _name("")
, _loop(false) , _loop(false)
, _bPause(false) , _bPause(false)
, _bPlaying(false) , _bPlaying(false)
, _fUnitTime(0.1f) , _fUnitTime(0.1f)
, _currentTime(0.0f) , _currentTime(0.0f)
, _pScheduler(NULL) , _pScheduler(nullptr)
, _CallBack(nullptr)
, _fTotalTime(0.0f)
{ {
_actionNodeList = Array::create();
_actionNodeList->retain();
_pScheduler = Director::getInstance()->getScheduler(); _pScheduler = Director::getInstance()->getScheduler();
CC_SAFE_RETAIN(_pScheduler); CC_SAFE_RETAIN(_pScheduler);
} }
ActionObject::~ActionObject() ActionObject::~ActionObject()
{ {
_actionNodeList->removeAllObjects(); _actionNodeList.clear();
_actionNodeList->release();
CC_SAFE_RELEASE(_pScheduler); CC_SAFE_RELEASE(_pScheduler);
} }
@ -73,11 +71,9 @@ bool ActionObject::getLoop()
void ActionObject::setUnitTime(float fTime) void ActionObject::setUnitTime(float fTime)
{ {
_fUnitTime = fTime; _fUnitTime = fTime;
auto nodeNum = _actionNodeList->count(); for(const auto &e : _actionNodeList)
for ( int i = 0; i < nodeNum; i++ )
{ {
ActionNode* actionNode = (ActionNode*)_actionNodeList->getObjectAtIndex(i); e->setUnitTime(_fUnitTime);
actionNode->setUnitTime(_fUnitTime);
} }
} }
float ActionObject::getUnitTime() float ActionObject::getUnitTime()
@ -95,62 +91,78 @@ void ActionObject::setCurrentTime(float fTime)
_currentTime = fTime; _currentTime = fTime;
} }
float ActionObject::getTotalTime()
{
return _fTotalTime;
}
bool ActionObject::isPlaying() bool ActionObject::isPlaying()
{ {
return _bPlaying; return _bPlaying;
} }
void ActionObject::initWithDictionary(JsonDictionary *dic,Object* root) void ActionObject::initWithDictionary(const rapidjson::Value& dic, Object* root)
{ {
setName(DICTOOL->getStringValue_json(dic, "name")); setName(DICTOOL->getStringValue_json(dic, "name"));
setLoop(DICTOOL->getBooleanValue_json(dic, "loop")); setLoop(DICTOOL->getBooleanValue_json(dic, "loop"));
setUnitTime(DICTOOL->getFloatValue_json(dic, "unittime")); setUnitTime(DICTOOL->getFloatValue_json(dic, "unittime"));
int actionNodeCount = DICTOOL->getArrayCount_json(dic, "actionnodelist"); int actionNodeCount = DICTOOL->getArrayCount_json(dic, "actionnodelist");
int maxLength = 0;
for (int i=0; i<actionNodeCount; i++) { for (int i=0; i<actionNodeCount; i++) {
ActionNode* actionNode = new ActionNode(); ActionNode* actionNode = new ActionNode();
actionNode->autorelease(); actionNode->autorelease();
JsonDictionary* actionNodeDic = DICTOOL->getDictionaryFromArray_json(dic, "actionnodelist", i); const rapidjson::Value& actionNodeDic = DICTOOL->getDictionaryFromArray_json(dic, "actionnodelist", i);
actionNode->initWithDictionary(actionNodeDic,root); actionNode->initWithDictionary(actionNodeDic,root);
actionNode->setUnitTime(getUnitTime()); actionNode->setUnitTime(getUnitTime());
_actionNodeList->addObject(actionNode); _actionNodeList.pushBack(actionNode);
CC_SAFE_DELETE(actionNodeDic);
int length = actionNode->getLastFrameIndex() - actionNode->getFirstFrameIndex();
if(length > maxLength)
maxLength = length;
} }
_fTotalTime = maxLength*_fTotalTime;
} }
void ActionObject::addActionNode(ActionNode* node) void ActionObject::addActionNode(ActionNode* node)
{ {
if (node == NULL) if (node == nullptr)
{ {
return; return;
} }
_actionNodeList->addObject(node); _actionNodeList.pushBack(node);
node->setUnitTime(_fUnitTime); node->setUnitTime(_fUnitTime);
} }
void ActionObject::removeActionNode(ActionNode* node) void ActionObject::removeActionNode(ActionNode* node)
{ {
if (node == NULL) if (node == nullptr)
{ {
return; return;
} }
_actionNodeList->removeObject(node); _actionNodeList.eraseObject(node);
} }
void ActionObject::play() void ActionObject::play()
{ {
stop(); stop();
this->updateToFrameByTime(0.0f); this->updateToFrameByTime(0.0f);
auto frameNum = _actionNodeList->count(); for(const auto &e : _actionNodeList)
for ( int i = 0; i < frameNum; i++ )
{ {
ActionNode* actionNode = (ActionNode*)_actionNodeList->getObjectAtIndex(i); e->playAction();
actionNode->playAction();
} }
if (_loop) if (_loop)
{ {
_pScheduler->scheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f , kRepeatForever, 0.0f, false); _pScheduler->scheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f , kRepeatForever, 0.0f, false);
} }
else
{
_pScheduler->scheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f, false);
}
} }
void ActionObject::play(CallFunc* func)
{
this->play();
this->_CallBack = func;
}
void ActionObject::pause() void ActionObject::pause()
{ {
_bPause = true; _bPause = true;
@ -158,14 +170,10 @@ void ActionObject::pause()
void ActionObject::stop() void ActionObject::stop()
{ {
auto frameNum = _actionNodeList->count(); for(const auto &e : _actionNodeList)
for ( int i = 0; i < frameNum; i++ )
{ {
ActionNode* actionNode = (ActionNode*)_actionNodeList->getObjectAtIndex(i); e->stopAction();
actionNode->stopAction();
} }
_pScheduler->unscheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this); _pScheduler->unscheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this);
_bPause = false; _bPause = false;
} }
@ -173,29 +181,19 @@ void ActionObject::stop()
void ActionObject::updateToFrameByTime(float fTime) void ActionObject::updateToFrameByTime(float fTime)
{ {
_currentTime = fTime; _currentTime = fTime;
for(const auto &e : _actionNodeList)
auto nodeNum = _actionNodeList->count();
for ( int i = 0; i < nodeNum; i++ )
{ {
ActionNode* actionNode = (ActionNode*)_actionNodeList->getObjectAtIndex(i); e->updateActionToTimeLine(fTime);
actionNode->updateActionToTimeLine(fTime);
} }
} }
void ActionObject::simulationActionUpdate(float dt) void ActionObject::simulationActionUpdate(float dt)
{ {
if (_loop)
{
bool isEnd = true; bool isEnd = true;
auto nodeNum = _actionNodeList->count();
for ( int i = 0; i < nodeNum; i++ ) for(const auto &e : _actionNodeList)
{ {
ActionNode* actionNode = static_cast<ActionNode*>(_actionNodeList->getObjectAtIndex(i)); if (!e->isActionDoneOnce())
if (actionNode->isActionDoneOnce() == false)
{ {
isEnd = false; isEnd = false;
break; break;
@ -203,11 +201,15 @@ void ActionObject::simulationActionUpdate(float dt)
} }
if (isEnd) if (isEnd)
{
if (_CallBack != nullptr)
{
_CallBack->execute();
}
if (_loop)
{ {
this->play(); this->play();
} }
//CCLOG("ActionObject Update");
} }
} }
} }

View File

@ -1,40 +1,40 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef __ActionObject_H__ #ifndef __ActionObject_H__
#define __ActionObject_H__ #define __ActionObject_H__
#include "cocos2d.h" #include "cocos2d.h"
#include "CCActionNode.h" #include "CCActionNode.h"
#include "cocostudio/CSContentJsonDictionary.h" #include "cocostudio/DictionaryHelper.h"
namespace cocostudio { namespace cocostudio {
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
class ActionObject:public cocos2d::Object class ActionObject:public cocos2d::Object
{ {
public: public:
@ -105,6 +105,13 @@ public:
*/ */
float getCurrentTime(); float getCurrentTime();
/**
* Gets the total time of frame.
*
* @return fTime the current time of frame
*/
float getTotalTime();
/** /**
* Return if the action is playing. * Return if the action is playing.
* *
@ -117,6 +124,13 @@ public:
*/ */
void play(); void play();
/**
* Play the action.
*
* @ Action Call Back
*/
void play(cocos2d::CallFunc* func);
/** /**
* Pause the action. * Pause the action.
*/ */
@ -145,12 +159,12 @@ public:
void updateToFrameByTime(float fTime); void updateToFrameByTime(float fTime);
/*init properties with a json dictionary*/ /*init properties with a json dictionary*/
void initWithDictionary(JsonDictionary* dic,cocos2d::Object* root); void initWithDictionary(const rapidjson::Value& dic,Object* root);
/*scheduler update function*/ /*scheduler update function*/
void simulationActionUpdate(float dt); void simulationActionUpdate(float dt);
protected: protected:
cocos2d::Array* _actionNodeList;/*actionnode*/ cocos2d::Vector<ActionNode*> _actionNodeList;/*actionnode*/
std::string _name; std::string _name;
bool _loop; bool _loop;
bool _bPause; bool _bPause;
@ -158,6 +172,8 @@ protected:
float _fUnitTime; float _fUnitTime;
float _currentTime; float _currentTime;
cocos2d::Scheduler *_pScheduler; cocos2d::Scheduler *_pScheduler;
cocos2d::CallFunc *_CallBack;
float _fTotalTime;
}; };
} }

View File

@ -28,7 +28,7 @@ THE SOFTWARE.
#include "cocostudio/CCDataReaderHelper.h" #include "cocostudio/CCDataReaderHelper.h"
#include "cocostudio/CCDatas.h" #include "cocostudio/CCDatas.h"
#include "cocostudio/CCSkin.h" #include "cocostudio/CCSkin.h"
#include "CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCRenderer.h" #include "CCRenderer.h"
#include "CCGroupCommand.h" #include "CCGroupCommand.h"
@ -181,9 +181,6 @@ bool Armature::init(const std::string& name)
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
unscheduleUpdate();
scheduleUpdate();
setCascadeOpacityEnabled(true); setCascadeOpacityEnabled(true);
setCascadeColorEnabled(true); setCascadeColorEnabled(true);
@ -432,6 +429,18 @@ void Armature::draw()
} }
} }
void Armature::onEnter()
{
Node::onEnter();
scheduleUpdate();
}
void Armature::onExit()
{
Node::onExit();
unscheduleUpdate();
}
void Armature::visit() void Armature::visit()
{ {

View File

@ -161,6 +161,9 @@ public:
virtual void update(float dt) override; virtual void update(float dt) override;
virtual void draw() override; virtual void draw() override;
virtual void onEnter() override;
virtual void onExit() override;
virtual const kmMat4& getNodeToParentTransform() const override; virtual const kmMat4& getNodeToParentTransform() const override;
/** /**
* @js NA * @js NA

View File

@ -246,8 +246,12 @@ void ArmatureAnimation::play(const std::string& animationName, int durationTo,
_armature->update(0); _armature->update(0);
} }
void ArmatureAnimation::playByIndex(int animationIndex, int durationTo, int loop) void ArmatureAnimation::playByIndex(int animationIndex, int durationTo, int loop)
{
playWithIndex(animationIndex, durationTo, loop);
}
void ArmatureAnimation::playWithIndex(int animationIndex, int durationTo, int loop)
{ {
std::vector<std::string> &movName = _animationData->movementNames; std::vector<std::string> &movName = _animationData->movementNames;
CC_ASSERT((animationIndex > -1) && ((unsigned int)animationIndex < movName.size())); CC_ASSERT((animationIndex > -1) && ((unsigned int)animationIndex < movName.size()));
@ -257,7 +261,7 @@ void ArmatureAnimation::playByIndex(int animationIndex, int durationTo, int loop
} }
void ArmatureAnimation::play(const std::vector<std::string>& movementNames, int durationTo, bool loop) void ArmatureAnimation::playWithNames(const std::vector<std::string>& movementNames, int durationTo, bool loop)
{ {
_movementList.clear(); _movementList.clear();
_movementListLoop = loop; _movementListLoop = loop;
@ -270,7 +274,7 @@ void ArmatureAnimation::play(const std::vector<std::string>& movementNames, int
updateMovementList(); updateMovementList();
} }
void ArmatureAnimation::playByIndex(const std::vector<int>& movementIndexes, int durationTo, bool loop) void ArmatureAnimation::playWithIndexes(const std::vector<int>& movementIndexes, int durationTo, bool loop)
{ {
_movementList.clear(); _movementList.clear();
_movementListLoop = loop; _movementListLoop = loop;

View File

@ -127,13 +127,14 @@ public:
/** /**
* Play animation by index, the other param is the same to play. * Play animation by index, the other param is the same to play.
* @deprecated, please use playWithIndex
* @param animationIndex the animation index you want to play * @param animationIndex the animation index you want to play
*/ */
virtual void playByIndex(int animationIndex, int durationTo = -1, int loop = -1); CC_DEPRECATED_ATTRIBUTE virtual void playByIndex(int animationIndex, int durationTo = -1, int loop = -1);
virtual void playWithIndex(int animationIndex, int durationTo = -1, int loop = -1);
virtual void playWithNames(const std::vector<std::string>& movementNames, int durationTo = -1, bool loop = true);
virtual void play(const std::vector<std::string>& movementNames, int durationTo = -1, bool loop = true); virtual void playWithIndexes(const std::vector<int>& movementIndexes, int durationTo = -1, bool loop = true);
virtual void playByIndex(const std::vector<int>& movementIndexes, int durationTo = -1, bool loop = true);
/** /**
* Go to specified frame and play current movement. * Go to specified frame and play current movement.

View File

@ -47,7 +47,7 @@ ArmatureDataManager *ArmatureDataManager::getInstance()
return s_sharedArmatureDataManager; return s_sharedArmatureDataManager;
} }
void ArmatureDataManager::destoryInstance() void ArmatureDataManager::destroyInstance()
{ {
SpriteFrameCacheHelper::purge(); SpriteFrameCacheHelper::purge();
DataReaderHelper::purge(); DataReaderHelper::purge();

View File

@ -49,10 +49,10 @@ public:
CC_DEPRECATED_ATTRIBUTE static ArmatureDataManager *sharedArmatureDataManager() { return ArmatureDataManager::getInstance(); } CC_DEPRECATED_ATTRIBUTE static ArmatureDataManager *sharedArmatureDataManager() { return ArmatureDataManager::getInstance(); }
/** @deprecated Use destoryInstance() instead */ /** @deprecated Use destoryInstance() instead */
CC_DEPRECATED_ATTRIBUTE static void purge() { ArmatureDataManager::destoryInstance(); }; CC_DEPRECATED_ATTRIBUTE static void purge() { ArmatureDataManager::destroyInstance(); };
static ArmatureDataManager *getInstance(); static ArmatureDataManager *getInstance();
static void destoryInstance(); static void destroyInstance();
private: private:
/** /**
@ -199,7 +199,7 @@ private:
bool _autoLoadSpriteFile; bool _autoLoadSpriteFile;
std::map<std::string, RelativeData> _relativeDatas; std::unordered_map<std::string, RelativeData> _relativeDatas;
}; };

View File

@ -46,11 +46,13 @@ BatchNode *BatchNode::create()
} }
BatchNode::BatchNode() BatchNode::BatchNode()
: _groupCommand(nullptr)
{ {
} }
BatchNode::~BatchNode() BatchNode::~BatchNode()
{ {
CC_SAFE_DELETE(_groupCommand);
} }
bool BatchNode::init() bool BatchNode::init()
@ -78,6 +80,10 @@ void BatchNode::addChild(Node *child, int zOrder, int tag)
if (armature != nullptr) if (armature != nullptr)
{ {
armature->setBatchNode(this); armature->setBatchNode(this);
if (_groupCommand == nullptr)
{
_groupCommand = new GroupCommand();
}
} }
} }
@ -120,16 +126,16 @@ void BatchNode::draw()
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
generateGroupCommand(); bool pushed = false;
for(auto object : _children) for(auto object : _children)
{ {
Armature *armature = dynamic_cast<Armature *>(object); Armature *armature = dynamic_cast<Armature *>(object);
if (armature) if (armature)
{ {
if (_popGroupCommand) if (!pushed)
{ {
generateGroupCommand(); generateGroupCommand();
pushed = true;
} }
armature->visit(); armature->visit();
@ -137,7 +143,7 @@ void BatchNode::draw()
else else
{ {
Director::getInstance()->getRenderer()->popGroup(); Director::getInstance()->getRenderer()->popGroup();
_popGroupCommand = true; pushed = false;
((Node *)object)->visit(); ((Node *)object)->visit();
} }
@ -147,13 +153,10 @@ void BatchNode::draw()
void BatchNode::generateGroupCommand() void BatchNode::generateGroupCommand()
{ {
Renderer* renderer = Director::getInstance()->getRenderer(); Renderer* renderer = Director::getInstance()->getRenderer();
GroupCommand* groupCommand = GroupCommand::getCommandPool().generateCommand(); _groupCommand->init(0,_vertexZ);
groupCommand->init(0,_vertexZ); renderer->addCommand(_groupCommand);
renderer->addCommand(groupCommand);
renderer->pushGroup(groupCommand->getRenderQueueID()); renderer->pushGroup(_groupCommand->getRenderQueueID());
_popGroupCommand = false;
} }
} }

View File

@ -27,6 +27,10 @@ THE SOFTWARE.
#include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmatureDefine.h"
namespace cocos2d {
class GroupCommand;
}
namespace cocostudio { namespace cocostudio {
class BatchNode : public cocos2d::Node class BatchNode : public cocos2d::Node
@ -61,11 +65,10 @@ public:
*/ */
void draw() override; void draw() override;
void setPopGroupCommand(bool pop) { _popGroupCommand = pop; }
protected: protected:
void generateGroupCommand(); void generateGroupCommand();
bool _popGroupCommand; cocos2d::GroupCommand* _groupCommand;
}; };
} }

View File

@ -28,22 +28,80 @@ using namespace cocos2d;
namespace cocostudio { namespace cocostudio {
ComAttribute::ComAttribute(void) ComAttribute::ComAttribute(void)
: _jsonDict(nullptr)
{ {
_name = "ComAttribute"; _name = "ComAttribute";
} }
ComAttribute::~ComAttribute(void) ComAttribute::~ComAttribute(void)
{ {
CC_SAFE_DELETE(_jsonDict); _dict.clear();
} }
bool ComAttribute::init() bool ComAttribute::init()
{ {
_jsonDict = new JsonDictionary();
return true; return true;
} }
void ComAttribute::setInt(const std::string& key, int value)
{
_dict[key] = cocos2d::Value(value);
}
void ComAttribute::setFloat(const std::string& key, float value)
{
_dict[key] = cocos2d::Value(value);
}
void ComAttribute::setBool(const std::string& key, bool value)
{
_dict[key] = cocos2d::Value(value);
}
void ComAttribute::setString(const std::string& key, const std::string& value)
{
_dict[key] = cocos2d::Value(value);
}
int ComAttribute::getInt(const std::string& key, int def) const
{
if (_dict.find(key) == _dict.end())
{
return def;
}
const cocos2d::Value& v = _dict.at(key);
return v.asInt();
}
float ComAttribute::getFloat(const std::string& key, float def) const
{
if (_dict.find(key) == _dict.end())
{
return def;
}
const cocos2d::Value& v = _dict.at(key);
return v.asFloat();
}
bool ComAttribute::getBool(const std::string& key, bool def) const
{
if (_dict.find(key) == _dict.end())
{
return def;
}
const cocos2d::Value& v = _dict.at(key);
return v.asBool();
}
std::string ComAttribute::getString(const std::string& key, const std::string& def) const
{
if (_dict.find(key) == _dict.end())
{
return def;
}
const cocos2d::Value& v = _dict.at(key);
return v.asString();
}
ComAttribute* ComAttribute::create(void) ComAttribute* ComAttribute::create(void)
{ {
ComAttribute * pRet = new ComAttribute(); ComAttribute * pRet = new ComAttribute();
@ -58,54 +116,5 @@ ComAttribute* ComAttribute::create(void)
return pRet; return pRet;
} }
void ComAttribute::setInt(const char *key, int value)
{
CCASSERT(key != NULL, "Argument must be non-nil");
_jsonDict->insertItem(key, value);
}
void ComAttribute::setFloat(const char *key, float value)
{
CCASSERT(key != NULL, "Argument must be non-nil");
_jsonDict->insertItem(key, value);
}
void ComAttribute::setBool(const char *key, bool value)
{
CCASSERT(key != NULL, "Argument must be non-nil");
_jsonDict->insertItem(key, value);
}
void ComAttribute::setCString(const char *key, const char *value)
{
CCASSERT(key != NULL, "Argument must be non-nil");
_jsonDict->insertItem(key, value);
}
int ComAttribute::getInt(const char *key) const
{
return _jsonDict->getItemIntValue(key, -1);
}
float ComAttribute::getFloat(const char *key) const
{
return _jsonDict->getItemFloatValue(key, -1.0f);
}
bool ComAttribute::getBool(const char *key) const
{
return _jsonDict->getItemBoolvalue(key, false);
}
const char* ComAttribute::getCString(const char *key) const
{
return _jsonDict->getItemStringValue(key);
}
JsonDictionary* ComAttribute::getDict() const
{
return _jsonDict;
}
} }

View File

@ -27,7 +27,7 @@ THE SOFTWARE.
#include "cocos2d.h" #include "cocos2d.h"
#include <string> #include <string>
#include "cocostudio/CSContentJsonDictionary.h" #include "cocostudio/DictionaryHelper.h"
namespace cocostudio { namespace cocostudio {
@ -48,23 +48,17 @@ public:
virtual bool init(); virtual bool init();
static ComAttribute* create(void); static ComAttribute* create(void);
void setInt(const char *key, int value); void setInt(const std::string& key, int value);
void setFloat(const char *key, float value); void setFloat(const std::string& key, float value);
void setBool(const char *key, bool value); void setBool(const std::string& key, bool value);
void setCString(const char *key, const char *value); void setString(const std::string& key, const std::string& value);
int getInt(const char *key) const;
float getFloat(const char *key) const;
bool getBool(const char *key) const;
const char* getCString(const char *key) const;
/**
* @js NA
*/
JsonDictionary* getDict() const;
int getInt(const std::string& key, int def = 0) const;
float getFloat(const std::string& key, float def = 0.0f) const;
bool getBool(const std::string& key, bool def = false) const;
std::string getString(const std::string& key, const std::string& def = "") const;
private: private:
JsonDictionary *_jsonDict; cocos2d::ValueMap _dict;
}; };
} }

View File

@ -86,11 +86,14 @@ void ComAudio::end()
void ComAudio::preloadBackgroundMusic(const char* pszFilePath) void ComAudio::preloadBackgroundMusic(const char* pszFilePath)
{ {
CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic(pszFilePath); CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic(pszFilePath);
setFile(pszFilePath);
setLoop(false);
} }
void ComAudio::playBackgroundMusic(const char* pszFilePath, bool bLoop) void ComAudio::playBackgroundMusic(const char* pszFilePath, bool bLoop)
{ {
CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(pszFilePath, bLoop); CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(pszFilePath, bLoop);
} }
void ComAudio::playBackgroundMusic(const char* pszFilePath) void ComAudio::playBackgroundMusic(const char* pszFilePath)
@ -98,6 +101,11 @@ void ComAudio::playBackgroundMusic(const char* pszFilePath)
CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(pszFilePath); CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(pszFilePath);
} }
void ComAudio::playBackgroundMusic()
{
CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(_filePath.c_str(), _loop);
}
void ComAudio::stopBackgroundMusic(bool bReleaseData) void ComAudio::stopBackgroundMusic(bool bReleaseData)
{ {
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(bReleaseData); CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(bReleaseData);
@ -163,6 +171,11 @@ unsigned int ComAudio::playEffect(const char* pszFilePath)
return CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(pszFilePath); return CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(pszFilePath);
} }
unsigned int ComAudio::playEffect()
{
return CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(_filePath.c_str(), _loop);
}
void ComAudio::pauseEffect(unsigned int nSoundId) void ComAudio::pauseEffect(unsigned int nSoundId)
{ {
return CocosDenshion::SimpleAudioEngine::getInstance()->pauseEffect(nSoundId); return CocosDenshion::SimpleAudioEngine::getInstance()->pauseEffect(nSoundId);
@ -196,6 +209,8 @@ void ComAudio::stopAllEffects()
void ComAudio::preloadEffect(const char* pszFilePath) void ComAudio::preloadEffect(const char* pszFilePath)
{ {
CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect(pszFilePath); CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect(pszFilePath);
setFile(pszFilePath);
setLoop(false);
} }
void ComAudio::unloadEffect(const char *pszFilePath) void ComAudio::unloadEffect(const char *pszFilePath)

View File

@ -64,6 +64,7 @@ public:
void preloadBackgroundMusic(const char* pszFilePath); void preloadBackgroundMusic(const char* pszFilePath);
void playBackgroundMusic(const char* pszFilePath, bool bLoop); void playBackgroundMusic(const char* pszFilePath, bool bLoop);
void playBackgroundMusic(const char* pszFilePath); void playBackgroundMusic(const char* pszFilePath);
void playBackgroundMusic();
void stopBackgroundMusic(bool bReleaseData); void stopBackgroundMusic(bool bReleaseData);
void stopBackgroundMusic(); void stopBackgroundMusic();
void pauseBackgroundMusic(); void pauseBackgroundMusic();
@ -77,6 +78,7 @@ public:
void setEffectsVolume(float volume); void setEffectsVolume(float volume);
unsigned int playEffect(const char* pszFilePath, bool bLoop); unsigned int playEffect(const char* pszFilePath, bool bLoop);
unsigned int playEffect(const char* pszFilePath); unsigned int playEffect(const char* pszFilePath);
unsigned int playEffect();
void pauseEffect(unsigned int nSoundId); void pauseEffect(unsigned int nSoundId);
void pauseAllEffects(); void pauseAllEffects();
void resumeEffect(unsigned int nSoundId); void resumeEffect(unsigned int nSoundId);

View File

@ -295,7 +295,6 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath)
dataInfo.filename = filePathStr; dataInfo.filename = filePathStr;
dataInfo.asyncStruct = nullptr; dataInfo.asyncStruct = nullptr;
dataInfo.baseFilePath = basefilePath; dataInfo.baseFilePath = basefilePath;
if (str == ".xml") if (str == ".xml")
{ {
DataReaderHelper::addDataFromCache(contentStr, &dataInfo); DataReaderHelper::addDataFromCache(contentStr, &dataInfo);
@ -1180,17 +1179,21 @@ ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML, D
void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, DataInfo *dataInfo) void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, DataInfo *dataInfo)
{ {
JsonDictionary json; rapidjson::Document json;
json.initWithDescription(fileContent.c_str());
dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); json.Parse<0>(fileContent.c_str());
if (json.HasParseError()) {
CCLOG("GetParseError %s\n",json.GetParseError());
}
dataInfo->contentScale = DICTOOL->getFloatValue_json(json, CONTENT_SCALE, 1.0f);
// Decode armatures // Decode armatures
int length = json.getArrayItemCount(ARMATURE_DATA); int length = DICTOOL->getArrayCount_json(json, ARMATURE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); const rapidjson::Value &armatureDic = DICTOOL->getSubDictionary_json(json, ARMATURE_DATA, i);
ArmatureData *armatureData = decodeArmature(*armatureDic, dataInfo); ArmatureData *armatureData = decodeArmature(armatureDic, dataInfo);
if (dataInfo->asyncStruct) if (dataInfo->asyncStruct)
{ {
@ -1202,15 +1205,14 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
{ {
_dataReaderHelper->_addDataMutex.unlock(); _dataReaderHelper->_addDataMutex.unlock();
} }
delete armatureDic;
} }
// Decode animations // Decode animations
length = json.getArrayItemCount(ANIMATION_DATA); length = DICTOOL->getArrayCount_json(json, ANIMATION_DATA); //json[ANIMATION_DATA].IsNull() ? 0 : json[ANIMATION_DATA].Size();
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); const rapidjson::Value &animationDic = DICTOOL->getSubDictionary_json(json, ANIMATION_DATA, i);
AnimationData *animationData = decodeAnimation(*animationDic, dataInfo); AnimationData *animationData = decodeAnimation(animationDic, dataInfo);
if (dataInfo->asyncStruct) if (dataInfo->asyncStruct)
{ {
@ -1222,15 +1224,14 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
{ {
_dataReaderHelper->_addDataMutex.unlock(); _dataReaderHelper->_addDataMutex.unlock();
} }
delete animationDic;
} }
// Decode textures // Decode textures
length = json.getArrayItemCount(TEXTURE_DATA); length = DICTOOL->getArrayCount_json(json, TEXTURE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); const rapidjson::Value &textureDic = DICTOOL->getSubDictionary_json(json, TEXTURE_DATA, i);
TextureData *textureData = decodeTexture(*textureDic); TextureData *textureData = decodeTexture(textureDic);
if (dataInfo->asyncStruct) if (dataInfo->asyncStruct)
{ {
@ -1242,17 +1243,16 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
{ {
_dataReaderHelper->_addDataMutex.unlock(); _dataReaderHelper->_addDataMutex.unlock();
} }
delete textureDic;
} }
// Auto load sprite file // Auto load sprite file
bool autoLoad = dataInfo->asyncStruct == nullptr ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; bool autoLoad = dataInfo->asyncStruct == nullptr ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile;
if (autoLoad) if (autoLoad)
{ {
length = json.getArrayItemCount(CONFIG_FILE_PATH); length = DICTOOL->getArrayCount_json(json, CONFIG_FILE_PATH); // json[CONFIG_FILE_PATH].IsNull() ? 0 : json[CONFIG_FILE_PATH].Size();
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i); const char *path = DICTOOL->getStringValueFromArray_json(json, CONFIG_FILE_PATH, i); // json[CONFIG_FILE_PATH][i].IsNull() ? NULL : json[CONFIG_FILE_PATH][i].GetString();
if (path == nullptr) if (path == nullptr)
{ {
CCLOG("load CONFIG_FILE_PATH error."); CCLOG("load CONFIG_FILE_PATH error.");
@ -1277,70 +1277,68 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
} }
} }
ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *dataInfo) ArmatureData *DataReaderHelper::decodeArmature(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
ArmatureData *armatureData = new ArmatureData(); ArmatureData *armatureData = new ArmatureData();
armatureData->init(); armatureData->init();
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != nullptr)
{ {
armatureData->name = name; armatureData->name = name;
} }
dataInfo->cocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); dataInfo->cocoStudioVersion = armatureData->dataVersion = DICTOOL->getFloatValue_json(json, VERSION, 0.1f);
int length = json.getArrayItemCount(BONE_DATA); int length = DICTOOL->getArrayCount_json(json, BONE_DATA, 0);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, BONE_DATA, i); //json[BONE_DATA][i];
BoneData *boneData = decodeBone(*dic, dataInfo); BoneData *boneData = decodeBone(dic, dataInfo);
armatureData->addBoneData(boneData); armatureData->addBoneData(boneData);
boneData->release(); boneData->release();
delete dic;
} }
return armatureData; return armatureData;
} }
BoneData *DataReaderHelper::decodeBone(JsonDictionary &json, DataInfo *dataInfo) BoneData *DataReaderHelper::decodeBone(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
BoneData *boneData = new BoneData(); BoneData *boneData = new BoneData();
boneData->init(); boneData->init();
decodeNode(boneData, json, dataInfo); decodeNode(boneData, json, dataInfo);
const char *str = json.getItemStringValue(A_NAME); const char *str = DICTOOL->getStringValue_json(json, A_NAME);
if(str != nullptr) if(str != nullptr)
{ {
boneData->name = str; boneData->name = str;
} }
str = json.getItemStringValue(A_PARENT); str = DICTOOL->getStringValue_json(json, A_PARENT);
if(str != nullptr) if(str != nullptr)
{ {
boneData->parentName = str; boneData->parentName = str;
} }
int length = json.getArrayItemCount(DISPLAY_DATA); int length = DICTOOL->getArrayCount_json(json, DISPLAY_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, DISPLAY_DATA, i);
DisplayData *displayData = decodeBoneDisplay(*dic, dataInfo); DisplayData *displayData = decodeBoneDisplay(dic, dataInfo);
boneData->addDisplayData(displayData); boneData->addDisplayData(displayData);
displayData->release(); displayData->release();
delete dic;
} }
return boneData; return boneData;
} }
DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo) DisplayData *DataReaderHelper::decodeBoneDisplay(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); DisplayType displayType = (DisplayType)(DICTOOL->getIntValue_json(json, A_DISPLAY_TYPE, CS_DISPLAY_SPRITE));
DisplayData *displayData = nullptr; DisplayData *displayData = nullptr;
@ -1350,27 +1348,29 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo
{ {
displayData = new SpriteDisplayData(); displayData = new SpriteDisplayData();
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != NULL)
{ {
((SpriteDisplayData *)displayData)->displayName = name; ((SpriteDisplayData *)displayData)->displayName = name;
} }
const rapidjson::Value &dicArray = DICTOOL->getSubDictionary_json(json, SKIN_DATA);
JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); if(!dicArray.IsNull())
if (dic != nullptr) {
rapidjson::SizeType index = 0;
const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(dicArray, index);
if (!dic.IsNull())
{ {
SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; SpriteDisplayData *sdd = (SpriteDisplayData *)displayData;
sdd->skinData.x = dic->getItemFloatValue(A_X, 0) * s_PositionReadScale; sdd->skinData.x = DICTOOL->getFloatValue_json(dic, A_X) * s_PositionReadScale;
sdd->skinData.y = dic->getItemFloatValue(A_Y, 0) * s_PositionReadScale; sdd->skinData.y = DICTOOL->getFloatValue_json(dic, A_Y) * s_PositionReadScale;
sdd->skinData.scaleX = dic->getItemFloatValue(A_SCALE_X, 1); sdd->skinData.scaleX = DICTOOL->getFloatValue_json(dic, A_SCALE_X, 1.0f);
sdd->skinData.scaleY = dic->getItemFloatValue(A_SCALE_Y, 1); sdd->skinData.scaleY = DICTOOL->getFloatValue_json(dic, A_SCALE_Y, 1.0f);
sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewX = DICTOOL->getFloatValue_json(dic, A_SKEW_X, 1.0f);
sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); sdd->skinData.skewY = DICTOOL->getFloatValue_json(dic, A_SKEW_Y, 1.0f);
sdd->skinData.x *= dataInfo->contentScale; sdd->skinData.x *= dataInfo->contentScale;
sdd->skinData.y *= dataInfo->contentScale; sdd->skinData.y *= dataInfo->contentScale;
}
delete dic;
} }
} }
@ -1379,7 +1379,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo
{ {
displayData = new ArmatureDisplayData(); displayData = new ArmatureDisplayData();
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != nullptr)
{ {
((ArmatureDisplayData *)displayData)->displayName = name; ((ArmatureDisplayData *)displayData)->displayName = name;
@ -1390,7 +1390,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo
{ {
displayData = new ParticleDisplayData(); displayData = new ParticleDisplayData();
const char *plist = json.getItemStringValue(A_PLIST); const char *plist = DICTOOL->getStringValue_json(json, A_PLIST);
if(plist != nullptr) if(plist != nullptr)
{ {
if (dataInfo->asyncStruct) if (dataInfo->asyncStruct)
@ -1416,80 +1416,84 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo
return displayData; return displayData;
} }
AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json, DataInfo *dataInfo) AnimationData *DataReaderHelper::decodeAnimation(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
AnimationData *aniData = new AnimationData(); AnimationData *aniData = new AnimationData();
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != nullptr)
{ {
aniData->name = name; aniData->name = name;
} }
int length = json.getArrayItemCount(MOVEMENT_DATA); int length = DICTOOL->getArrayCount_json(json, MOVEMENT_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, MOVEMENT_DATA, i);
MovementData *movementData = decodeMovement(*dic, dataInfo); MovementData *movementData = decodeMovement(dic, dataInfo);
aniData->addMovement(movementData); aniData->addMovement(movementData);
movementData->release(); movementData->release();
delete dic;
} }
return aniData; return aniData;
} }
MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *dataInfo) MovementData *DataReaderHelper::decodeMovement(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
MovementData *movementData = new MovementData(); MovementData *movementData = new MovementData();
movementData->loop = json.getItemBoolvalue(A_LOOP, true); movementData->loop = DICTOOL->getBooleanValue_json(json, A_LOOP, true);
movementData->durationTween = json.getItemIntValue(A_DURATION_TWEEN, 0); movementData->durationTween = DICTOOL->getIntValue_json(json, A_DURATION_TWEEN, 0);
movementData->durationTo = json.getItemIntValue(A_DURATION_TO, 0); movementData->durationTo = DICTOOL->getIntValue_json(json, A_DURATION_TO, 0);
movementData->duration = json.getItemIntValue(A_DURATION, 0); movementData->duration = DICTOOL->getIntValue_json(json, A_DURATION, 0);
movementData->scale = json.getItemFloatValue(A_MOVEMENT_SCALE, 1); if (!DICTOOL->checkObjectExist_json(json, A_DURATION))
movementData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); {
movementData->scale = 1.0f;
}
else
{
movementData->scale = DICTOOL->getFloatValue_json(json, A_MOVEMENT_SCALE, 1.0f);
}
movementData->tweenEasing = (TweenType)(DICTOOL->getIntValue_json(json, A_TWEEN_EASING, Linear));
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != nullptr)
{ {
movementData->name = name; movementData->name = name;
} }
int length = json.getArrayItemCount(MOVEMENT_BONE_DATA); int length = DICTOOL->getArrayCount_json(json, MOVEMENT_BONE_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, MOVEMENT_BONE_DATA, i);
MovementBoneData *movementBoneData = decodeMovementBone(*dic, dataInfo); MovementBoneData *movementBoneData = decodeMovementBone(dic, dataInfo);
movementData->addMovementBoneData(movementBoneData); movementData->addMovementBoneData(movementBoneData);
movementBoneData->release(); movementBoneData->release();
delete dic;
} }
return movementData; return movementData;
} }
MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo) MovementBoneData *DataReaderHelper::decodeMovementBone(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
MovementBoneData *movementBoneData = new MovementBoneData(); MovementBoneData *movementBoneData = new MovementBoneData();
movementBoneData->init(); movementBoneData->init();
movementBoneData->delay = json.getItemFloatValue(A_MOVEMENT_DELAY, 0); movementBoneData->delay = DICTOOL->getFloatValue_json(json, A_MOVEMENT_DELAY);
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != nullptr)
{ {
movementBoneData->name = name; movementBoneData->name = name;
} }
int length = json.getArrayItemCount(FRAME_DATA); rapidjson::SizeType length = DICTOOL->getArrayCount_json(json, FRAME_DATA);
for (int i = 0; i < length; i++) for (rapidjson::SizeType i = 0; i < length; i++)
{ {
JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, FRAME_DATA, i);
FrameData *frameData = decodeFrame(*dic, dataInfo); FrameData *frameData = decodeFrame(dic, dataInfo);
movementBoneData->addFrameData(frameData); movementBoneData->addFrameData(frameData);
frameData->release(); frameData->release();
@ -1499,8 +1503,6 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat
frameData->frameID = movementBoneData->duration; frameData->frameID = movementBoneData->duration;
movementBoneData->duration += frameData->duration; movementBoneData->duration += frameData->duration;
} }
delete dic;
} }
@ -1544,19 +1546,19 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat
return movementBoneData; return movementBoneData;
} }
FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInfo) FrameData *DataReaderHelper::decodeFrame(const rapidjson::Value& json, DataInfo *dataInfo)
{ {
FrameData *frameData = new FrameData(); FrameData *frameData = new FrameData();
decodeNode(frameData, json, dataInfo); decodeNode(frameData, json, dataInfo);
frameData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->tweenEasing = (TweenType)(DICTOOL->getIntValue_json(json, A_TWEEN_EASING, Linear));
frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); frameData->displayIndex = DICTOOL->getIntValue_json(json, A_DISPLAY_INDEX);
frameData->blendFunc.src = (GLenum)(json.getItemIntValue(A_BLEND_SRC, BlendFunc::ALPHA_NON_PREMULTIPLIED.src)); frameData->blendFunc.src = (GLenum)(DICTOOL->getIntValue_json(json, A_BLEND_SRC, BlendFunc::ALPHA_NON_PREMULTIPLIED.src));
frameData->blendFunc.dst = (GLenum)(json.getItemIntValue(A_BLEND_DST, BlendFunc::ALPHA_NON_PREMULTIPLIED.dst)); frameData->blendFunc.dst = (GLenum)(DICTOOL->getIntValue_json(json, A_BLEND_DST, BlendFunc::ALPHA_NON_PREMULTIPLIED.dst));
frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); frameData->isTween = DICTOOL->getBooleanValue_json(json, A_TWEEN_FRAME, true);
const char *event = json.getItemStringValue(A_EVENT); const char *event = DICTOOL->getStringValue_json(json, A_EVENT);
if (event != nullptr) if (event != nullptr)
{ {
frameData->strEvent = event; frameData->strEvent = event;
@ -1564,116 +1566,118 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf
if (dataInfo->cocoStudioVersion < VERSION_COMBINED) if (dataInfo->cocoStudioVersion < VERSION_COMBINED)
{ {
frameData->duration = json.getItemIntValue(A_DURATION, 1); frameData->duration = DICTOOL->getIntValue_json(json, A_DURATION, 1);
} }
else else
{ {
frameData->frameID = json.getItemIntValue(A_FRAME_INDEX, 0); frameData->frameID = DICTOOL->getIntValue_json(json, A_FRAME_INDEX);
} }
int length = json.getArrayItemCount(A_EASING_PARAM); int length = DICTOOL->getArrayCount_json(json, A_EASING_PARAM);
if (length != 0) if (length != 0)
{ {
frameData->easingParams = new float[length]; frameData->easingParams = new float[length];
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
frameData->easingParams[i] = json.getFloatValueFromArray(A_EASING_PARAM, i, 0); frameData->easingParams[i] = DICTOOL->getFloatValueFromArray_json(json, A_EASING_PARAM, i);
} }
} }
return frameData; return frameData;
} }
TextureData *DataReaderHelper::decodeTexture(JsonDictionary &json) TextureData *DataReaderHelper::decodeTexture(const rapidjson::Value& json)
{ {
TextureData *textureData = new TextureData(); TextureData *textureData = new TextureData();
textureData->init(); textureData->init();
const char *name = json.getItemStringValue(A_NAME); const char *name = DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr) if(name != nullptr)
{ {
textureData->name = name; textureData->name = name;
} }
textureData->width = json.getItemFloatValue(A_WIDTH, 0); textureData->width = DICTOOL->getFloatValue_json(json, A_WIDTH);
textureData->height = json.getItemFloatValue(A_HEIGHT, 0); textureData->height = DICTOOL->getFloatValue_json(json, A_HEIGHT);
textureData->pivotX = json.getItemFloatValue(A_PIVOT_X, 0); textureData->pivotX = DICTOOL->getFloatValue_json(json, A_PIVOT_X);
textureData->pivotY = json.getItemFloatValue(A_PIVOT_Y, 0); textureData->pivotY = DICTOOL->getFloatValue_json(json, A_PIVOT_Y);
int length = json.getArrayItemCount(CONTOUR_DATA); int length = DICTOOL->getArrayCount_json(json, CONTOUR_DATA);
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
JsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, CONTOUR_DATA, i);
ContourData *contourData = decodeContour(*dic); ContourData *contourData = decodeContour(dic);
textureData->contourDataList.pushBack(contourData); textureData->contourDataList.pushBack(contourData);
contourData->release(); contourData->release();
delete dic;
} }
return textureData; return textureData;
} }
ContourData *DataReaderHelper::decodeContour(JsonDictionary &json) ContourData *DataReaderHelper::decodeContour(const rapidjson::Value& json)
{ {
ContourData *contourData = new ContourData(); ContourData *contourData = new ContourData();
contourData->init(); contourData->init();
int length = json.getArrayItemCount(VERTEX_POINT); int length = DICTOOL->getArrayCount_json(json, VERTEX_POINT);
for (int i = length - 1; i >= 0; i--) for (int i = length - 1; i >= 0; i--)
{ {
JsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i); const rapidjson::Value &dic = DICTOOL->getSubDictionary_json(json, VERTEX_POINT, i);
Point vertex; Point vertex;
vertex.x = dic->getItemFloatValue(A_X, 0); vertex.x = DICTOOL->getFloatValue_json(dic, A_X);
vertex.y = dic->getItemFloatValue(A_Y, 0); vertex.y = DICTOOL->getFloatValue_json(dic, A_Y);
contourData->vertexList.push_back(vertex); contourData->vertexList.push_back(vertex);
delete dic;
} }
return contourData; return contourData;
} }
void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo) void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json, DataInfo *dataInfo)
{ {
node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->x = DICTOOL->getFloatValue_json(json, A_X) * s_PositionReadScale;
node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; node->y = DICTOOL->getFloatValue_json(json, A_Y) * s_PositionReadScale;
node->x *= dataInfo->contentScale; node->x *= dataInfo->contentScale;
node->y *= dataInfo->contentScale; node->y *= dataInfo->contentScale;
node->zOrder = json.getItemIntValue(A_Z, 0); node->zOrder = DICTOOL->getIntValue_json(json, A_Z);
node->skewX = json.getItemFloatValue(A_SKEW_X, 0); node->skewX = DICTOOL->getFloatValue_json(json, A_SKEW_X);
node->skewY = json.getItemFloatValue(A_SKEW_Y, 0); node->skewY = DICTOOL->getFloatValue_json(json, A_SKEW_Y);
node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleX = DICTOOL->getFloatValue_json(json, A_SCALE_X, 1.0f);
node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); node->scaleY = DICTOOL->getFloatValue_json(json, A_SCALE_Y, 1.0f);
JsonDictionary *colorDic = nullptr;
if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING) if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING)
{ {
colorDic = json.getSubItemFromArray(COLOR_INFO, 0); if (DICTOOL->checkObjectExist_json(json, 0))
{
const rapidjson::Value &colorDic = DICTOOL->getSubDictionary_json(json, 0);
node->a = DICTOOL->getIntValue_json(colorDic, A_ALPHA, 255);
node->r = DICTOOL->getIntValue_json(colorDic, A_RED, 255);
node->g = DICTOOL->getIntValue_json(colorDic, A_GREEN, 255);
node->b = DICTOOL->getIntValue_json(colorDic, A_BLUE, 255);
node->isUseColorInfo = true;
}
} }
else else
{ {
colorDic = json.getSubDictionary(COLOR_INFO); if (DICTOOL->checkObjectExist_json(json, COLOR_INFO))
}
if (colorDic)
{ {
node->a = colorDic->getItemIntValue(A_ALPHA, 255); const rapidjson::Value &colorDic = DICTOOL->getSubDictionary_json(json, COLOR_INFO); //json.getSubDictionary(COLOR_INFO);
node->r = colorDic->getItemIntValue(A_RED, 255); node->a = DICTOOL->getIntValue_json(colorDic, A_ALPHA, 255);
node->g = colorDic->getItemIntValue(A_GREEN, 255); node->r = DICTOOL->getIntValue_json(colorDic, A_RED, 255);
node->b = colorDic->getItemIntValue(A_BLUE, 255); node->g = DICTOOL->getIntValue_json(colorDic, A_GREEN, 255);
node->b = DICTOOL->getIntValue_json(colorDic, A_BLUE, 255);
node->isUseColorInfo = true; node->isUseColorInfo = true;
}
delete colorDic;
} }
} }

View File

@ -28,7 +28,7 @@ THE SOFTWARE.
#include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmatureDefine.h"
#include "cocostudio/CCDatas.h" #include "cocostudio/CCDatas.h"
#include "cocostudio/CCArmature.h" #include "cocostudio/CCArmature.h"
#include "cocostudio/CSContentJsonDictionary.h" #include "cocostudio/DictionaryHelper.h"
#include <string> #include <string>
#include <queue> #include <queue>
@ -156,20 +156,20 @@ public:
public: public:
static void addDataFromJsonCache(const std::string& fileContent, DataInfo *dataInfo = nullptr); static void addDataFromJsonCache(const std::string& fileContent, DataInfo *dataInfo = nullptr);
static ArmatureData *decodeArmature(JsonDictionary &json, DataInfo *dataInfo); static ArmatureData *decodeArmature(const rapidjson::Value& json, DataInfo *dataInfo);
static BoneData *decodeBone(JsonDictionary &json, DataInfo *dataInfo); static BoneData *decodeBone(const rapidjson::Value& json, DataInfo *dataInfo);
static DisplayData *decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo); static DisplayData *decodeBoneDisplay(const rapidjson::Value& json, DataInfo *dataInfo);
static AnimationData *decodeAnimation(JsonDictionary &json, DataInfo *dataInfo); static AnimationData *decodeAnimation(const rapidjson::Value& json, DataInfo *dataInfo);
static MovementData *decodeMovement(JsonDictionary &json, DataInfo *dataInfo); static MovementData *decodeMovement(const rapidjson::Value& json, DataInfo *dataInfo);
static MovementBoneData *decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo); static MovementBoneData *decodeMovementBone(const rapidjson::Value& json, DataInfo *dataInfo);
static FrameData *decodeFrame(JsonDictionary &json, DataInfo *dataInfo); static FrameData *decodeFrame(const rapidjson::Value& json, DataInfo *dataInfo);
static TextureData *decodeTexture(JsonDictionary &json); static TextureData *decodeTexture(const rapidjson::Value& json);
static ContourData *decodeContour(JsonDictionary &json); static ContourData *decodeContour(const rapidjson::Value& json);
static void decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo); static void decodeNode(BaseData *node, const rapidjson::Value& json, DataInfo *dataInfo);
protected: protected:
void loadData(); void loadData();

View File

@ -142,7 +142,7 @@ Color4B BaseData::getColor()
return Color4B(r, g, b, a); return Color4B(r, g, b, a);
} }
const std::string& DisplayData::changeDisplayToTexture(const std::string& displayName) const std::string DisplayData::changeDisplayToTexture(const std::string& displayName)
{ {
// remove .xxx // remove .xxx
std::string textureName = displayName; std::string textureName = displayName;
@ -153,7 +153,7 @@ const std::string& DisplayData::changeDisplayToTexture(const std::string& displa
textureName = textureName.erase(startPos); textureName = textureName.erase(startPos);
} }
return textureName.c_str(); return textureName;
} }
DisplayData::DisplayData(void) DisplayData::DisplayData(void)

Some files were not shown because too many files have changed in this diff Show More